gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds.scm.container; import static java.lang.Math.max; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.common.base.Preconditions; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Comparator; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor; import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationType; import org.apache.hadoop.hdds.scm.container.common.helpers.PipelineID; import org.apache.hadoop.util.Time; /** * Class wraps ozone container info. */ public class ContainerInfo implements Comparator<ContainerInfo>, Comparable<ContainerInfo>, Externalizable { private static final ObjectWriter WRITER; private static final String SERIALIZATION_ERROR_MSG = "Java serialization not" + " supported. Use protobuf instead."; static { ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); mapper .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); WRITER = mapper.writer(); } private HddsProtos.LifeCycleState state; @JsonIgnore private PipelineID pipelineID; private ReplicationFactor replicationFactor; private ReplicationType replicationType; private long usedBytes; private long numberOfKeys; private long lastUsed; // The wall-clock ms since the epoch at which the current state enters. private long stateEnterTime; private String owner; private long containerID; private long deleteTransactionId; /** * Allows you to maintain private data on ContainerInfo. This is not * serialized via protobuf, just allows us to maintain some private data. */ @JsonIgnore private byte[] data; ContainerInfo( long containerID, HddsProtos.LifeCycleState state, PipelineID pipelineID, long usedBytes, long numberOfKeys, long stateEnterTime, String owner, long deleteTransactionId, ReplicationFactor replicationFactor, ReplicationType repType) { this.containerID = containerID; this.pipelineID = pipelineID; this.usedBytes = usedBytes; this.numberOfKeys = numberOfKeys; this.lastUsed = Time.monotonicNow(); this.state = state; this.stateEnterTime = stateEnterTime; this.owner = owner; this.deleteTransactionId = deleteTransactionId; this.replicationFactor = replicationFactor; this.replicationType = repType; } public ContainerInfo(ContainerInfo info) { this(info.getContainerID(), info.getState(), info.getPipelineID(), info.getUsedBytes(), info.getNumberOfKeys(), info.getStateEnterTime(), info.getOwner(), info.getDeleteTransactionId(), info.getReplicationFactor(), info.getReplicationType()); } /** * Needed for serialization findbugs. */ public ContainerInfo() { } public static ContainerInfo fromProtobuf(HddsProtos.SCMContainerInfo info) { ContainerInfo.Builder builder = new ContainerInfo.Builder(); return builder.setPipelineID( PipelineID.getFromProtobuf(info.getPipelineID())) .setUsedBytes(info.getUsedBytes()) .setNumberOfKeys(info.getNumberOfKeys()) .setState(info.getState()) .setStateEnterTime(info.getStateEnterTime()) .setOwner(info.getOwner()) .setContainerID(info.getContainerID()) .setDeleteTransactionId(info.getDeleteTransactionId()) .setReplicationFactor(info.getReplicationFactor()) .setReplicationType(info.getReplicationType()) .build(); } public long getContainerID() { return containerID; } public HddsProtos.LifeCycleState getState() { return state; } public void setState(HddsProtos.LifeCycleState state) { this.state = state; } public long getStateEnterTime() { return stateEnterTime; } public ReplicationFactor getReplicationFactor() { return replicationFactor; } public PipelineID getPipelineID() { return pipelineID; } public long getUsedBytes() { return usedBytes; } public long getNumberOfKeys() { return numberOfKeys; } public long getDeleteTransactionId() { return deleteTransactionId; } public void updateDeleteTransactionId(long transactionId) { deleteTransactionId = max(transactionId, deleteTransactionId); } public ContainerID containerID() { return new ContainerID(getContainerID()); } /** * Gets the last used time from SCM's perspective. * * @return time in milliseconds. */ public long getLastUsed() { return lastUsed; } public ReplicationType getReplicationType() { return replicationType; } public void updateLastUsedTime() { lastUsed = Time.monotonicNow(); } public HddsProtos.SCMContainerInfo getProtobuf() { HddsProtos.SCMContainerInfo.Builder builder = HddsProtos.SCMContainerInfo.newBuilder(); Preconditions.checkState(containerID > 0); return builder.setContainerID(getContainerID()) .setUsedBytes(getUsedBytes()) .setNumberOfKeys(getNumberOfKeys()).setState(getState()) .setStateEnterTime(getStateEnterTime()).setContainerID(getContainerID()) .setDeleteTransactionId(getDeleteTransactionId()) .setPipelineID(getPipelineID().getProtobuf()) .setReplicationFactor(getReplicationFactor()) .setReplicationType(getReplicationType()) .setOwner(getOwner()) .build(); } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } @Override public String toString() { return "ContainerInfo{" + "id=" + containerID + ", state=" + state + ", pipelineID=" + pipelineID + ", stateEnterTime=" + stateEnterTime + ", owner=" + owner + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ContainerInfo that = (ContainerInfo) o; return new EqualsBuilder() .append(getContainerID(), that.getContainerID()) // TODO : Fix this later. If we add these factors some tests fail. // So Commenting this to continue and will enforce this with // Changes in pipeline where we remove Container Name to // SCMContainerinfo from Pipeline. // .append(pipeline.getFactor(), that.pipeline.getFactor()) // .append(pipeline.getType(), that.pipeline.getType()) .append(owner, that.owner) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(11, 811) .append(getContainerID()) .append(getOwner()) .toHashCode(); } /** * Compares its two arguments for order. Returns a negative integer, zero, or * a positive integer as the first argument is less than, equal to, or greater * than the second.<p> * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. * @throws NullPointerException if an argument is null and this comparator * does not permit null arguments * @throws ClassCastException if the arguments' types prevent them from * being compared by this comparator. */ @Override public int compare(ContainerInfo o1, ContainerInfo o2) { return Long.compare(o1.getLastUsed(), o2.getLastUsed()); } /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less than, * equal to, or greater than the specified object. * * @param o the object to be compared. * @return a negative integer, zero, or a positive integer as this object is * less than, equal to, or greater than the specified object. * @throws NullPointerException if the specified object is null * @throws ClassCastException if the specified object's type prevents it * from being compared to this object. */ @Override public int compareTo(ContainerInfo o) { return this.compare(this, o); } /** * Returns a JSON string of this object. * * @return String - json string * @throws IOException */ public String toJsonString() throws IOException { return WRITER.writeValueAsString(this); } /** * Returns private data that is set on this containerInfo. * * @return blob, the user can interpret it any way they like. */ public byte[] getData() { if (this.data != null) { return Arrays.copyOf(this.data, this.data.length); } else { return null; } } /** * Set private data on ContainerInfo object. * * @param data -- private data. */ public void setData(byte[] data) { if (data != null) { this.data = Arrays.copyOf(data, data.length); } } /** * Throws IOException as default java serialization is not supported. Use * serialization via protobuf instead. * * @param out the stream to write the object to * @throws IOException Includes any I/O exceptions that may occur * @serialData Overriding methods should use this tag to describe * the data layout of this Externalizable object. * List the sequence of element types and, if possible, * relate the element to a public/protected field and/or * method of this Externalizable class. */ @Override public void writeExternal(ObjectOutput out) throws IOException { throw new IOException(SERIALIZATION_ERROR_MSG); } /** * Throws IOException as default java serialization is not supported. Use * serialization via protobuf instead. * * @param in the stream to read data from in order to restore the object * @throws IOException if I/O errors occur * @throws ClassNotFoundException If the class for an object being * restored cannot be found. */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { throw new IOException(SERIALIZATION_ERROR_MSG); } /** * Builder class for ContainerInfo. */ public static class Builder { private HddsProtos.LifeCycleState state; private long used; private long keys; private long stateEnterTime; private String owner; private long containerID; private long deleteTransactionId; private PipelineID pipelineID; private ReplicationFactor replicationFactor; private ReplicationType replicationType; public Builder setReplicationType( ReplicationType repType) { this.replicationType = repType; return this; } public Builder setPipelineID(PipelineID pipelineId) { this.pipelineID = pipelineId; return this; } public Builder setReplicationFactor(ReplicationFactor repFactor) { this.replicationFactor = repFactor; return this; } public Builder setContainerID(long id) { Preconditions.checkState(id >= 0); this.containerID = id; return this; } public Builder setState(HddsProtos.LifeCycleState lifeCycleState) { this.state = lifeCycleState; return this; } public Builder setUsedBytes(long bytesUsed) { this.used = bytesUsed; return this; } public Builder setNumberOfKeys(long keyCount) { this.keys = keyCount; return this; } public Builder setStateEnterTime(long time) { this.stateEnterTime = time; return this; } public Builder setOwner(String containerOwner) { this.owner = containerOwner; return this; } public Builder setDeleteTransactionId(long deleteTransactionID) { this.deleteTransactionId = deleteTransactionID; return this; } public ContainerInfo build() { return new ContainerInfo(containerID, state, pipelineID, used, keys, stateEnterTime, owner, deleteTransactionId, replicationFactor, replicationType); } } /** * Check if a container is in open state, this will check if the * container is either open, allocated, creating or creating. * Any containers in these states is managed as an open container by SCM. */ public boolean isOpen() { return state == HddsProtos.LifeCycleState.ALLOCATED || state == HddsProtos.LifeCycleState.CREATING || state == HddsProtos.LifeCycleState.OPEN || state == HddsProtos.LifeCycleState.CLOSING; } }
package main.java.parsing; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import de.fhpotsdam.unfolding.data.Feature; import de.fhpotsdam.unfolding.data.PointFeature; import de.fhpotsdam.unfolding.data.ShapeFeature; import de.fhpotsdam.unfolding.geo.Location; import processing.core.PApplet; import processing.data.XML; public class ParseFeed { /* * This method is to parse a GeoRSS feed corresponding to earthquakes around * the globe. * * @param p - PApplet being used * @param fileName - file name or URL for data source */ public static List<PointFeature> parseEarthquake(PApplet p, String fileName) { List<PointFeature> features = new ArrayList<PointFeature>(); XML rss = p.loadXML(fileName); // Get all items XML[] itemXML = rss.getChildren("entry"); PointFeature point; for (int i = 0; i < itemXML.length; i++) { // get location and create feature Location location = getLocationFromPoint(itemXML[i]); // if successful create PointFeature and add to list if( location != null) { point = new PointFeature(location); features.add(point); } else { continue; } // Sets title if existing String titleStr = getStringVal(itemXML[i], "title"); if (titleStr != null) { point.putProperty("title", titleStr); // get magnitude from title point.putProperty("magnitude", Float.parseFloat(titleStr.substring(2, 5))); } // Sets depth(elevation) if existing float depthVal = getFloatVal(itemXML[i], "georss:elev"); // NOT SURE ABOUT CHECKING ERR CONDITION BECAUSE 0 COULD BE VALID? // get one decimal place when converting to km int interVal = (int)(depthVal/100); depthVal = (float) interVal/10; point.putProperty("depth", Math.abs((depthVal))); // Sets age if existing XML[] catXML = itemXML[i].getChildren("category"); for (int c = 0; c < catXML.length; c++) { String label = catXML[c].getString("label"); if ("Age".equals(label)) { String ageStr = catXML[c].getString("term"); point.putProperty("age", ageStr); } } } return features; } /* * Gets location from georss:point tag * * @param XML Node which has point as child * * @return Location object corresponding to point */ private static Location getLocationFromPoint(XML itemXML) { // set loc to null in case of failure Location loc = null; XML pointXML = itemXML.getChild("georss:point"); // set location if existing if (pointXML != null && pointXML.getContent() != null) { String pointStr = pointXML.getContent(); String[] latLon = pointStr.split(" "); float lat = Float.valueOf(latLon[0]); float lon = Float.valueOf(latLon[1]); loc = new Location(lat, lon); } return loc; } /* * Get String content from child node. */ private static String getStringVal(XML itemXML, String tagName) { // Sets title if existing String str = null; XML strXML = itemXML.getChild(tagName); // check if node exists and has content if (strXML != null && strXML.getContent() != null) { str = strXML.getContent(); } return str; } /* * Get float value from child node */ private static float getFloatVal(XML itemXML, String tagName) { return Float.parseFloat(getStringVal(itemXML, tagName)); } /* * This method is to parse a file containing airport information. * The file and its format can be found: * http://openflights.org/data.html#airport * * It is also included with the UC San Diego MOOC package in the file airports.dat * * @param p - PApplet being used * @param fileName - file name or URL for data source */ public static List<PointFeature> parseAirports(PApplet p, String fileName) { List<PointFeature> features = new ArrayList<PointFeature>(); String[] rows = p.loadStrings(fileName); for (String row : rows) { // hot-fix for altitude when lat lon out of place int i = 0; // split row by commas not in quotations String[] columns = row.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); // get location and create feature //System.out.println(columns[6]); float lat = Float.parseFloat(columns[6]); float lon = Float.parseFloat(columns[7]); Location loc = new Location(lat, lon); PointFeature point = new PointFeature(loc); // set ID to OpenFlights unique identifier point.setId(columns[0]); // get other fields from csv point.addProperty("name", columns[1]); point.putProperty("city", columns[2]); point.putProperty("country", columns[3]); // pretty sure IATA/FAA is used in routes.dat // get airport IATA/FAA code if(!columns[4].equals("")) { point.putProperty("code", columns[4]); } // get airport ICAO code if no IATA else if(!columns[5].equals("")) { point.putProperty("code", columns[5]); } point.putProperty("altitude", columns[8 + i]); features.add(point); } return features; } /* * This method is to parse a file containing airport route information. * The file and its format can be found: * http://openflights.org/data.html#route * * It is also included with the UC San Diego MOOC package in the file routes.dat * * @param p - PApplet being used * @param fileName - file name or URL for data source */ public static List<ShapeFeature> parseRoutes(PApplet p, String fileName) { List<ShapeFeature> routes = new ArrayList<ShapeFeature>(); String[] rows = p.loadStrings(fileName); for(String row : rows) { String[] columns = row.split(","); ShapeFeature route = new ShapeFeature(Feature.FeatureType.LINES); // set id to be OpenFlights identifier for source airport // check that both airports on route have OpenFlights Identifier if(!columns[3].equals("\\N") && !columns[5].equals("\\N")){ // set "source" property to be OpenFlights identifier for source airport route.putProperty("source", columns[3]); // "destination property" -- OpenFlights identifier route.putProperty("destination", columns[5]); routes.add(route); } } return routes; } /* * This method is to parse a file containing life expectancy information from * the world bank. * The file and its format can be found: * http://data.worldbank.org/indicator/SP.DYN.LE00.IN * * It is also included with the UC San Diego MOOC package * in the file LifeExpectancyWorldBank.csv * * @param p - PApplet being used * @param fileName - file name or URL for data source * @return A HashMap of country->average age of death */ public static HashMap<String, Float> loadLifeExpectancyFromCSV(PApplet p, String fileName) { // HashMap key: country ID and data: lifeExp at birth HashMap<String, Float> lifeExpMap = new HashMap<String, Float>(); // get lines of csv file String[] rows = p.loadStrings(fileName); // Reads country name and population density value from CSV row for (String row : rows) { // split row by commas not in quotations String[] columns = row.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); // check if there is any life expectancy data from any year, get most recent /* * EXTENSION: Add code to also get the year the data is from. * You may want to use a list of Floats as the values for the HashMap * and store the year as the second value. (There are many other ways to do this) */ // for(int i = columns.length - 1; i > 3; i--) { // check if value exists for year if(!columns[i].equals("..")) { lifeExpMap.put(columns[3], Float.parseFloat(columns[i])); // break once most recent data is found break; } } } return lifeExpMap; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution; import com.facebook.presto.OutputBuffers; import com.facebook.presto.Session; import com.facebook.presto.memory.MemoryPool; import com.facebook.presto.memory.MemoryPoolId; import com.facebook.presto.memory.QueryContext; import com.facebook.presto.metadata.Split; import com.facebook.presto.metadata.TableHandle; import com.facebook.presto.operator.TaskContext; import com.facebook.presto.spi.Node; import com.facebook.presto.spi.TupleDomain; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.planner.PlanFragment; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.TestingColumnHandle; import com.facebook.presto.sql.planner.TestingTableHandle; import com.facebook.presto.sql.planner.plan.PlanFragmentId; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.facebook.presto.sql.planner.plan.TableScanNode; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import io.airlift.units.DataSize; import org.joda.time.DateTime; import javax.annotation.concurrent.GuardedBy; import java.net.URI; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.execution.StateMachine.StateChangeListener; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.util.Failures.toFailures; import static io.airlift.units.DataSize.Unit.GIGABYTE; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.util.Objects.requireNonNull; public class MockRemoteTaskFactory implements RemoteTaskFactory { private final Executor executor; public MockRemoteTaskFactory(Executor executor) { this.executor = executor; } public RemoteTask createTableScanTask(Node newNode, List<Split> splits) { TaskId taskId = new TaskId(new StageId("test", "1"), "1"); Symbol symbol = new Symbol("column"); PlanNodeId tableScanNodeId = new PlanNodeId("test"); PlanNodeId sourceId = new PlanNodeId("sourceId"); PlanFragment testFragment = new PlanFragment( new PlanFragmentId("test"), new TableScanNode( new PlanNodeId("test"), new TableHandle("test", new TestingTableHandle()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null), ImmutableMap.<Symbol, Type>of(symbol, VARCHAR), ImmutableList.of(symbol), PlanFragment.PlanDistribution.SOURCE, tableScanNodeId, PlanFragment.OutputPartitioning.NONE, Optional.empty(), Optional.empty(), Optional.empty() ); ImmutableMultimap.Builder<PlanNodeId, Split> initialSplits = ImmutableMultimap.builder(); for (Split sourceSplit : splits) { initialSplits.put(sourceId, sourceSplit); } return createRemoteTask(TEST_SESSION, taskId, newNode, testFragment, initialSplits.build(), OutputBuffers.INITIAL_EMPTY_OUTPUT_BUFFERS); } @Override public RemoteTask createRemoteTask( Session session, TaskId taskId, Node node, PlanFragment fragment, Multimap<PlanNodeId, Split> initialSplits, OutputBuffers outputBuffers) { return new MockRemoteTask(taskId, fragment, node.getNodeIdentifier(), executor, initialSplits); } public static class MockRemoteTask implements RemoteTask { private final AtomicLong nextTaskInfoVersion = new AtomicLong(TaskInfo.STARTING_VERSION); private final URI location; private final TaskStateMachine taskStateMachine; private final TaskContext taskContext; private final SharedBuffer sharedBuffer; private final String nodeId; private final PlanFragment fragment; @GuardedBy("this") private final Set<PlanNodeId> noMoreSplits = new HashSet<>(); @GuardedBy("this") private final Multimap<PlanNodeId, Split> splits = HashMultimap.create(); public MockRemoteTask(TaskId taskId, PlanFragment fragment, String nodeId, Executor executor, Multimap<PlanNodeId, Split> initialSplits) { this.taskStateMachine = new TaskStateMachine(requireNonNull(taskId, "taskId is null"), requireNonNull(executor, "executor is null")); MemoryPool memoryPool = new MemoryPool(new MemoryPoolId("test"), new DataSize(1, GIGABYTE)); MemoryPool memorySystemPool = new MemoryPool(new MemoryPoolId("testSystem"), new DataSize(1, GIGABYTE)); this.taskContext = new QueryContext(taskId.getQueryId(), new DataSize(1, MEGABYTE), memoryPool, memorySystemPool, executor).addTaskContext(taskStateMachine, TEST_SESSION, new DataSize(1, MEGABYTE), true, true); this.location = URI.create("fake://task/" + taskId); this.sharedBuffer = new SharedBuffer(taskId, executor, requireNonNull(new DataSize(1, DataSize.Unit.BYTE), "maxBufferSize is null")); this.fragment = requireNonNull(fragment, "fragment is null"); this.nodeId = requireNonNull(nodeId, "nodeId is null"); splits.putAll(initialSplits); } @Override public TaskId getTaskId() { return taskStateMachine.getTaskId(); } @Override public String getNodeId() { return nodeId; } @Override public TaskInfo getTaskInfo() { TaskState state = taskStateMachine.getState(); List<ExecutionFailureInfo> failures = ImmutableList.of(); if (state == TaskState.FAILED) { failures = toFailures(taskStateMachine.getFailureCauses()); } return new TaskInfo( taskStateMachine.getTaskId(), Optional.empty(), nextTaskInfoVersion.getAndIncrement(), state, location, DateTime.now(), sharedBuffer.getInfo(), ImmutableSet.<PlanNodeId>of(), taskContext.getTaskStats(), failures); } public void clearSplits() { splits.clear(); } @Override public void start() { } @Override public void addSplits(PlanNodeId sourceId, Iterable<Split> splits) { requireNonNull(splits, "splits is null"); for (Split split : splits) { this.splits.put(sourceId, split); } } @Override public void noMoreSplits(PlanNodeId sourceId) { noMoreSplits.add(sourceId); boolean allSourcesComplete = Stream.concat(Stream.of(fragment.getPartitionedSourceNode()), fragment.getRemoteSourceNodes().stream()) .filter(Objects::nonNull) .map(PlanNode::getId) .allMatch(noMoreSplits::contains); if (allSourcesComplete) { taskStateMachine.finished(); } } @Override public void setOutputBuffers(OutputBuffers outputBuffers) { sharedBuffer.setOutputBuffers(outputBuffers); } @Override public void addStateChangeListener(StateChangeListener<TaskInfo> stateChangeListener) { taskStateMachine.addStateChangeListener(newValue -> stateChangeListener.stateChanged(getTaskInfo())); } @Override public CompletableFuture<TaskInfo> getStateChange(TaskInfo taskInfo) { return taskStateMachine.getStateChange(taskInfo.getState()).thenApply(ignored -> getTaskInfo()); } @Override public void cancel() { taskStateMachine.cancel(); } @Override public void abort() { taskStateMachine.abort(); } @Override public int getPartitionedSplitCount() { if (taskStateMachine.getState().isDone()) { return 0; } return splits.size(); } @Override public int getQueuedPartitionedSplitCount() { if (taskStateMachine.getState().isDone()) { return 0; } return splits.size(); } } }
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.distort; import boofcv.alg.interpolate.InterpolatePixelS; import boofcv.concurrency.BoofConcurrency; import boofcv.struct.distort.PixelTransform; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageGray; import georegression.struct.point.Point2D_F32; import java.util.ArrayDeque; /** * Except for very simple functions, computing the per pixel distortion is an expensive operation. * To overcome this problem the distortion is computed once and cached. Then when the image is distorted * again the save results are simply recalled and not computed again. * * @author Peter Abeles */ public class ImageDistortCache_SB_MT<Input extends ImageGray<Input>, Output extends ImageGray<Output>> extends ImageDistortCache_SB<Input, Output> { private final ArrayDeque<BlockDistort> queue = new ArrayDeque<>(); /** * Specifies configuration parameters * * @param interp Interpolation algorithm */ public ImageDistortCache_SB_MT( AssignPixelValue_SB<Output> assigner, InterpolatePixelS<Input> interp ) { super(assigner, interp); } private BlockDistort pop() { synchronized (queue) { if (queue.isEmpty()) { return new BlockDistort(); } else { return queue.pop(); } } } private void recycle( BlockDistort b ) { synchronized (queue) { queue.push(b); } } @Override protected void init( Input srcImg, Output dstImg ) { if (dirty || width != dstImg.width || height != dstImg.height) { width = dstImg.width; height = dstImg.height; map = new Point2D_F32[width*height]; for (int i = 0; i < map.length; i++) { map[i] = new Point2D_F32(); } BoofConcurrency.loopBlocks(0, height, ( y0, y1 ) -> { PixelTransform<Point2D_F32> dstToSrc = this.dstToSrc.copyConcurrent(); for (int y = y0; y < y1; y++) { int index = y*width; for (int x = 0; x < width; x++) { dstToSrc.compute(x, y, map[index++]); } } }); dirty = false; } else if (dstImg.width != width || dstImg.height != height) throw new IllegalArgumentException("Unexpected dstImg dimension"); this.srcImg = srcImg; this.dstImg = dstImg; interp.setImage(srcImg); assigner.setImage(dstImg); } @Override protected void renderAll() { BoofConcurrency.loopBlocks(y0, y1, ( y0, y1 ) -> { BlockDistort b = pop(); b.applyAll(y0, y1); recycle(b); }); } @Override protected void renderAll( GrayU8 mask ) { BoofConcurrency.loopBlocks(y0, y1, ( y0, y1 ) -> { BlockDistort b = pop(); b.applyAll(y0, y1, mask); recycle(b); }); } @Override protected void applyOnlyInside() { BoofConcurrency.loopBlocks(y0, y1, ( y0, y1 ) -> { BlockDistort b = pop(); b.applyOnlyInside(y0, y1); recycle(b); }); } @Override protected void applyOnlyInside( GrayU8 mask ) { BoofConcurrency.loopBlocks(y0, y1, ( y0, y1 ) -> { BlockDistort b = pop(); b.applyOnlyInside(y0, y1, mask); recycle(b); }); } private class BlockDistort { InterpolatePixelS<Input> interp = ImageDistortCache_SB_MT.this.interp.copy(); public void init() { interp.setImage(srcImg); } void applyAll( int y0, int y1 ) { init(); for (int y = y0; y < y1; y++) { int indexDst = dstImg.startIndex + dstImg.stride*y + x0; for (int x = x0; x < x1; x++, indexDst++) { Point2D_F32 s = map[indexDst]; assigner.assign(indexDst, interp.get(s.x, s.y)); } } } void applyAll( int y0, int y1, GrayU8 mask ) { init(); float maxWidth = srcImg.getWidth() - 1; float maxHeight = srcImg.getHeight() - 1; for (int y = y0; y < y1; y++) { int indexDst = dstImg.startIndex + dstImg.stride*y + x0; int indexMsk = mask.startIndex + mask.stride*y + x0; for (int x = x0; x < x1; x++, indexDst++, indexMsk++) { Point2D_F32 s = map[indexDst]; assigner.assign(indexDst, interp.get(s.x, s.y)); if (s.x >= 0 && s.x <= maxWidth && s.y >= 0 && s.y <= maxHeight) { mask.data[indexMsk] = 1; } else { mask.data[indexMsk] = 0; } } } } void applyOnlyInside( int y0, int y1 ) { init(); float maxWidth = srcImg.getWidth() - 1; float maxHeight = srcImg.getHeight() - 1; for (int y = y0; y < y1; y++) { int indexDst = dstImg.startIndex + dstImg.stride*y + x0; for (int x = x0; x < x1; x++, indexDst++) { Point2D_F32 s = map[indexDst]; if (s.x >= 0 && s.x <= maxWidth && s.y >= 0 && s.y <= maxHeight) { assigner.assign(indexDst, interp.get(s.x, s.y)); } } } } void applyOnlyInside( int y0, int y1, GrayU8 mask ) { init(); float maxWidth = srcImg.getWidth() - 1; float maxHeight = srcImg.getHeight() - 1; for (int y = y0; y < y1; y++) { int indexDst = dstImg.startIndex + dstImg.stride*y + x0; int indexMsk = mask.startIndex + mask.stride*y + x0; for (int x = x0; x < x1; x++, indexDst++, indexMsk++) { Point2D_F32 s = map[indexDst]; if (s.x >= 0 && s.x <= maxWidth && s.y >= 0 && s.y <= maxHeight) { assigner.assign(indexDst, interp.get(s.x, s.y)); mask.data[indexMsk] = 1; } else { mask.data[indexMsk] = 0; } } } } } }
/* * The Gemma project * * Copyright (c) 2008 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.web.controller.common; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import ubic.gemma.core.job.executor.webapp.TaskRunningService; import ubic.gemma.core.tasks.maintenance.CharacteristicUpdateCommand; import ubic.gemma.core.util.AnchorTagUtil; import ubic.gemma.model.association.phenotype.PhenotypeAssociation; import ubic.gemma.model.common.description.AnnotationValueObject; import ubic.gemma.model.common.description.Characteristic; import ubic.gemma.model.expression.biomaterial.BioMaterial; import ubic.gemma.model.expression.experiment.ExperimentalFactor; import ubic.gemma.model.expression.experiment.ExpressionExperiment; import ubic.gemma.model.expression.experiment.FactorValue; import ubic.gemma.persistence.service.common.description.CharacteristicService; import ubic.gemma.persistence.service.expression.experiment.ExperimentalDesignService; import ubic.gemma.persistence.service.expression.experiment.ExpressionExperimentService; import ubic.gemma.persistence.service.expression.experiment.FactorValueService; import ubic.gemma.web.remote.JsonReaderResponse; import ubic.gemma.web.remote.ListBatchCommand; import java.util.*; /** * NOTE: Logging messages from this service are important for tracking changes to annotations. * * @author luke * @author paul * @see ubic.gemma.web.controller.expression.experiment.AnnotationController for related methods. */ @Controller public class CharacteristicBrowserController { private static final Log log = LogFactory.getLog( CharacteristicBrowserController.class.getName() ); private static final int MAX_RESULTS = 2000; @Autowired private TaskRunningService taskRunningService; @Autowired private ExperimentalDesignService experimentalDesignService; @Autowired private ExpressionExperimentService expressionExperimentService; @Autowired private FactorValueService factorValueService; @Autowired private CharacteristicService characteristicService; public JsonReaderResponse<AnnotationValueObject> browse( ListBatchCommand batch ) { Integer count = characteristicService.countAll(); List<AnnotationValueObject> results = new ArrayList<>(); Collection<Characteristic> records; if ( StringUtils.isNotBlank( batch.getSort() ) ) { String o = batch.getSort(); String orderBy; switch ( o ) { case "className": orderBy = "category"; break; case "termName": orderBy = "value"; break; case "evidenceCode": orderBy = "evidenceCode"; break; default: throw new IllegalArgumentException( "Unknown sort field: " + o ); } boolean descending = batch.getDir() != null && batch.getDir().equalsIgnoreCase( "DESC" ); records = characteristicService.browse( batch.getStart(), batch.getLimit(), orderBy, descending ); } else { records = characteristicService.browse( batch.getStart(), batch.getLimit() ); } Map<Characteristic, Object> charToParent = characteristicService.getParents( records ); for ( Object o : records ) { Characteristic c = ( Characteristic ) o; Object parent = charToParent.get( c ); AnnotationValueObject avo = new AnnotationValueObject(); avo.setId( c.getId() ); avo.setClassName( c.getCategory() ); avo.setTermName( c.getValue() ); if ( c.getEvidenceCode() != null ) avo.setEvidenceCode( c.getEvidenceCode().toString() ); populateClassValues( c, avo ); if ( parent != null ) { populateParentInformation( avo, parent ); } results.add( avo ); } return new JsonReaderResponse<>( results, count ); } private void populateClassValues( Characteristic c, AnnotationValueObject avo ) { avo.setClassUri( c.getCategoryUri() ); avo.setTermUri( c.getValueUri() ); avo.setObjectClass( Characteristic.class.getSimpleName() ); } public Integer count() { return characteristicService.countAll(); } public Collection<AnnotationValueObject> findCharacteristics( String valuePrefix ) { return findCharacteristicsCustom( valuePrefix, true, true, true, true, true, true, false ); } /** * @param searchFVs Search factor values that lack characteristics -- that is, search the factorValue.value. * @param searchCategories Should the Category be searched, not just the Value? */ public Collection<AnnotationValueObject> findCharacteristicsCustom( String queryString, boolean searchNos, boolean searchEEs, boolean searchBMs, boolean searchFVs, boolean searchPAs, boolean searchFVVs, boolean searchCategories ) { List<AnnotationValueObject> results = new ArrayList<>(); if ( StringUtils.isBlank( queryString ) ) { return results; } Collection<Characteristic> chars = new HashSet<>(); if ( queryString.startsWith( "http://" ) ) { chars = characteristicService.findByUri( queryString ); } else { chars = characteristicService.findByValue( queryString ); if ( searchCategories ) { chars.addAll( characteristicService.findByCategory( queryString ) ); } } Map<Characteristic, Object> charToParent = characteristicService.getParents( chars ); for ( Object o : chars ) { Characteristic c = ( Characteristic ) o; Object parent = charToParent.get( c ); if ( ( searchEEs && parent instanceof ExpressionExperiment ) || ( searchBMs && parent instanceof BioMaterial ) || ( searchFVs && ( parent instanceof FactorValue || parent instanceof ExperimentalFactor ) ) || ( searchNos && parent == null ) || ( searchPAs && parent instanceof PhenotypeAssociation ) ) { AnnotationValueObject avo = new AnnotationValueObject(); avo.setId( c.getId() ); avo.setClassName( c.getCategory() ); avo.setTermName( c.getValue() ); if ( c.getEvidenceCode() != null ) avo.setEvidenceCode( c.getEvidenceCode().toString() ); populateClassValues( c, avo ); if ( parent != null ) { populateParentInformation( avo, parent ); } results.add( avo ); if ( results.size() >= MAX_RESULTS ) { break; } } } if ( results.size() < MAX_RESULTS && searchFVVs ) { // non-characteristics. Collection<FactorValue> factorValues = factorValueService.findByValue( queryString ); for ( FactorValue factorValue : factorValues ) { if ( factorValue.getCharacteristics().size() > 0 ) continue; if ( StringUtils.isBlank( factorValue.getValue() ) ) continue; AnnotationValueObject avo = new AnnotationValueObject(); avo.setId( factorValue.getId() ); avo.setTermName( factorValue.getValue() ); avo.setObjectClass( FactorValue.class.getSimpleName() ); populateParentInformation( avo, factorValue ); results.add( avo ); } } log.info( "Characteristic search for: '" + queryString + "*': " + results.size() + " results, returning up to " + MAX_RESULTS ); return results.subList( 0, Math.min( results.size(), MAX_RESULTS ) ); } @RequestMapping(value = "/characteristicBrowser.html", method = RequestMethod.GET) public String getView() { return "characteristics"; } public void removeCharacteristics( Collection<AnnotationValueObject> chars ) { CharacteristicUpdateCommand c = new CharacteristicUpdateCommand(); c.setAnnotationValueObjects( chars ); c.setRemove( true ); taskRunningService.submitLocalTask( c ); } /** * Update characteristics associated with entities. This allows for the case of factor values that we are adding * characteristics to for the first time, but the most common case is altering existing characteristics. */ public void updateCharacteristics( Collection<AnnotationValueObject> avos ) { CharacteristicUpdateCommand c = new CharacteristicUpdateCommand(); c.setAnnotationValueObjects( avos ); c.setRemove( false ); taskRunningService.submitLocalTask( c ); } /** * @param avo * @param annotatedItem - the object that has the annotation, we want to find who "owns" it. */ private void populateParentInformation( AnnotationValueObject avo, Object annotatedItem ) { assert avo != null; if ( annotatedItem == null ) { avo.setParentLink( "[Parent hidden or not available, " + avo.getObjectClass() + " ID=" + avo.getId() + "]" ); } else if ( annotatedItem instanceof ExpressionExperiment ) { ExpressionExperiment ee = ( ExpressionExperiment ) annotatedItem; avo.setParentName( String.format( "Experiment: %s", ee.getName() ) ); avo.setParentLink( AnchorTagUtil.getExpressionExperimentLink( ee.getId(), avo.getParentName() ) ); } else if ( annotatedItem instanceof BioMaterial ) { BioMaterial bm = ( BioMaterial ) annotatedItem; avo.setParentName( String.format( "BioMat: %s", bm.getName() ) ); avo.setParentLink( AnchorTagUtil.getBioMaterialLink( bm.getId(), avo.getParentName() ) ); ExpressionExperiment ee = expressionExperimentService.findByBioMaterial( bm ); if ( ee == null ) { log.warn( "Expression experiment for " + bm + " was null" ); return; } avo.setParentOfParentName( String.format( "%s", ee.getName() ) ); // avo.setParentOfParentDescription( ee.getDescription() ); avo.setParentOfParentLink( AnchorTagUtil.getExpressionExperimentLink( ee.getId(), avo.getParentOfParentName() ) ); } else if ( annotatedItem instanceof FactorValue ) { FactorValue fv = ( FactorValue ) annotatedItem; avo.setParentDescription( String.format( "FactorValue: %s &laquo; Exp.Factor: %s", ( fv.getValue() == null ? "" : ": " + fv.getValue() ), fv.getExperimentalFactor().getName() ) ); ExpressionExperiment ee = expressionExperimentService.findByFactorValue( fv ); if ( ee == null ) { log.warn( "Expression experiment for " + fv + " was null" ); return; } avo.setParentOfParentName( String.format( "Experimental Design for: %s", ee.getName() ) ); avo.setParentOfParentLink( AnchorTagUtil .getExperimentalDesignLink( fv.getExperimentalFactor().getExperimentalDesign().getId(), avo.getParentName() ) + "&nbsp;&laquo;&nbsp;" + AnchorTagUtil .getExpressionExperimentLink( ee.getId(), String.format( "%s (%s)", StringUtils.abbreviate( ee.getName(), 80 ), ee.getShortName() ) ) ); } else if ( annotatedItem instanceof ExperimentalFactor ) { ExperimentalFactor ef = ( ExperimentalFactor ) annotatedItem; avo.setParentLink( AnchorTagUtil.getExperimentalDesignLink( ef.getExperimentalDesign().getId(), "Exp Fac: " + ef.getName() + " (" + StringUtils.abbreviate( ef.getDescription(), 50 ) + ")" ) ); ExpressionExperiment ee = experimentalDesignService.getExpressionExperiment( ef.getExperimentalDesign() ); if ( ee == null ) { log.warn( "Expression experiment for " + ef + " was null" ); return; } avo.setParentOfParentName( String.format( "%s (%s)", StringUtils.abbreviate( ee.getName(), 80 ), ee.getShortName() ) ); avo.setParentOfParentLink( AnchorTagUtil.getExpressionExperimentLink( ee.getId(), avo.getParentOfParentName() ) ); } else if ( annotatedItem instanceof PhenotypeAssociation ) { PhenotypeAssociation pa = ( PhenotypeAssociation ) annotatedItem; avo.setParentLink( "PhenotypeAssoc: " + pa.getGene().getOfficialSymbol() ); avo.setParentDescription( pa.getId().toString() ); } } }
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.metadata.sys; import com.google.common.collect.ImmutableList; import io.crate.analyze.WhereClause; import io.crate.metadata.*; import io.crate.metadata.shard.unassigned.UnassignedShard; import io.crate.types.*; import org.elasticsearch.action.NoShardAvailableActionException; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.routing.GroupShardsIterator; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Singleton; import org.elasticsearch.index.shard.ShardId; import javax.annotation.Nullable; import java.util.*; @Singleton public class SysShardsTableInfo extends SysTableInfo { public static final TableIdent IDENT = new TableIdent(SCHEMA, "shards"); private final Map<ColumnIdent, ReferenceInfo> infos; private final Set<ReferenceInfo> columns; public static class Columns { public static final ColumnIdent ID = new ColumnIdent("id"); public static final ColumnIdent SCHEMA_NAME = new ColumnIdent("schema_name"); public static final ColumnIdent TABLE_NAME = new ColumnIdent("table_name"); public static final ColumnIdent PARTITION_IDENT = new ColumnIdent("partition_ident"); public static final ColumnIdent NUM_DOCS = new ColumnIdent("num_docs"); public static final ColumnIdent PRIMARY = new ColumnIdent("primary"); public static final ColumnIdent RELOCATING_NODE = new ColumnIdent("relocating_node"); public static final ColumnIdent SIZE = new ColumnIdent("size"); public static final ColumnIdent STATE = new ColumnIdent("state"); public static final ColumnIdent ROUTING_STATE = new ColumnIdent("routing_state"); public static final ColumnIdent ORPHAN_PARTITION = new ColumnIdent("orphan_partition"); public static final ColumnIdent RECOVERY = new ColumnIdent("recovery"); public static final ColumnIdent RECOVERY_STAGE = new ColumnIdent("recovery", ImmutableList.of("stage")); public static final ColumnIdent RECOVERY_TYPE = new ColumnIdent("recovery", ImmutableList.of("type")); public static final ColumnIdent RECOVERY_TOTAL_TIME = new ColumnIdent("recovery", ImmutableList.of("total_time")); public static final ColumnIdent RECOVERY_FILES = new ColumnIdent("recovery", ImmutableList.of("files")); public static final ColumnIdent RECOVERY_FILES_USED = new ColumnIdent("recovery", ImmutableList.of("files", "used")); public static final ColumnIdent RECOVERY_FILES_REUSED = new ColumnIdent("recovery", ImmutableList.of("files", "reused")); public static final ColumnIdent RECOVERY_FILES_RECOVERED = new ColumnIdent("recovery", ImmutableList.of("files", "recovered")); public static final ColumnIdent RECOVERY_FILES_PERCENT = new ColumnIdent("recovery", ImmutableList.of("files", "percent")); public static final ColumnIdent RECOVERY_SIZE = new ColumnIdent("recovery", ImmutableList.of("size")); public static final ColumnIdent RECOVERY_SIZE_USED = new ColumnIdent("recovery", ImmutableList.of("size", "used")); public static final ColumnIdent RECOVERY_SIZE_REUSED = new ColumnIdent("recovery", ImmutableList.of("size", "reused")); public static final ColumnIdent RECOVERY_SIZE_RECOVERED = new ColumnIdent("recovery", ImmutableList.of("size", "recovered")); public static final ColumnIdent RECOVERY_SIZE_PERCENT = new ColumnIdent("recovery", ImmutableList.of("size", "percent")); } public static class ReferenceIdents { public static final ReferenceIdent ID = new ReferenceIdent(IDENT, Columns.ID); public static final ReferenceIdent SCHEMA_NAME = new ReferenceIdent(IDENT, Columns.SCHEMA_NAME); public static final ReferenceIdent TABLE_NAME = new ReferenceIdent(IDENT, Columns.TABLE_NAME); public static final ReferenceIdent PARTITION_IDENT = new ReferenceIdent(IDENT, Columns.PARTITION_IDENT); public static final ReferenceIdent NUM_DOCS = new ReferenceIdent(IDENT, Columns.NUM_DOCS); public static final ReferenceIdent PRIMARY = new ReferenceIdent(IDENT, Columns.PRIMARY); public static final ReferenceIdent RELOCATING_NODE = new ReferenceIdent(IDENT, Columns.RELOCATING_NODE); public static final ReferenceIdent SIZE = new ReferenceIdent(IDENT, Columns.SIZE); public static final ReferenceIdent STATE = new ReferenceIdent(IDENT, Columns.STATE); public static final ReferenceIdent ROUTING_STATE = new ReferenceIdent(IDENT, Columns.ROUTING_STATE); public static final ReferenceIdent ORPHAN_PARTITION = new ReferenceIdent(IDENT, Columns.ORPHAN_PARTITION); public static final ReferenceIdent RECOVERY = new ReferenceIdent(IDENT, Columns.RECOVERY); } private static final ImmutableList<ColumnIdent> primaryKey = ImmutableList.of( Columns.SCHEMA_NAME, Columns.TABLE_NAME, Columns.ID, Columns.PARTITION_IDENT ); private final TableColumn nodesTableColumn; @Inject public SysShardsTableInfo(ClusterService service, SysNodesTableInfo sysNodesTableInfo) { super(service); nodesTableColumn = sysNodesTableInfo.tableColumn(); ColumnRegistrar registrar = new ColumnRegistrar(IDENT, RowGranularity.SHARD) .register(Columns.SCHEMA_NAME, StringType.INSTANCE) .register(Columns.TABLE_NAME, StringType.INSTANCE) .register(Columns.ID, IntegerType.INSTANCE) .register(Columns.PARTITION_IDENT, StringType.INSTANCE) .register(Columns.NUM_DOCS, LongType.INSTANCE) .register(Columns.PRIMARY, BooleanType.INSTANCE) .register(Columns.RELOCATING_NODE, StringType.INSTANCE) .register(Columns.SIZE, LongType.INSTANCE) .register(Columns.STATE, StringType.INSTANCE) .register(Columns.ROUTING_STATE, StringType.INSTANCE) .register(Columns.ORPHAN_PARTITION, BooleanType.INSTANCE) .register(Columns.RECOVERY, ObjectType.INSTANCE) .register(Columns.RECOVERY_STAGE, StringType.INSTANCE) .register(Columns.RECOVERY_TYPE, StringType.INSTANCE) .register(Columns.RECOVERY_TOTAL_TIME, LongType.INSTANCE) .register(Columns.RECOVERY_SIZE, ObjectType.INSTANCE) .register(Columns.RECOVERY_SIZE_USED, LongType.INSTANCE) .register(Columns.RECOVERY_SIZE_REUSED, LongType.INSTANCE) .register(Columns.RECOVERY_SIZE_RECOVERED, LongType.INSTANCE) .register(Columns.RECOVERY_SIZE_PERCENT, FloatType.INSTANCE) .register(Columns.RECOVERY_FILES, ObjectType.INSTANCE) .register(Columns.RECOVERY_FILES_USED, IntegerType.INSTANCE) .register(Columns.RECOVERY_FILES_REUSED, IntegerType.INSTANCE) .register(Columns.RECOVERY_FILES_RECOVERED, IntegerType.INSTANCE) .register(Columns.RECOVERY_FILES_PERCENT, FloatType.INSTANCE) .putInfoOnly(SysNodesTableInfo.SYS_COL_IDENT, SysNodesTableInfo.tableColumnInfo(IDENT)); infos = registrar.infos(); columns = registrar.columns(); } @Override public ReferenceInfo getReferenceInfo(ColumnIdent columnIdent) { ReferenceInfo info = infos.get(columnIdent); if (info == null) { return nodesTableColumn.getReferenceInfo(this.ident(), columnIdent); } return info; } @Override public Collection<ReferenceInfo> columns() { return columns; } private void processShardRouting(Map<String, Map<String, List<Integer>>> routing, ShardRouting shardRouting, ShardId shardId) { String node; int id; String index = shardId.getIndex(); if (shardRouting == null) { node = clusterService.localNode().id(); id = UnassignedShard.markUnassigned(shardId.id()); } else { node = shardRouting.currentNodeId(); id = shardRouting.id(); } Map<String, List<Integer>> nodeMap = routing.get(node); if (nodeMap == null) { nodeMap = new TreeMap<>(); routing.put(node, nodeMap); } List<Integer> shards = nodeMap.get(index); if (shards == null) { shards = new ArrayList<>(); nodeMap.put(index, shards); } shards.add(id); } @Override public RowGranularity rowGranularity() { return RowGranularity.SHARD; } @Override public TableIdent ident() { return IDENT; } /** * Retrieves the routing for sys.shards * * This routing contains ALL shards of ALL indices. * Any shards that are not yet assigned to a node will have a NEGATIVE shard id (see {@link UnassignedShard} */ @Override public Routing getRouting(WhereClause whereClause, @Nullable String preference) { // TODO: filter on whereClause Map<String, Map<String, List<Integer>>> locations = new TreeMap<>(); String[] concreteIndices = clusterService.state().metaData().concreteAllIndices(); GroupShardsIterator groupShardsIterator = clusterService.state().getRoutingTable().allAssignedShardsGrouped(concreteIndices, true, true); for (final ShardIterator shardIt : groupShardsIterator) { final ShardRouting shardRouting = shardIt.nextOrNull(); processShardRouting(locations, shardRouting, shardIt.shardId()); } return new Routing(locations); } @Override public List<ColumnIdent> primaryKey() { return primaryKey; } @Override public Iterator<ReferenceInfo> iterator() { return infos.values().iterator(); } }
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.operation.collect; import io.crate.core.collections.BlockingEvictingQueue; import io.crate.core.collections.NoopQueue; import io.crate.metadata.settings.CrateSettings; import io.crate.operation.reference.sys.job.JobContext; import io.crate.operation.reference.sys.job.JobContextLog; import io.crate.operation.reference.sys.operation.OperationContext; import io.crate.operation.reference.sys.operation.OperationContextLog; import jsr166e.LongAdder; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Singleton; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.settings.NodeSettingsService; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import java.util.Map; import java.util.Queue; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; /** * Stats tables that are globally available on each node and contain meta data of the cluster * like active jobs * * injected via guice instead of using static so that if two nodes run * in the same jvm the memoryTables aren't shared between the nodes. */ @ThreadSafe @Singleton public class StatsTables { private final static BlockingQueue<OperationContextLog> NOOP_OPERATIONS_LOG = NoopQueue.instance(); private final static BlockingQueue<JobContextLog> NOOP_JOBS_LOG = NoopQueue.instance(); protected final Map<UUID, JobContext> jobsTable = new ConcurrentHashMap<>(); protected final Map<Integer, OperationContext> operationsTable = new ConcurrentHashMap<>(); protected final AtomicReference<BlockingQueue<JobContextLog>> jobsLog = new AtomicReference<>(NOOP_JOBS_LOG); protected final AtomicReference<BlockingQueue<OperationContextLog>> operationsLog = new AtomicReference<>(NOOP_OPERATIONS_LOG); private final JobsLogIterableGetter jobsLogIterableGetter; private final JobsIterableGetter jobsIterableGetter; private final OperationsIterableGetter operationsIterableGetter; private final OperationsLogIterableGetter operationsLogIterableGetter; protected final NodeSettingsService.Listener listener = new NodeSettingListener(); protected volatile int lastOperationsLogSize; protected volatile int lastJobsLogSize; protected volatile boolean lastIsEnabled; private final LongAdder activeRequests = new LongAdder(); public void activeRequestsInc() { activeRequests.increment(); } public void activeRequestsDec() { activeRequests.decrement(); } public long activeRequests() { return activeRequests.longValue(); } @Inject public StatsTables(Settings settings, NodeSettingsService nodeSettingsService) { int operationsLogSize = CrateSettings.STATS_OPERATIONS_LOG_SIZE.extract(settings); int jobsLogSize = CrateSettings.STATS_JOBS_LOG_SIZE.extract(settings); boolean isEnabled = CrateSettings.STATS_ENABLED.extract(settings); if (isEnabled) { setJobsLog(jobsLogSize); setOperationsLog(operationsLogSize); } else { setJobsLog(0); setOperationsLog(0); } lastOperationsLogSize = operationsLogSize; lastJobsLogSize = jobsLogSize; lastIsEnabled = isEnabled; nodeSettingsService.addListener(listener); jobsLogIterableGetter = new JobsLogIterableGetter(); jobsIterableGetter = new JobsIterableGetter(); operationsIterableGetter = new OperationsIterableGetter(); operationsLogIterableGetter = new OperationsLogIterableGetter(); } /** * Indicates if statistics are gathered. * This result will change if the cluster settings is updated. */ public boolean isEnabled() { return lastIsEnabled; } /** * Track a job. If the job has finished {@link #jobFinished(java.util.UUID, String)} * must be called. * * If {@link #isEnabled()} is false this method won't do anything. */ public void jobStarted(UUID jobId, String statement) { if (!isEnabled()) { return; } jobsTable.put(jobId, new JobContext(jobId, statement, System.currentTimeMillis())); } /** * mark a job as finished. * * If {@link #isEnabled()} is false this method won't do anything. */ public void jobFinished(UUID jobId, @Nullable String errorMessage) { if (!isEnabled()) { return; } JobContext jobContext = jobsTable.remove(jobId); if (jobContext == null) { return; } Queue<JobContextLog> jobContextLogs = jobsLog.get(); jobContextLogs.offer(new JobContextLog(jobContext, errorMessage)); } public void operationStarted(int operationId, UUID jobId, String name) { if (isEnabled()) { operationsTable.put( operationId, new OperationContext(operationId, jobId, name, System.currentTimeMillis())); } } public void operationFinished(@Nullable Integer operationId, @Nullable String errorMessage, long usedBytes) { if (operationId == null || !isEnabled()) { return; } OperationContext operationContext = operationsTable.remove(operationId); if (operationContext == null) { // this might be the case if the stats were disabled when the operation started but have // been enabled before the finish return; } operationContext.usedBytes = usedBytes; Queue<OperationContextLog> operationContextLogs = operationsLog.get(); operationContextLogs.offer(new OperationContextLog(operationContext, errorMessage)); } public IterableGetter jobsGetter() { return jobsIterableGetter; } public IterableGetter jobsLogGetter() { return jobsLogIterableGetter; } public IterableGetter operationsGetter() { return operationsIterableGetter; } public IterableGetter operationsLogGetter() { return operationsLogIterableGetter; } private class JobsLogIterableGetter implements IterableGetter { @Override public Iterable<?> getIterable() { return jobsLog.get(); } } private class JobsIterableGetter implements IterableGetter { @Override public Iterable<?> getIterable() { return jobsTable.values(); } } private class OperationsIterableGetter implements IterableGetter { @Override public Iterable<?> getIterable() { return operationsTable.values(); } } private class OperationsLogIterableGetter implements IterableGetter { @Override public Iterable<?> getIterable() { return operationsLog.get(); } } private void setOperationsLog(int size) { if (size == 0) { operationsLog.set(NOOP_OPERATIONS_LOG); } else { Queue<OperationContextLog> oldQ = operationsLog.get(); BlockingEvictingQueue<OperationContextLog> newQ = new BlockingEvictingQueue<>(size); newQ.addAll(oldQ); operationsLog.set(newQ); } } private void setJobsLog(int size) { if (size == 0) { jobsLog.set(NOOP_JOBS_LOG); } else { Queue<JobContextLog> oldQ = jobsLog.get(); BlockingEvictingQueue<JobContextLog> newQ = new BlockingEvictingQueue<>(size); newQ.addAll(oldQ); jobsLog.set(newQ); } } private class NodeSettingListener implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { boolean wasEnabled = lastIsEnabled; boolean becomesEnabled = CrateSettings.STATS_ENABLED.extract(settings); if (wasEnabled && becomesEnabled) { int opSize = CrateSettings.STATS_OPERATIONS_LOG_SIZE.extract(settings); if (opSize != lastOperationsLogSize) { lastOperationsLogSize = opSize; setOperationsLog(opSize); } int jobSize = CrateSettings.STATS_JOBS_LOG_SIZE.extract(settings); if (jobSize != lastJobsLogSize) { lastJobsLogSize = jobSize; setJobsLog(jobSize); } } else if (wasEnabled) { // !becomesEnabled setOperationsLog(0); setJobsLog(0); lastIsEnabled = false; lastOperationsLogSize = CrateSettings.STATS_OPERATIONS_LOG_SIZE.extract(settings); lastJobsLogSize = CrateSettings.STATS_JOBS_LOG_SIZE.extract(settings); } else if (becomesEnabled) { // !wasEnabled lastIsEnabled = true; // queue sizes was zero before so we have to change it int opSize = CrateSettings.STATS_OPERATIONS_LOG_SIZE.extract(settings); lastOperationsLogSize = opSize; setOperationsLog(opSize); int jobSize = CrateSettings.STATS_JOBS_LOG_SIZE.extract(settings); lastJobsLogSize = jobSize; setJobsLog(jobSize); } } } }
/* * Copyright 2009-2011 The MyBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.session; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ibatis.BaseDataTest; import org.apache.ibatis.binding.BindingException; import org.apache.ibatis.cache.impl.PerpetualCache; import org.apache.ibatis.executor.result.DefaultResultHandler; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory; import org.junit.BeforeClass; import org.junit.Test; import domain.blog.Author; import domain.blog.Blog; import domain.blog.Comment; import domain.blog.DraftPost; import domain.blog.ImmutableAuthor; import domain.blog.Post; import domain.blog.Section; import domain.blog.Tag; import domain.blog.mappers.AuthorMapper; import domain.blog.mappers.AuthorMapperWithMultipleHandlers; import domain.blog.mappers.AuthorMapperWithRowBounds; import domain.blog.mappers.BlogMapper; public class SqlSessionTest extends BaseDataTest { private static SqlSessionFactory sqlMapper; @BeforeClass public static void setup() throws Exception { createBlogDataSource(); final String resource = "org/apache/ibatis/builder/MapperConfig.xml"; final Reader reader = Resources.getResourceAsReader(resource); sqlMapper = new SqlSessionFactoryBuilder().build(reader); } @Test public void shouldResolveBothSimpleNameAndFullyQualifiedName() { Configuration c = new Configuration(); final String fullName = "com.mycache.MyCache"; final String shortName = "MyCache"; final PerpetualCache cache = new PerpetualCache(fullName); c.addCache(cache); assertEquals(cache, c.getCache(fullName)); assertEquals(cache, c.getCache(shortName)); } @Test(expected=IllegalArgumentException.class) public void shouldFailOverToMostApplicableSimpleName() { Configuration c = new Configuration(); final String fullName = "com.mycache.MyCache"; final String invalidName = "unknown.namespace.MyCache"; final PerpetualCache cache = new PerpetualCache(fullName); c.addCache(cache); assertEquals(cache, c.getCache(fullName)); assertEquals(cache, c.getCache(invalidName)); } @Test public void shouldSucceedWhenFullyQualifiedButFailDueToAmbiguity() { Configuration c = new Configuration(); final String name1 = "com.mycache.MyCache"; final PerpetualCache cache1 = new PerpetualCache(name1); c.addCache(cache1); final String name2 = "com.other.MyCache"; final PerpetualCache cache2 = new PerpetualCache(name2); c.addCache(cache2); final String shortName = "MyCache"; assertEquals(cache1, c.getCache(name1)); assertEquals(cache2, c.getCache(name2)); try { c.getCache(shortName); fail("Exception expected."); } catch (Exception e) { assertTrue(e.getMessage().contains("ambiguous")); } } @Test public void shouldFailToAddDueToNameConflict() { Configuration c = new Configuration(); final String fullName = "com.mycache.MyCache"; final PerpetualCache cache = new PerpetualCache(fullName); try { c.addCache(cache); c.addCache(cache); fail("Exception expected."); } catch (Exception e) { assertTrue(e.getMessage().contains("already contains value")); } } @Test public void shouldOpenAndClose() throws Exception { SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE); session.close(); } @Test public void shouldCommitAnUnUsedSqlSession() throws Exception { SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE); session.commit(true); session.close(); } @Test public void shouldRollbackAnUnUsedSqlSession() throws Exception { SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE); session.rollback(true); session.close(); } @Test public void shouldSelectAllAuthors() throws Exception { SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE); try { List<Author> authors = session.selectList("domain.blog.mappers.AuthorMapper.selectAllAuthors"); assertEquals(2, authors.size()); } finally { session.close(); } } @Test public void shouldSelectAllAuthorsAsMap() throws Exception { SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE); try { final Map<Integer,Author> authors = session.selectMap("domain.blog.mappers.AuthorMapper.selectAllAuthors", "id"); assertEquals(2, authors.size()); for(Map.Entry<Integer,Author> authorEntry : authors.entrySet()) { assertEquals(authorEntry.getKey(), (Integer) authorEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldSelectCountOfPosts() throws Exception { SqlSession session = sqlMapper.openSession(); try { Integer count = session.selectOne("domain.blog.mappers.BlogMapper.selectCountOfPosts"); assertEquals(5, count.intValue()); } finally { session.close(); } } @Test public void shouldEnsureThatBothEarlyAndLateResolutionOfNesteDiscriminatorsResolesToUseNestedResultSetHandler() throws Exception { SqlSession session = sqlMapper.openSession(); try { Configuration configuration = sqlMapper.getConfiguration(); assertTrue(configuration.getResultMap("domain.blog.mappers.BlogMapper.earlyNestedDiscriminatorPost").hasNestedResultMaps()); assertTrue(configuration.getResultMap("domain.blog.mappers.BlogMapper.lateNestedDiscriminatorPost").hasNestedResultMaps()); } finally { session.close(); } } @Test public void shouldSelectOneAuthor() throws Exception { SqlSession session = sqlMapper.openSession(); try { Author author = session.selectOne( "domain.blog.mappers.AuthorMapper.selectAuthor", new Author(101)); assertEquals(101, author.getId()); assertEquals(Section.NEWS, author.getFavouriteSection()); } finally { session.close(); } } @Test public void shouldSelectOneAuthorAsList() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Author> authors = session.selectList( "domain.blog.mappers.AuthorMapper.selectAuthor", new Author(101)); assertEquals(101, authors.get(0).getId()); assertEquals(Section.NEWS, authors.get(0).getFavouriteSection()); } finally { session.close(); } } @Test public void shouldSelectOneImmutableAuthor() throws Exception { SqlSession session = sqlMapper.openSession(); try { ImmutableAuthor author = session.selectOne( "domain.blog.mappers.AuthorMapper.selectImmutableAuthor", new Author(101)); assertEquals(101, author.getId()); assertEquals(Section.NEWS, author.getFavouriteSection()); } finally { session.close(); } } @Test public void shouldSelectOneAuthorWithInlineParams() throws Exception { SqlSession session = sqlMapper.openSession(); try { Author author = session.selectOne( "domain.blog.mappers.AuthorMapper.selectAuthorWithInlineParams", new Author(101)); assertEquals(101, author.getId()); } finally { session.close(); } } @Test public void shouldInsertAuthor() throws Exception { SqlSession session = sqlMapper.openSession(); try { Author expected = new Author(500, "cbegin", "******", "cbegin@somewhere.com", "Something...", null); int updates = session.insert("domain.blog.mappers.AuthorMapper.insertAuthor", expected); assertEquals(1, updates); Author actual = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", new Author(500)); assertNotNull(actual); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getUsername(), actual.getUsername()); assertEquals(expected.getPassword(), actual.getPassword()); assertEquals(expected.getEmail(), actual.getEmail()); assertEquals(expected.getBio(), actual.getBio()); } finally { session.close(); } } @Test public void shouldUpdateAuthorImplicitRollback() throws Exception { SqlSession session = sqlMapper.openSession(); Author original; Author updated; try { original = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); original.setEmail("new@email.com"); int updates = session.update("domain.blog.mappers.AuthorMapper.updateAuthor", original); assertEquals(1, updates); updated = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); assertEquals(original.getEmail(), updated.getEmail()); } finally { session.close(); } try { session = sqlMapper.openSession(); updated = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); assertEquals("jim@ibatis.apache.org", updated.getEmail()); } finally { session.close(); } } @Test public void shouldUpdateAuthorCommit() throws Exception { SqlSession session = sqlMapper.openSession(); Author original; Author updated; try { original = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); original.setEmail("new@email.com"); int updates = session.update("domain.blog.mappers.AuthorMapper.updateAuthor", original); assertEquals(1, updates); updated = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); assertEquals(original.getEmail(), updated.getEmail()); session.commit(); } finally { session.close(); } try { session = sqlMapper.openSession(); updated = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); assertEquals(original.getEmail(), updated.getEmail()); } finally { session.close(); } } @Test public void shouldUpdateAuthorIfNecessary() throws Exception { SqlSession session = sqlMapper.openSession(); Author original; Author updated; try { original = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); original.setEmail("new@email.com"); original.setBio(null); int updates = session.update("domain.blog.mappers.AuthorMapper.updateAuthorIfNecessary", original); assertEquals(1, updates); updated = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); assertEquals(original.getEmail(), updated.getEmail()); session.commit(); } finally { session.close(); } try { session = sqlMapper.openSession(); updated = session.selectOne("domain.blog.mappers.AuthorMapper.selectAuthor", 101); assertEquals(original.getEmail(), updated.getEmail()); } finally { session.close(); } } @Test public void shouldDeleteAuthor() throws Exception { SqlSession session = sqlMapper.openSession(); try { final int id = 102; List<Author> authors = session.selectList("domain.blog.mappers.AuthorMapper.selectAuthor", id); assertEquals(1, authors.size()); int updates = session.delete("domain.blog.mappers.AuthorMapper.deleteAuthor", id); assertEquals(1, updates); authors = session.selectList("domain.blog.mappers.AuthorMapper.selectAuthor", id); assertEquals(0, authors.size()); session.rollback(); authors = session.selectList("domain.blog.mappers.AuthorMapper.selectAuthor", id); assertEquals(1, authors.size()); } finally { session.close(); } } @Test public void shouldSelectBlogWithPostsAndAuthorUsingSubSelects() throws Exception { SqlSession session = sqlMapper.openSession(); try { Blog blog = session.selectOne("domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect", 1); assertEquals("Jim Business", blog.getTitle()); assertEquals(2, blog.getPosts().size()); assertEquals("Corn nuts", blog.getPosts().get(0).getSubject()); assertEquals(101, blog.getAuthor().getId()); assertEquals("jim", blog.getAuthor().getUsername()); } finally { session.close(); } } @Test public void shouldSelectBlogWithPostsAndAuthorUsingJoin() throws Exception { SqlSession session = sqlMapper.openSession(); try { Blog blog = session.selectOne("domain.blog.mappers.BlogMapper.selectBlogJoinedWithPostsAndAuthor", 1); assertEquals("Jim Business", blog.getTitle()); final Author author = blog.getAuthor(); assertEquals(101, author.getId()); assertEquals("jim", author.getUsername()); final List<Post> posts = blog.getPosts(); assertEquals(2, posts.size()); final Post post = blog.getPosts().get(0); assertEquals(1, post.getId()); assertEquals("Corn nuts", post.getSubject()); final List<Comment> comments = post.getComments(); assertEquals(2, comments.size()); final List<Tag> tags = post.getTags(); assertEquals(3, tags.size()); final Comment comment = comments.get(0); assertEquals(1, comment.getId()); assertEquals(DraftPost.class, blog.getPosts().get(0).getClass()); assertEquals(Post.class, blog.getPosts().get(1).getClass()); } finally { session.close(); } } @Test public void shouldSelectNestedBlogWithPostsAndAuthorUsingJoin() throws Exception { SqlSession session = sqlMapper.openSession(); try { Blog blog = session.selectOne("domain.blog.mappers.NestedBlogMapper.selectBlogJoinedWithPostsAndAuthor", 1); assertEquals("Jim Business", blog.getTitle()); final Author author = blog.getAuthor(); assertEquals(101, author.getId()); assertEquals("jim", author.getUsername()); final List<Post> posts = blog.getPosts(); assertEquals(2, posts.size()); final Post post = blog.getPosts().get(0); assertEquals(1, post.getId()); assertEquals("Corn nuts", post.getSubject()); final List<Comment> comments = post.getComments(); assertEquals(2, comments.size()); final List<Tag> tags = post.getTags(); assertEquals(3, tags.size()); final Comment comment = comments.get(0); assertEquals(1, comment.getId()); assertEquals(DraftPost.class, blog.getPosts().get(0).getClass()); assertEquals(Post.class, blog.getPosts().get(1).getClass()); } finally { session.close(); } } @Test public void shouldThrowExceptionIfMappedStatementDoesNotExist() throws Exception { SqlSession session = sqlMapper.openSession(); try { session.selectList("ThisStatementDoesNotExist"); fail("Expected exception to be thrown due to statement that does not exist."); } catch (Exception e) { assertTrue(e.getMessage().contains("does not contain value for ThisStatementDoesNotExist")); } finally { session.close(); } } @Test public void shouldThrowExceptionIfTryingToAddStatementWithSameName() throws Exception { Configuration config = sqlMapper.getConfiguration(); try { config.addMappedStatement(config.getMappedStatement("domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect")); fail("Expected exception to be thrown due to statement that already exists."); } catch (Exception e) { assertTrue(e.getMessage().contains("already contains value for domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect")); } } @Test public void shouldCacheAllAuthors() throws Exception { int first = -1; int second = -1; SqlSession session = sqlMapper.openSession(); try { List<Author> authors = session.selectList("com.domain.CachedAuthorMapper.selectAllAuthors"); first = System.identityHashCode(authors); session.commit(); // commit should not be required for read/only activity. } finally { session.close(); } session = sqlMapper.openSession(); try { List<Author> authors = session.selectList("com.domain.CachedAuthorMapper.selectAllAuthors"); second = System.identityHashCode(authors); } finally { session.close(); } assertEquals(first, second); } @Test public void shouldNotCacheAllAuthors() throws Exception { int first = -1; int second = -1; SqlSession session = sqlMapper.openSession(); try { List<Author> authors = session.selectList("domain.blog.mappers.AuthorMapper.selectAllAuthors"); first = System.identityHashCode(authors); } finally { session.close(); } session = sqlMapper.openSession(); try { List<Author> authors = session.selectList("domain.blog.mappers.AuthorMapper.selectAllAuthors"); second = System.identityHashCode(authors); } finally { session.close(); } assertTrue(first != second); } @Test public void shouldSelectAuthorsUsingMapperClass() { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); List authors = mapper.selectAllAuthors(); assertEquals(2, authors.size()); } finally { session.close(); } } @Test public void shouldExecuteSelectOneAuthorUsingMapperClass() { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Author author = mapper.selectAuthor(101); assertEquals(101, author.getId()); } finally { session.close(); } } @Test public void shouldExecuteSelectOneAuthorUsingMapperClassThatReturnsSet() { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Collection<Author> authors = mapper.selectAllAuthorsSet(); assertEquals(2, authors.size()); } finally { session.close(); } } @Test public void shouldExecuteSelectOneAuthorUsingMapperClassThatReturnsVector() { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Collection<Author> authors = mapper.selectAllAuthorsVector(); assertEquals(2, authors.size()); } finally { session.close(); } } @Test public void shouldExecuteSelectOneAuthorUsingMapperClassThatReturnsLinkedList() { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Collection<Author> authors = mapper.selectAllAuthorsLinkedList(); assertEquals(2, authors.size()); } finally { session.close(); } } @Test public void shouldExecuteSelectOneAuthorUsingMapperClassThatReturnsAnArray() { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Author[] authors = mapper.selectAllAuthorsArray(); assertEquals(2, authors.length); } finally { session.close(); } } @Test public void shouldExecuteSelectOneAuthorUsingMapperClassWithResultHandler() { SqlSession session = sqlMapper.openSession(); try { DefaultResultHandler handler = new DefaultResultHandler(); AuthorMapper mapper = session.getMapper(AuthorMapper.class); mapper.selectAuthor(101, handler); Author author = (Author) handler.getResultList().get(0); assertEquals(101, author.getId()); } finally { session.close(); } } @Test(expected=BindingException.class) public void shouldFailExecutingAnAnnotatedMapperClassWithResultHandler() { SqlSession session = sqlMapper.openSession(); try { DefaultResultHandler handler = new DefaultResultHandler(); AuthorMapper mapper = session.getMapper(AuthorMapper.class); mapper.selectAuthor2(101, handler); Author author = (Author) handler.getResultList().get(0); assertEquals(101, author.getId()); } finally { session.close(); } } @Test public void shouldSelectAuthorsUsingMapperClassWithResultHandler() { SqlSession session = sqlMapper.openSession(); try { DefaultResultHandler handler = new DefaultResultHandler(); AuthorMapper mapper = session.getMapper(AuthorMapper.class); mapper.selectAllAuthors(handler); assertEquals(2, handler.getResultList().size()); } finally { session.close(); } } @Test(expected = BindingException.class) public void shouldFailSelectOneAuthorUsingMapperClassWithTwoResultHandlers() { Configuration configuration = new Configuration(sqlMapper.getConfiguration().getEnvironment()); configuration.addMapper(AuthorMapperWithMultipleHandlers.class); SqlSessionFactory sqlMapperWithMultipleHandlers = new DefaultSqlSessionFactory(configuration); SqlSession sqlSession = sqlMapperWithMultipleHandlers.openSession(); try { DefaultResultHandler handler1 = new DefaultResultHandler(); DefaultResultHandler handler2 = new DefaultResultHandler(); AuthorMapperWithMultipleHandlers mapper = sqlSession.getMapper(AuthorMapperWithMultipleHandlers.class); mapper.selectAuthor(101, handler1, handler2); } finally { sqlSession.close(); } } @Test(expected = BindingException.class) public void shouldFailSelectOneAuthorUsingMapperClassWithTwoRowBounds() { Configuration configuration = new Configuration(sqlMapper.getConfiguration().getEnvironment()); configuration.addMapper(AuthorMapperWithRowBounds.class); SqlSessionFactory sqlMapperWithMultipleHandlers = new DefaultSqlSessionFactory(configuration); SqlSession sqlSession = sqlMapperWithMultipleHandlers.openSession(); try { RowBounds bounds1 = new RowBounds(0, 1); RowBounds bounds2 = new RowBounds(0, 1); AuthorMapperWithRowBounds mapper = sqlSession.getMapper(AuthorMapperWithRowBounds.class); mapper.selectAuthor(101, bounds1, bounds2); } finally { sqlSession.close(); } } @Test public void shouldInsertAuthorUsingMapperClass() throws Exception { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Author expected = new Author(500, "cbegin", "******", "cbegin@somewhere.com", "Something...", null); mapper.insertAuthor(expected); Author actual = mapper.selectAuthor(500); assertNotNull(actual); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getUsername(), actual.getUsername()); assertEquals(expected.getPassword(), actual.getPassword()); assertEquals(expected.getEmail(), actual.getEmail()); assertEquals(expected.getBio(), actual.getBio()); } finally { session.close(); } } @Test public void shouldDeleteAuthorUsingMapperClass() throws Exception { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); int count = mapper.deleteAuthor(101); assertEquals(1, count); assertNull(mapper.selectAuthor(101)); } finally { session.close(); } } @Test public void shouldUpdateAuthorUsingMapperClass() throws Exception { SqlSession session = sqlMapper.openSession(); try { AuthorMapper mapper = session.getMapper(AuthorMapper.class); Author expected = mapper.selectAuthor(101); expected.setUsername("NewUsername"); int count = mapper.updateAuthor(expected); assertEquals(1, count); Author actual = mapper.selectAuthor(101); assertEquals(expected.getUsername(), actual.getUsername()); } finally { session.close(); } } @Test public void shouldSelectAllPostsUsingMapperClass() throws Exception { SqlSession session = sqlMapper.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); List<Map> posts = mapper.selectAllPosts(); assertEquals(5, posts.size()); } finally { session.close(); } } @Test public void shouldLimitResultsUsingMapperClass() throws Exception { SqlSession session = sqlMapper.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); List<Map> posts = mapper.selectAllPosts(new RowBounds(0, 2), null); assertEquals(2, posts.size()); assertEquals(1, posts.get(0).get("ID")); assertEquals(2, posts.get(1).get("ID")); } finally { session.close(); } } private static class TestResultHandler implements ResultHandler { int count = 0; public void handleResult(ResultContext context) { count++; } } @Test public void shouldHandleZeroParameters() throws Exception { SqlSession session = sqlMapper.openSession(); try { final TestResultHandler resultHandler = new TestResultHandler(); session.select("domain.blog.mappers.BlogMapper.selectAllPosts", resultHandler); assertEquals(5, resultHandler.count); } finally { session.close(); } } private static class TestResultStopHandler implements ResultHandler { int count = 0; public void handleResult(ResultContext context) { count++; if (count == 2) context.stop(); } } @Test public void shouldStopResultHandler() throws Exception { SqlSession session = sqlMapper.openSession(); try { final TestResultStopHandler resultHandler = new TestResultStopHandler(); session.select("domain.blog.mappers.BlogMapper.selectAllPosts", null, resultHandler); assertEquals(2, resultHandler.count); } finally { session.close(); } } @Test public void shouldOffsetAndLimitResultsUsingMapperClass() throws Exception { SqlSession session = sqlMapper.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); List<Map> posts = mapper.selectAllPosts(new RowBounds(2, 3)); assertEquals(3, posts.size()); assertEquals(3, posts.get(0).get("ID")); assertEquals(4, posts.get(1).get("ID")); assertEquals(5, posts.get(2).get("ID")); } finally { session.close(); } } @Test public void shouldFindPostsAllPostsWithDynamicSql() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.findPost"); assertEquals(5, posts.size()); } finally { session.close(); } } @Test public void shouldFindPostByIDWithDynamicSql() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.findPost", new HashMap() {{ put("id", 1); }}); assertEquals(1, posts.size()); } finally { session.close(); } } @Test public void shouldFindPostsInSetOfIDsWithDynamicSql() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.findPost", new HashMap() {{ put("ids", new ArrayList() {{ add(1); add(2); add(3); }}); }}); assertEquals(3, posts.size()); } finally { session.close(); } } @Test public void shouldFindPostsWithBlogIdUsingDynamicSql() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.findPost", new HashMap() {{ put("blog_id", 1); }}); assertEquals(2, posts.size()); } finally { session.close(); } } @Test public void shouldFindPostsWithAuthorIdUsingDynamicSql() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.findPost", new HashMap() {{ put("author_id", 101); }}); assertEquals(3, posts.size()); } finally { session.close(); } } @Test public void shouldFindPostsWithAuthorAndBlogIdUsingDynamicSql() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.findPost", new HashMap() {{ put("ids", new ArrayList() {{ add(1); add(2); add(3); }}); put("blog_id", 1); }}); assertEquals(2, posts.size()); } finally { session.close(); } } @Test public void shouldFindPostsInList() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.selectPostIn", new ArrayList() {{ add(1); add(3); add(5); }}); assertEquals(3, posts.size()); } finally { session.close(); } } @Test public void shouldFindOddPostsInList() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.selectOddPostsIn", new ArrayList() {{ add(0); add(1); add(2); add(3); add(4); }}); // we're getting odd indexes, not odd values, 0 is not odd assertEquals(2, posts.size()); assertEquals(1, posts.get(0).getId()); assertEquals(3, posts.get(1).getId()); } finally { session.close(); } } @Test public void shouldSelectOddPostsInKeysList() throws Exception { SqlSession session = sqlMapper.openSession(); try { List<Post> posts = session.selectList("domain.blog.mappers.PostMapper.selectOddPostsInKeysList", new HashMap() {{put("keys",new ArrayList() {{ add(0); add(1); add(2); add(3); add(4); }}); }}); // we're getting odd indexes, not odd values, 0 is not odd assertEquals(2, posts.size()); assertEquals(1, posts.get(0).getId()); assertEquals(3, posts.get(1).getId()); } finally { session.close(); } } }
package fi.seco.rdfio; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Map; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; import org.apache.jena.iri.IRI; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFLanguages; import org.apache.jena.riot.RiotReader; import org.apache.jena.riot.lang.LabelToNode; import org.apache.jena.riot.lang.LangNTuple; import org.apache.jena.riot.lang.LangRIOT; import org.apache.jena.riot.system.ErrorHandlerFactory; import org.apache.jena.riot.system.ParserProfileBase; import org.apache.jena.riot.system.PrefixMap; import org.apache.jena.riot.system.PrefixMapStd; import org.apache.jena.riot.system.StreamRDFBase; import org.openrdf.model.Statement; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.RDFParser.DatatypeHandling; import org.openrdf.rio.RDFParserRegistry; import org.openrdf.rio.Rio; import org.openrdf.rio.helpers.RDFHandlerBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Triple; import fi.seco.openrdf.IllegalURICorrectingValueFactory; import fi.seco.openrdf.RDFFormats; import fi.seco.rdfobject.IQuad; import fi.seco.rdfobject.IQuadVisitor; import fi.seco.rdfobject.IRDFObject; import fi.seco.rdfobject.ITriple; import fi.seco.rdfobject.ITripleVisitor; import fi.seco.rdfobject.URIResourceRDFObject; import fi.seco.rdfobject.jena.JenaRDFObjectUtil; import fi.seco.rdfobject.model.IRDFObjectQuadModel; import fi.seco.rdfobject.model.IRDFObjectTripleModel; import fi.seco.rdfobject.openrdf.OpenRDFRDFObjectUtil; /** * An utility class for reading RDF. Uses efficient streaming parsers where * possible. Combines readers from Sesame and Jena with custom readers for the * Freebase dump format and Sindice DE tar format. Can read at least RDF/XML, * turtle, N3, n-triples, n-quads, trix, trig, rdf-json, binary, Freebase dump * and Sindice DE tar. Also supports gzip and bzip2 compressed sources. * * @author jiemakel * */ public class RDFReader { private static final Logger log = LoggerFactory.getLogger(RDFReader.class); static { RDFParserRegistry.getInstance(); // for initialization of formats; } /** * A handler for streaming RDF quads and metadata * * @author jiemakel * */ public interface IRDFHandler extends IQuadVisitor { /** * A namespace definition encountered while processing RDF * * @param prefix * the prefix for the namespace * @param ns * the namespace for the prefix */ public void setNameSpace(String prefix, String ns); public void setBaseIRI(String baseIRI); /** * A comment encountered while processing RDF * * @param comment * the comment */ public void comment(String comment); } static RDFFormat getFormat(String url) { return RDFFormat.forFileName(url); } static Lang getLang(String url) { return RDFLanguages.filenameToLang(url); } static InputStream getInputStreamFromURL(String s) { try { if (s.endsWith(".xz")) return new XZCompressorInputStream(new URL(s).openStream()); if (s.endsWith(".gz")) return new GZIPInputStream(new URL(s).openStream()); if (s.endsWith(".bz2")) return new BZip2CompressorInputStream(new URL(s).openStream()); else return new URL(s).openStream(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Check whether the format of the source url is a quad format, as * determined by the extension * * @param url * the file to check * @return <code>true</code> if the url's extension indicates a quad format */ public static boolean isQuads(String url) { RDFFormat f = getFormat(url); if (f != null) return f.supportsContexts(); return false; } /** * Check whether the format of the source url is something that this reader * can parse, as determined by the extension. * * @param url * the file to check * @return <code>true</code> if this reader can parse the file format */ public static boolean canRead(String url) { if (getFormat(url) != null) return true; return false; } /** * Parse a file, streaming quads and metadata to an RDF handler * * @param url * the location of the file to read * @param handler * the RDF handler to pass quads and metadata to * @throws IOException * @throws RDFHandlerException * @throws RDFParseException */ public static void read(String url, final IRDFHandler handler) throws IOException, RDFParseException, RDFHandlerException { read(getInputStreamFromURL(url), getFormat(url), new URIResourceRDFObject(url), url, handler); } public static void read(InputStream is, RDFFormat type, final IRDFObject dg, String baseURI, final IRDFHandler handler) throws IOException, RDFParseException, RDFHandlerException { Lang lang = RDFLanguages.nameToLang(type.getName()); if (lang != null && !RDFLanguages.RDFXML.equals(lang)) {// openrdf parsers throw a fit if ttl lname starts with a number. RIOT seems faster also on at least NTRIPLES. But RIOT's RDF/XML parser is too strict LangRIOT parser = RiotReader.createParser(is, lang, baseURI, new StreamRDFBase() { @Override public void triple(Triple t) { handler.visit(new fi.seco.rdfobject.Quad(JenaRDFObjectUtil.getRDFObjectForNode(t.getSubject()), JenaRDFObjectUtil.getRDFObjectForNode(t.getPredicate()), JenaRDFObjectUtil.getRDFObjectForNode(t.getObject()), dg)); } @Override public void prefix(String prefix, String iri) { handler.setNameSpace(prefix, iri); } @Override public void base(String iri) { handler.setBaseIRI(iri); } }); if (parser instanceof LangNTuple<?>) ((LangNTuple<?>) parser).setSkipOnBadTerm(true); parser.setProfile(new ParserProfileBase(parser.getProfile().getPrologue(), ErrorHandlerFactory.errorHandlerWarn, LabelToNode.createUseLabelAsGiven())); parser.getProfile().getPrologue().setPrefixMapping(new PrefixMapStd(parser.getProfile().getPrologue().getPrefixMap()) { @Override public void add(String prefix, String iriString) { super.add(prefix, iriString); handler.setNameSpace(prefix, iriString); } @Override public void add(String prefix, IRI iri) { super.add(prefix, iri); handler.setNameSpace(prefix, iri.toString()); } @Override public void putAll(PrefixMap pmap) { super.putAll(pmap); for (Map.Entry<String, IRI> e : pmap.getMapping().entrySet()) handler.setNameSpace(e.getKey(), e.getValue().toString()); } }); parser.parse(); } else if (RDFFormats.SINDICE_DE_TAR.equals(type)) SindiceDETarParser.parse(is, handler); else if (RDFFormats.FREEBASE_QUADS.equals(type)) FreebaseParser.transformData(new BufferedReader(new InputStreamReader(is)), new ITripleVisitor() { @Override public void visit(ITriple t) { handler.visit(new fi.seco.rdfobject.Quad(t.getSubject(), t.getProperty(), t.getObject(), dg)); } }); else { RDFParser p = Rio.createParser(type); p.setStopAtFirstError(false); p.setVerifyData(false); p.setValueFactory(IllegalURICorrectingValueFactory.instance); p.setDatatypeHandling(DatatypeHandling.IGNORE); if (type.supportsContexts()) p.setRDFHandler(new RDFHandlerBase() { @Override public void handleNamespace(String prefix, String uri) { if ("".equals(prefix)) handler.setBaseIRI(uri); else handler.setNameSpace(prefix, uri); } @Override public void handleStatement(Statement st) { handler.visit(OpenRDFRDFObjectUtil.getQuadForStatement(st)); } @Override public void handleComment(String comment) { handler.comment(comment); } }); else p.setRDFHandler(new RDFHandlerBase() { @Override public void handleNamespace(String prefix, String uri) { if ("".equals(prefix)) handler.setBaseIRI(uri); else handler.setNameSpace(prefix, uri); } @Override public void handleStatement(Statement st) { handler.visit(new fi.seco.rdfobject.Quad(OpenRDFRDFObjectUtil.getRDFObjectForValue(st.getSubject()), OpenRDFRDFObjectUtil.getRDFObjectForValue(st.getPredicate()), OpenRDFRDFObjectUtil.getRDFObjectForValue(st.getObject()), dg)); } @Override public void handleComment(String comment) { handler.comment(comment); } }); p.parse(new InputStreamReader(is, "UTF-8"), baseURI); } } public static IRDFHandler getInserter(final IRDFObjectQuadModel m) { return new IRDFHandler() { @Override public void visit(IQuad q) { m.addQuad(q); } @Override public void setNameSpace(String prefix, String ns) { m.getPrefixMap().put(prefix, ns); } @Override public void comment(String comment) { } @Override public void setBaseIRI(String baseIRI) {} }; } public static IRDFHandler getInserter(final IRDFObjectTripleModel m) { return new IRDFHandler() { @Override public void visit(IQuad q) { m.addTriple(q); } @Override public void setNameSpace(String prefix, String ns) { m.getPrefixMap().put(prefix, ns); } @Override public void comment(String comment) { } @Override public void setBaseIRI(String baseIRI) {} }; } }
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.core.services.impl.jpa; import com.netflix.genie.common.exceptions.GenieConflictException; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GenieNotFoundException; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.exceptions.GenieServerUnavailableException; import com.netflix.genie.common.model.Job; import com.netflix.genie.common.model.JobStatus; import com.netflix.genie.common.util.ProcessStatus; import com.netflix.genie.core.repositories.jpa.JobSpecs; import com.netflix.genie.core.services.ExecutionService; import com.netflix.genie.core.services.JobService; import com.netflix.genie.core.jobmanager.JobManagerFactory; import com.netflix.genie.core.metrics.GenieNodeStatistics; import com.netflix.genie.core.metrics.JobCountManager; import com.netflix.genie.core.repositories.jpa.JobRepository; import com.netflix.genie.core.util.NetUtil; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotBlank; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; /** * Implementation of the Genie Execution Service API that uses a local job * launcher (via the job manager implementation), and uses OpenJPA for * persistence. * * @author tgianos * @author amsharma */ @Service public class ExecutionServiceJPAImpl implements ExecutionService { private static final Logger LOG = LoggerFactory.getLogger(ExecutionServiceJPAImpl.class); // per-instance variables private final GenieNodeStatistics stats; private final JobRepository jobRepo; private final JobCountManager jobCountManager; private final JobManagerFactory jobManagerFactory; private final JobService jobService; private final NetUtil netUtil; @Value("${netflix.appinfo.port:8080}") private int serverPort; @Value("${com.netflix.genie.server.job.resource.prefix:genie/v2/jobs}") private String jobResourcePrefix; @Value("${com.netflix.genie.server.max.running.jobs:0}") private int maxRunningJobs; @Value("${com.netflix.genie.server.forward.jobs.threshold:0}") private int jobForwardThreshold; @Value("${com.netflix.genie.server.max.idle.host.threshold:0}") private int maxIdleHostThreshold; @Value("${com.netflix.genie.server.idle.host.threshold.delta:0}") private int idleHostThresholdDelta; @Value("${com.netflix.genie.server.janitor.zombie.delta.ms:1800000}") private long zombieTime; /** * Default constructor - initializes persistence manager, and other utility * classes. * * @param jobRepo The job repository to use. * @param stats the GenieNodeStatistics object * @param jobCountManager the job count manager to use * @param jobManagerFactory The the job manager factory to use * @param jobService The job service to use. * @param netUtil The network utility to use */ @Autowired public ExecutionServiceJPAImpl( final JobRepository jobRepo, final GenieNodeStatistics stats, final JobCountManager jobCountManager, final JobManagerFactory jobManagerFactory, final JobService jobService, final NetUtil netUtil ) { this.jobRepo = jobRepo; this.stats = stats; this.jobCountManager = jobCountManager; this.jobManagerFactory = jobManagerFactory; this.jobService = jobService; this.netUtil = netUtil; } /** * {@inheritDoc} */ @Override public Job submitJob( @NotNull(message = "No job entered to run") @Valid final Job job ) throws GenieException { if (LOG.isDebugEnabled()) { LOG.debug("Called"); } if (StringUtils.isNotBlank(job.getId()) && this.jobRepo.exists(job.getId())) { throw new GenieConflictException("Job with ID specified already exists."); } // Check if the job is forwarded. If not this is the first node that got the request. // So we log it, to track all requests. if (!job.isForwarded()) { LOG.info("Received job request:" + job); } final Job forwardedJob = checkAbilityToRunOrForward(job); if (forwardedJob != null) { return forwardedJob; } // At this point we have established that the job can be run on this node. // Before running we validate the job and save it in the db if it passes validation. final Job savedJob = this.jobService.createJob(job); // try to run the job - return success or error return this.jobService.runJob(savedJob); } /** * {@inheritDoc} */ @Override @Transactional( rollbackFor = { GenieException.class, ConstraintViolationException.class } ) public Job killJob( @NotBlank(message = "No id entered unable to kill job.") final String id ) throws GenieException { if (LOG.isDebugEnabled()) { LOG.debug("called for id: " + id); } final Job job = this.jobRepo.findOne(id); // do some basic error handling if (job == null) { throw new GenieNotFoundException("No job exists for id " + id + ". Unable to kill."); } // check if it is done already if (job.getStatus() == JobStatus.SUCCEEDED || job.getStatus() == JobStatus.KILLED || job.getStatus() == JobStatus.FAILED) { // job already exited, return status to user return job; } else if (job.getStatus() == JobStatus.INIT || job.getProcessHandle() == -1) { // can't kill a job if it is still initializing throw new GeniePreconditionException("Unable to kill job as it is still initializing"); } // if we get here, job is still running - and can be killed // redirect to the right node if killURI points to a different node final String killURI = job.getKillURI(); if (StringUtils.isBlank(killURI)) { throw new GeniePreconditionException("Failed to get killURI for jobID: " + id); } final String localURI = getEndPoint() + "/" + this.jobResourcePrefix + "/" + id; if (!killURI.equals(localURI)) { if (LOG.isDebugEnabled()) { LOG.debug("forwarding kill request to: " + killURI); } return forwardJobKill(killURI); } // if we get here, killURI == localURI, and job should be killed here if (LOG.isDebugEnabled()) { LOG.debug("killing job on same instance: " + id); } this.jobManagerFactory.getJobManager(job).kill(); job.setJobStatus(JobStatus.KILLED, "Job killed on user request"); job.setExitCode(ProcessStatus.JOB_KILLED.getExitCode()); // increment counter for killed jobs this.stats.incrGenieKilledJobs(); if (LOG.isDebugEnabled()) { LOG.debug("updating job status to KILLED for: " + id); } if (!job.isDisableLogArchival()) { job.setArchiveLocation(this.netUtil.getArchiveURI(id)); } // all good - return results return job; } /** * {@inheritDoc} */ @Override @Transactional public int markZombies() { if (LOG.isDebugEnabled()) { LOG.debug("called"); } final ProcessStatus zombie = ProcessStatus.ZOMBIE_JOB; final long currentTime = new Date().getTime(); @SuppressWarnings("unchecked") final List<Job> jobs = this.jobRepo.findAll(JobSpecs.findZombies(currentTime, this.zombieTime)); for (final Job job : jobs) { job.setStatus(JobStatus.FAILED); job.setFinished(new Date()); job.setExitCode(zombie.getExitCode()); job.setStatusMsg(zombie.getMessage()); } return jobs.size(); } /** * {@inheritDoc} */ @Override @Transactional( rollbackFor = { GenieException.class, ConstraintViolationException.class } ) public JobStatus finalizeJob( @NotBlank(message = "No job id entered. Unable to finalize.") final String id, final int exitCode ) throws GenieException { final Job job = this.jobRepo.findOne(id); if (job == null) { throw new GenieNotFoundException("No job with id " + id + " exists"); } job.setExitCode(exitCode); // We check if status code is killed. The kill thread sets this, but just to make sure we set // it here again to prevent a race condition problem. This just makes the status message as // killed and prevents some jobs that are killed being marked as failed if (exitCode == ProcessStatus.JOB_KILLED.getExitCode()) { if (LOG.isDebugEnabled()) { LOG.debug("Process has been killed, therefore setting the appropriate status message."); } job.setJobStatus(JobStatus.KILLED, "Job killed on user request"); return JobStatus.KILLED; } else { if (exitCode != ProcessStatus.SUCCESS.getExitCode()) { // all other failures except s3 log archival failure LOG.error("Failed to execute job, exit code: " + exitCode); String errMsg; try { errMsg = ProcessStatus.parse(exitCode).getMessage(); } catch (final GenieException ge) { errMsg = "Please look at job's stderr for more details"; } job.setJobStatus(JobStatus.FAILED, "Failed to execute job, Error Message: " + errMsg); // incr counter for failed jobs this.stats.incrGenieFailedJobs(); } else { // success job.setJobStatus(JobStatus.SUCCEEDED, "Job finished successfully"); // incr counter for successful jobs this.stats.incrGenieSuccessfulJobs(); } // set the archive location - if needed if (!job.isDisableLogArchival()) { job.setArchiveLocation(this.netUtil.getArchiveURI(job.getId())); } // set the updated time job.setUpdated(new Date()); return job.getStatus(); } } private String getEndPoint() throws GenieException { return "http://" + this.netUtil.getHostName() + ":" + this.serverPort; } private Job forwardJobKill(final String killURI) throws GenieException { throw new UnsupportedOperationException("Not yet implemented"); // try { // final BaseGenieClient client = new BaseGenieClient(null); // final HttpRequest request = BaseGenieClient.buildRequest(Verb.DELETE, killURI, null, null); // return (Job) client.executeRequest(request, null, Job.class); // } catch (final IOException ioe) { // throw new GenieServerException(ioe.getMessage(), ioe); // } } private Job forwardJobRequest(final String hostURI, final Job job) throws GenieException { throw new UnsupportedOperationException("Not yet implemented"); // try { // final BaseGenieClient client = new BaseGenieClient(null); // final HttpRequest request = BaseGenieClient.buildRequest(Verb.POST, hostURI, null, job); // return (Job) client.executeRequest(request, null, Job.class); // } catch (final IOException ioe) { // throw new GenieServerException(ioe.getMessage(), ioe); // } } /** * Check if we can run the job on this host or not. * * @throws GenieException */ private synchronized Job checkAbilityToRunOrForward(final Job job) throws GenieException { final int numRunningJobs = this.jobCountManager.getNumInstanceJobs(); LOG.info("Number of running jobs: " + numRunningJobs); // find an instance with fewer than (numRunningJobs - // idleHostThresholdDelta) int idleHostThreshold = numRunningJobs - this.idleHostThresholdDelta; // if numRunningJobs is already >= maxRunningJobs, forward // aggressively // but cap it at the max if (idleHostThreshold > this.maxIdleHostThreshold || numRunningJobs >= this.maxRunningJobs) { idleHostThreshold = this.maxIdleHostThreshold; } // check to see if job should be forwarded - only forward it // once. the assumption is that jobForwardThreshold < maxRunningJobs // (set in properties file) if (numRunningJobs >= this.jobForwardThreshold && !job.isForwarded()) { LOG.info("Number of running jobs greater than forwarding threshold - trying to auto-forward"); final String idleHost = this.jobCountManager.getIdleInstance(idleHostThreshold); if (!idleHost.equals(this.netUtil.getHostName())) { job.setForwarded(true); this.stats.incrGenieForwardedJobs(); return forwardJobRequest( "http://" + idleHost + ":" + this.serverPort + "/" + this.jobResourcePrefix, job ); } // else, no idle hosts found - run here if capacity exists } // TODO: Gotta be something better we can do than this if (numRunningJobs >= maxRunningJobs) { // if we get here, job can't be forwarded to an idle // instance anymore and current node is overloaded throw new GenieServerUnavailableException( "Number of running jobs greater than system limit (" + maxRunningJobs + ") - try another instance or try again later"); } //We didn't forward the job so return null to signal to run the job locally return null; } }
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.io.parquet.serde; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.hadoop.hive.ql.io.parquet.timestamp.NanoTime; import org.apache.hadoop.hive.ql.io.parquet.timestamp.NanoTimeUtils; /** * Tests util-libraries used for parquet-timestamp. */ public class TestParquetTimestampUtils extends TestCase { public void testJulianDay() { //check if May 23, 1968 is Julian Day 2440000 Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 1968); cal.set(Calendar.MONTH, Calendar.MAY); cal.set(Calendar.DAY_OF_MONTH, 23); cal.set(Calendar.HOUR_OF_DAY, 0); cal.setTimeZone(TimeZone.getTimeZone("GMT")); Timestamp ts = new Timestamp(cal.getTimeInMillis()); NanoTime nt = NanoTimeUtils.getNanoTime(ts, false); Assert.assertEquals(nt.getJulianDay(), 2440000); Timestamp tsFetched = NanoTimeUtils.getTimestamp(nt, false); Assert.assertEquals(tsFetched, ts); //check if 30 Julian Days between Jan 1, 2005 and Jan 31, 2005. Calendar cal1 = Calendar.getInstance(); cal1.set(Calendar.YEAR, 2005); cal1.set(Calendar.MONTH, Calendar.JANUARY); cal1.set(Calendar.DAY_OF_MONTH, 1); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.setTimeZone(TimeZone.getTimeZone("GMT")); Timestamp ts1 = new Timestamp(cal1.getTimeInMillis()); NanoTime nt1 = NanoTimeUtils.getNanoTime(ts1, false); Timestamp ts1Fetched = NanoTimeUtils.getTimestamp(nt1, false); Assert.assertEquals(ts1Fetched, ts1); Calendar cal2 = Calendar.getInstance(); cal2.set(Calendar.YEAR, 2005); cal2.set(Calendar.MONTH, Calendar.JANUARY); cal2.set(Calendar.DAY_OF_MONTH, 31); cal2.set(Calendar.HOUR_OF_DAY, 0); cal2.setTimeZone(TimeZone.getTimeZone("UTC")); Timestamp ts2 = new Timestamp(cal2.getTimeInMillis()); NanoTime nt2 = NanoTimeUtils.getNanoTime(ts2, false); Timestamp ts2Fetched = NanoTimeUtils.getTimestamp(nt2, false); Assert.assertEquals(ts2Fetched, ts2); Assert.assertEquals(nt2.getJulianDay() - nt1.getJulianDay(), 30); //check if 1464305 Julian Days between Jan 1, 2005 BC and Jan 31, 2005. cal1 = Calendar.getInstance(); cal1.set(Calendar.ERA, GregorianCalendar.BC); cal1.set(Calendar.YEAR, 2005); cal1.set(Calendar.MONTH, Calendar.JANUARY); cal1.set(Calendar.DAY_OF_MONTH, 1); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.setTimeZone(TimeZone.getTimeZone("GMT")); ts1 = new Timestamp(cal1.getTimeInMillis()); nt1 = NanoTimeUtils.getNanoTime(ts1, false); ts1Fetched = NanoTimeUtils.getTimestamp(nt1, false); Assert.assertEquals(ts1Fetched, ts1); cal2 = Calendar.getInstance(); cal2.set(Calendar.YEAR, 2005); cal2.set(Calendar.MONTH, Calendar.JANUARY); cal2.set(Calendar.DAY_OF_MONTH, 31); cal2.set(Calendar.HOUR_OF_DAY, 0); cal2.setTimeZone(TimeZone.getTimeZone("UTC")); ts2 = new Timestamp(cal2.getTimeInMillis()); nt2 = NanoTimeUtils.getNanoTime(ts2, false); ts2Fetched = NanoTimeUtils.getTimestamp(nt2, false); Assert.assertEquals(ts2Fetched, ts2); Assert.assertEquals(nt2.getJulianDay() - nt1.getJulianDay(), 1464305); } public void testNanos() { //case 1: 01:01:01.0000000001 Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 1968); cal.set(Calendar.MONTH, Calendar.MAY); cal.set(Calendar.DAY_OF_MONTH, 23); cal.set(Calendar.HOUR_OF_DAY, 1); cal.set(Calendar.MINUTE, 1); cal.set(Calendar.SECOND, 1); cal.setTimeZone(TimeZone.getTimeZone("GMT")); Timestamp ts = new Timestamp(cal.getTimeInMillis()); ts.setNanos(1); //(1*60*60 + 1*60 + 1) * 10e9 + 1 NanoTime nt = NanoTimeUtils.getNanoTime(ts, false); Assert.assertEquals(nt.getTimeOfDayNanos(), 3661000000001L); //case 2: 23:59:59.999999999 cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 1968); cal.set(Calendar.MONTH, Calendar.MAY); cal.set(Calendar.DAY_OF_MONTH, 23); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.setTimeZone(TimeZone.getTimeZone("GMT")); ts = new Timestamp(cal.getTimeInMillis()); ts.setNanos(999999999); //(23*60*60 + 59*60 + 59)*10e9 + 999999999 nt = NanoTimeUtils.getNanoTime(ts, false); Assert.assertEquals(nt.getTimeOfDayNanos(), 86399999999999L); //case 3: verify the difference. Calendar cal2 = Calendar.getInstance(); cal2.set(Calendar.YEAR, 1968); cal2.set(Calendar.MONTH, Calendar.MAY); cal2.set(Calendar.DAY_OF_MONTH, 23); cal2.set(Calendar.HOUR_OF_DAY, 0); cal2.set(Calendar.MINUTE, 10); cal2.set(Calendar.SECOND, 0); cal2.setTimeZone(TimeZone.getTimeZone("GMT")); Timestamp ts2 = new Timestamp(cal2.getTimeInMillis()); ts2.setNanos(10); Calendar cal1 = Calendar.getInstance(); cal1.set(Calendar.YEAR, 1968); cal1.set(Calendar.MONTH, Calendar.MAY); cal1.set(Calendar.DAY_OF_MONTH, 23); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); cal1.setTimeZone(TimeZone.getTimeZone("GMT")); Timestamp ts1 = new Timestamp(cal1.getTimeInMillis()); ts1.setNanos(1); NanoTime n2 = NanoTimeUtils.getNanoTime(ts2, false); NanoTime n1 = NanoTimeUtils.getNanoTime(ts1, false); Assert.assertEquals(n2.getTimeOfDayNanos() - n1.getTimeOfDayNanos(), 600000000009L); NanoTime n3 = new NanoTime(n1.getJulianDay() - 1, n1.getTimeOfDayNanos() + TimeUnit.DAYS.toNanos(1)); Assert.assertEquals(ts1, NanoTimeUtils.getTimestamp(n3, false)); n3 = new NanoTime(n1.getJulianDay() + 3, n1.getTimeOfDayNanos() - TimeUnit.DAYS.toNanos(3)); Assert.assertEquals(ts1, NanoTimeUtils.getTimestamp(n3, false)); } public void testTimezone() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 1968); cal.set(Calendar.MONTH, Calendar.MAY); cal.set(Calendar.DAY_OF_MONTH, 23); cal.set(Calendar.HOUR_OF_DAY, 17); cal.set(Calendar.MINUTE, 1); cal.set(Calendar.SECOND, 1); cal.setTimeZone(TimeZone.getTimeZone("US/Pacific")); Timestamp ts = new Timestamp(cal.getTimeInMillis()); ts.setNanos(1); /** * 17:00 PDT = 00:00 GMT (daylight-savings) * (0*60*60 + 1*60 + 1)*10e9 + 1 = 61000000001, or * * 17:00 PST = 01:00 GMT (if not daylight savings) * (1*60*60 + 1*60 + 1)*10e9 + 1 = 3661000000001 */ NanoTime nt = NanoTimeUtils.getNanoTime(ts, false); long timeOfDayNanos = nt.getTimeOfDayNanos(); Assert.assertTrue(timeOfDayNanos == 61000000001L || timeOfDayNanos == 3661000000001L); //in both cases, this will be the next day in GMT Assert.assertEquals(nt.getJulianDay(), 2440001); } public void testTimezoneValues() { valueTest(false); } public void testTimezonelessValues() { valueTest(true); } public void testTimezoneless() { Timestamp ts1 = Timestamp.valueOf("2011-01-01 00:30:30.111111111"); NanoTime nt1 = NanoTimeUtils.getNanoTime(ts1, true); Assert.assertEquals(nt1.getJulianDay(), 2455563); Assert.assertEquals(nt1.getTimeOfDayNanos(), 1830111111111L); Timestamp ts1Fetched = NanoTimeUtils.getTimestamp(nt1, true); Assert.assertEquals(ts1Fetched.toString(), ts1.toString()); Timestamp ts2 = Timestamp.valueOf("2011-02-02 08:30:30.222222222"); NanoTime nt2 = NanoTimeUtils.getNanoTime(ts2, true); Assert.assertEquals(nt2.getJulianDay(), 2455595); Assert.assertEquals(nt2.getTimeOfDayNanos(), 30630222222222L); Timestamp ts2Fetched = NanoTimeUtils.getTimestamp(nt2, true); Assert.assertEquals(ts2Fetched.toString(), ts2.toString()); } private void valueTest(boolean local) { //exercise a broad range of timestamps close to the present. verifyTsString("2011-01-01 01:01:01.111111111", local); verifyTsString("2012-02-02 02:02:02.222222222", local); verifyTsString("2013-03-03 03:03:03.333333333", local); verifyTsString("2014-04-04 04:04:04.444444444", local); verifyTsString("2015-05-05 05:05:05.555555555", local); verifyTsString("2016-06-06 06:06:06.666666666", local); verifyTsString("2017-07-07 07:07:07.777777777", local); verifyTsString("2018-08-08 08:08:08.888888888", local); verifyTsString("2019-09-09 09:09:09.999999999", local); verifyTsString("2020-10-10 10:10:10.101010101", local); verifyTsString("2021-11-11 11:11:11.111111111", local); verifyTsString("2022-12-12 12:12:12.121212121", local); verifyTsString("2023-01-02 13:13:13.131313131", local); verifyTsString("2024-02-02 14:14:14.141414141", local); verifyTsString("2025-03-03 15:15:15.151515151", local); verifyTsString("2026-04-04 16:16:16.161616161", local); verifyTsString("2027-05-05 17:17:17.171717171", local); verifyTsString("2028-06-06 18:18:18.181818181", local); verifyTsString("2029-07-07 19:19:19.191919191", local); verifyTsString("2030-08-08 20:20:20.202020202", local); verifyTsString("2031-09-09 21:21:21.212121212", local); //test some extreme cases. verifyTsString("9999-09-09 09:09:09.999999999", local); verifyTsString("0001-01-01 00:00:00.0", local); } private void verifyTsString(String tsString, boolean local) { Timestamp ts = Timestamp.valueOf(tsString); NanoTime nt = NanoTimeUtils.getNanoTime(ts, local); Timestamp tsFetched = NanoTimeUtils.getTimestamp(nt, local); Assert.assertEquals(tsString, tsFetched.toString()); } }
/* * @(#)Double.java 1.100 06/04/07 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.lang; import sun.misc.FloatingDecimal; import sun.misc.FpUtils; import sun.misc.DoubleConsts; /** * The <code>Double</code> class wraps a value of the primitive type * <code>double</code> in an object. An object of type * <code>Double</code> contains a single field whose type is * <code>double</code>. * <p> * In addition, this class provides several methods for converting a * <code>double</code> to a <code>String</code> and a * <code>String</code> to a <code>double</code>, as well as other * constants and methods useful when dealing with a * <code>double</code>. * * @author Lee Boynton * @author Arthur van Hoff * @author Joseph D. Darcy * @version 1.100, 04/07/06 * @since JDK1.0 */ public final class Double extends Number implements Comparable<Double> { /** * A constant holding the positive infinity of type * <code>double</code>. It is equal to the value returned by * <code>Double.longBitsToDouble(0x7ff0000000000000L)</code>. */ public static final double POSITIVE_INFINITY = 1.0 / 0.0; /** * A constant holding the negative infinity of type * <code>double</code>. It is equal to the value returned by * <code>Double.longBitsToDouble(0xfff0000000000000L)</code>. */ public static final double NEGATIVE_INFINITY = -1.0 / 0.0; /** * A constant holding a Not-a-Number (NaN) value of type * <code>double</code>. It is equivalent to the value returned by * <code>Double.longBitsToDouble(0x7ff8000000000000L)</code>. */ public static final double NaN = 0.0d / 0.0; /** * A constant holding the largest positive finite value of type * <code>double</code>, * (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>. It is equal to * the hexadecimal floating-point literal * <code>0x1.fffffffffffffP+1023</code> and also equal to * <code>Double.longBitsToDouble(0x7fefffffffffffffL)</code>. */ public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308 /** * A constant holding the smallest positive normal value of type * {@code double}, 2<sup>-1022</sup>. It is equal to the * hexadecimal floating-point literal {@code 0x1.0p-1022} and also * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}. * * @since 1.6 */ public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308 /** * A constant holding the smallest positive nonzero value of type * <code>double</code>, 2<sup>-1074</sup>. It is equal to the * hexadecimal floating-point literal * <code>0x0.0000000000001P-1022</code> and also equal to * <code>Double.longBitsToDouble(0x1L)</code>. */ public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324 /** * Maximum exponent a finite {@code double} variable may have. * It is equal to the value returned by * {@code Math.getExponent(Double.MAX_VALUE)}. * * @since 1.6 */ public static final int MAX_EXPONENT = 1023; /** * Minimum exponent a normalized {@code double} variable may * have. It is equal to the value returned by * {@code Math.getExponent(Double.MIN_NORMAL)}. * * @since 1.6 */ public static final int MIN_EXPONENT = -1022; /** * The number of bits used to represent a <tt>double</tt> value. * * @since 1.5 */ public static final int SIZE = 64; /** * The <code>Class</code> instance representing the primitive type * <code>double</code>. * * @since JDK1.1 */ public static final Class<Double> TYPE = (Class<Double>) Class.getPrimitiveClass("double"); /** * Returns a string representation of the <code>double</code> * argument. All characters mentioned below are ASCII characters. * <ul> * <li>If the argument is NaN, the result is the string * &quot;<code>NaN</code>&quot;. * <li>Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. If the sign is negative, * the first character of the result is '<code>-</code>' * (<code>'&#92;u002D'</code>); if the sign is positive, no sign character * appears in the result. As for the magnitude <i>m</i>: * <ul> * <li>If <i>m</i> is infinity, it is represented by the characters * <code>"Infinity"</code>; thus, positive infinity produces the result * <code>"Infinity"</code> and negative infinity produces the result * <code>"-Infinity"</code>. * * <li>If <i>m</i> is zero, it is represented by the characters * <code>"0.0"</code>; thus, negative zero produces the result * <code>"-0.0"</code> and positive zero produces the result * <code>"0.0"</code>. * * <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less * than 10<sup>7</sup>, then it is represented as the integer part of * <i>m</i>, in decimal form with no leading zeroes, followed by * '<code>.</code>' (<code>'&#92;u002E'</code>), followed by one or * more decimal digits representing the fractional part of <i>m</i>. * * <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or * equal to 10<sup>7</sup>, then it is represented in so-called * "computerized scientific notation." Let <i>n</i> be the unique * integer such that 10<sup><i>n</i></sup> &lt;= <i>m</i> &lt; * 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the * mathematically exact quotient of <i>m</i> and * 10<sup><i>n</i></sup> so that 1 &lt;= <i>a</i> &lt; 10. The * magnitude is then represented as the integer part of <i>a</i>, * as a single decimal digit, followed by '<code>.</code>' * (<code>'&#92;u002E'</code>), followed by decimal digits * representing the fractional part of <i>a</i>, followed by the * letter '<code>E</code>' (<code>'&#92;u0045'</code>), followed * by a representation of <i>n</i> as a decimal integer, as * produced by the method {@link Integer#toString(int)}. * </ul> * </ul> * How many digits must be printed for the fractional part of * <i>m</i> or <i>a</i>? There must be at least one digit to represent * the fractional part, and beyond that as many, but only as many, more * digits as are needed to uniquely distinguish the argument value from * adjacent values of type <code>double</code>. That is, suppose that * <i>x</i> is the exact mathematical value represented by the decimal * representation produced by this method for a finite nonzero argument * <i>d</i>. Then <i>d</i> must be the <code>double</code> value nearest * to <i>x</i>; or if two <code>double</code> values are equally close * to <i>x</i>, then <i>d</i> must be one of them and the least * significant bit of the significand of <i>d</i> must be <code>0</code>. * <p> * To create localized string representations of a floating-point * value, use subclasses of {@link java.text.NumberFormat}. * * @param d the <code>double</code> to be converted. * @return a string representation of the argument. */ public static String toString(double d) { return new FloatingDecimal(d).toJavaFormatString(); } /** * Returns a hexadecimal string representation of the * <code>double</code> argument. All characters mentioned below * are ASCII characters. * * <ul> * <li>If the argument is NaN, the result is the string * &quot;<code>NaN</code>&quot;. * <li>Otherwise, the result is a string that represents the sign * and magnitude of the argument. If the sign is negative, the * first character of the result is '<code>-</code>' * (<code>'&#92;u002D'</code>); if the sign is positive, no sign * character appears in the result. As for the magnitude <i>m</i>: * * <ul> * <li>If <i>m</i> is infinity, it is represented by the string * <code>"Infinity"</code>; thus, positive infinity produces the * result <code>"Infinity"</code> and negative infinity produces * the result <code>"-Infinity"</code>. * * <li>If <i>m</i> is zero, it is represented by the string * <code>"0x0.0p0"</code>; thus, negative zero produces the result * <code>"-0x0.0p0"</code> and positive zero produces the result * <code>"0x0.0p0"</code>. * * <li>If <i>m</i> is a <code>double</code> value with a * normalized representation, substrings are used to represent the * significand and exponent fields. The significand is * represented by the characters <code>&quot;0x1.&quot;</code> * followed by a lowercase hexadecimal representation of the rest * of the significand as a fraction. Trailing zeros in the * hexadecimal representation are removed unless all the digits * are zero, in which case a single zero is used. Next, the * exponent is represented by <code>&quot;p&quot;</code> followed * by a decimal string of the unbiased exponent as if produced by * a call to {@link Integer#toString(int) Integer.toString} on the * exponent value. * * <li>If <i>m</i> is a <code>double</code> value with a subnormal * representation, the significand is represented by the * characters <code>&quot;0x0.&quot;</code> followed by a * hexadecimal representation of the rest of the significand as a * fraction. Trailing zeros in the hexadecimal representation are * removed. Next, the exponent is represented by * <code>&quot;p-1022&quot;</code>. Note that there must be at * least one nonzero digit in a subnormal significand. * * </ul> * * </ul> * * <table border> * <caption><h3>Examples</h3></caption> * <tr><th>Floating-point Value</th><th>Hexadecimal String</th> * <tr><td><code>1.0</code></td> <td><code>0x1.0p0</code></td> * <tr><td><code>-1.0</code></td> <td><code>-0x1.0p0</code></td> * <tr><td><code>2.0</code></td> <td><code>0x1.0p1</code></td> * <tr><td><code>3.0</code></td> <td><code>0x1.8p1</code></td> * <tr><td><code>0.5</code></td> <td><code>0x1.0p-1</code></td> * <tr><td><code>0.25</code></td> <td><code>0x1.0p-2</code></td> * <tr><td><code>Double.MAX_VALUE</code></td> * <td><code>0x1.fffffffffffffp1023</code></td> * <tr><td><code>Minimum Normal Value</code></td> * <td><code>0x1.0p-1022</code></td> * <tr><td><code>Maximum Subnormal Value</code></td> * <td><code>0x0.fffffffffffffp-1022</code></td> * <tr><td><code>Double.MIN_VALUE</code></td> * <td><code>0x0.0000000000001p-1022</code></td> * </table> * @param d the <code>double</code> to be converted. * @return a hex string representation of the argument. * @since 1.5 * @author Joseph D. Darcy */ public static String toHexString(double d) { /* * Modeled after the "a" conversion specifier in C99, section * 7.19.6.1; however, the output of this method is more * tightly specified. */ if (!FpUtils.isFinite(d) ) // For infinity and NaN, use the decimal output. return Double.toString(d); else { // Initialized to maximum size of output. StringBuffer answer = new StringBuffer(24); if (FpUtils.rawCopySign(1.0, d) == -1.0) // value is negative, answer.append("-"); // so append sign info answer.append("0x"); d = Math.abs(d); if(d == 0.0) { answer.append("0.0p0"); } else { boolean subnormal = (d < DoubleConsts.MIN_NORMAL); // Isolate significand bits and OR in a high-order bit // so that the string representation has a known // length. long signifBits = (Double.doubleToLongBits(d) & DoubleConsts.SIGNIF_BIT_MASK) | 0x1000000000000000L; // Subnormal values have a 0 implicit bit; normal // values have a 1 implicit bit. answer.append(subnormal ? "0." : "1."); // Isolate the low-order 13 digits of the hex // representation. If all the digits are zero, // replace with a single 0; otherwise, remove all // trailing zeros. String signif = Long.toHexString(signifBits).substring(3,16); answer.append(signif.equals("0000000000000") ? // 13 zeros "0": signif.replaceFirst("0{1,12}$", "")); // If the value is subnormal, use the E_min exponent // value for double; otherwise, extract and report d's // exponent (the representation of a subnormal uses // E_min -1). answer.append("p" + (subnormal ? DoubleConsts.MIN_EXPONENT: FpUtils.getExponent(d) )); } return answer.toString(); } } /** * Returns a <code>Double</code> object holding the * <code>double</code> value represented by the argument string * <code>s</code>. * * <p>If <code>s</code> is <code>null</code>, then a * <code>NullPointerException</code> is thrown. * * <p>Leading and trailing whitespace characters in <code>s</code> * are ignored. Whitespace is removed as if by the {@link * String#trim} method; that is, both ASCII space and control * characters are removed. The rest of <code>s</code> should * constitute a <i>FloatValue</i> as described by the lexical * syntax rules: * * <blockquote> * <dl> * <dt><i>FloatValue:</i> * <dd><i>Sign<sub>opt</sub></i> <code>NaN</code> * <dd><i>Sign<sub>opt</sub></i> <code>Infinity</code> * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i> * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i> * <dd><i>SignedInteger</i> * </dl> * * <p> * * <dl> * <dt><i>HexFloatingPointLiteral</i>: * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i> * </dl> * * <p> * * <dl> * <dt><i>HexSignificand:</i> * <dd><i>HexNumeral</i> * <dd><i>HexNumeral</i> <code>.</code> * <dd><code>0x</code> <i>HexDigits<sub>opt</sub> * </i><code>.</code><i> HexDigits</i> * <dd><code>0X</code><i> HexDigits<sub>opt</sub> * </i><code>.</code> <i>HexDigits</i> * </dl> * * <p> * * <dl> * <dt><i>BinaryExponent:</i> * <dd><i>BinaryExponentIndicator SignedInteger</i> * </dl> * * <p> * * <dl> * <dt><i>BinaryExponentIndicator:</i> * <dd><code>p</code> * <dd><code>P</code> * </dl> * * </blockquote> * * where <i>Sign</i>, <i>FloatingPointLiteral</i>, * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and * <i>FloatTypeSuffix</i> are as defined in the lexical structure * sections of the of the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>. If <code>s</code> does not have the form of * a <i>FloatValue</i>, then a <code>NumberFormatException</code> * is thrown. Otherwise, <code>s</code> is regarded as * representing an exact decimal value in the usual * &quot;computerized scientific notation&quot; or as an exact * hexadecimal value; this exact numerical value is then * conceptually converted to an &quot;infinitely precise&quot; * binary value that is then rounded to type <code>double</code> * by the usual round-to-nearest rule of IEEE 754 floating-point * arithmetic, which includes preserving the sign of a zero * value. Finally, a <code>Double</code> object representing this * <code>double</code> value is returned. * * <p> To interpret localized string representations of a * floating-point value, use subclasses of {@link * java.text.NumberFormat}. * * <p>Note that trailing format specifiers, specifiers that * determine the type of a floating-point literal * (<code>1.0f</code> is a <code>float</code> value; * <code>1.0d</code> is a <code>double</code> value), do * <em>not</em> influence the results of this method. In other * words, the numerical value of the input string is converted * directly to the target floating-point type. The two-step * sequence of conversions, string to <code>float</code> followed * by <code>float</code> to <code>double</code>, is <em>not</em> * equivalent to converting a string directly to * <code>double</code>. For example, the <code>float</code> * literal <code>0.1f</code> is equal to the <code>double</code> * value <code>0.10000000149011612</code>; the <code>float</code> * literal <code>0.1f</code> represents a different numerical * value than the <code>double</code> literal * <code>0.1</code>. (The numerical value 0.1 cannot be exactly * represented in a binary floating-point number.) * * <p>To avoid calling this method on an invalid string and having * a <code>NumberFormatException</code> be thrown, the regular * expression below can be used to screen the input string: * * <code> * <pre> * final String Digits = "(\\p{Digit}+)"; * final String HexDigits = "(\\p{XDigit}+)"; * // an exponent is 'e' or 'E' followed by an optionally * // signed decimal integer. * final String Exp = "[eE][+-]?"+Digits; * final String fpRegex = * ("[\\x00-\\x20]*"+ // Optional leading &quot;whitespace&quot; * "[+-]?(" + // Optional sign character * "NaN|" + // "NaN" string * "Infinity|" + // "Infinity" string * * // A decimal floating-point string representing a finite positive * // number without a leading sign has at most five basic pieces: * // Digits . Digits ExponentPart FloatTypeSuffix * // * // Since this method allows integer-only strings as input * // in addition to strings of floating-point literals, the * // two sub-patterns below are simplifications of the grammar * // productions from the Java Language Specification, 2nd * // edition, section 3.10.2. * * // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt * "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ * * // . Digits ExponentPart_opt FloatTypeSuffix_opt * "(\\.("+Digits+")("+Exp+")?)|"+ * * // Hexadecimal strings * "((" + * // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt * "(0[xX]" + HexDigits + "(\\.)?)|" + * * // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt * "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + * * ")[pP][+-]?" + Digits + "))" + * "[fFdD]?))" + * "[\\x00-\\x20]*");// Optional trailing &quot;whitespace&quot; * * if (Pattern.matches(fpRegex, myString)) * Double.valueOf(myString); // Will not throw NumberFormatException * else { * // Perform suitable alternative action * } * </pre> * </code> * * @param s the string to be parsed. * @return a <code>Double</code> object holding the value * represented by the <code>String</code> argument. * @exception NumberFormatException if the string does not contain a * parsable number. */ public static Double valueOf(String s) throws NumberFormatException { return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue()); } /** * Returns a <tt>Double</tt> instance representing the specified * <tt>double</tt> value. * If a new <tt>Double</tt> instance is not required, this method * should generally be used in preference to the constructor * {@link #Double(double)}, as this method is likely to yield * significantly better space and time performance by caching * frequently requested values. * * @param d a double value. * @return a <tt>Double</tt> instance representing <tt>d</tt>. * @since 1.5 */ public static Double valueOf(double d) { return new Double(d); } /** * Returns a new <code>double</code> initialized to the value * represented by the specified <code>String</code>, as performed * by the <code>valueOf</code> method of class * <code>Double</code>. * * @param s the string to be parsed. * @return the <code>double</code> value represented by the string * argument. * @exception NumberFormatException if the string does not contain * a parsable <code>double</code>. * @see java.lang.Double#valueOf(String) * @since 1.2 */ public static double parseDouble(String s) throws NumberFormatException { return FloatingDecimal.readJavaFormatString(s).doubleValue(); } /** * Returns <code>true</code> if the specified number is a * Not-a-Number (NaN) value, <code>false</code> otherwise. * * @param v the value to be tested. * @return <code>true</code> if the value of the argument is NaN; * <code>false</code> otherwise. */ static public boolean isNaN(double v) { return (v != v); } /** * Returns <code>true</code> if the specified number is infinitely * large in magnitude, <code>false</code> otherwise. * * @param v the value to be tested. * @return <code>true</code> if the value of the argument is positive * infinity or negative infinity; <code>false</code> otherwise. */ static public boolean isInfinite(double v) { return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); } /** * The value of the Double. * * @serial */ private final double value; /** * Constructs a newly allocated <code>Double</code> object that * represents the primitive <code>double</code> argument. * * @param value the value to be represented by the <code>Double</code>. */ public Double(double value) { this.value = value; } /** * Constructs a newly allocated <code>Double</code> object that * represents the floating-point value of type <code>double</code> * represented by the string. The string is converted to a * <code>double</code> value as if by the <code>valueOf</code> method. * * @param s a string to be converted to a <code>Double</code>. * @exception NumberFormatException if the string does not contain a * parsable number. * @see java.lang.Double#valueOf(java.lang.String) */ public Double(String s) throws NumberFormatException { // REMIND: this is inefficient this(valueOf(s).doubleValue()); } /** * Returns <code>true</code> if this <code>Double</code> value is * a Not-a-Number (NaN), <code>false</code> otherwise. * * @return <code>true</code> if the value represented by this object is * NaN; <code>false</code> otherwise. */ public boolean isNaN() { return isNaN(value); } /** * Returns <code>true</code> if this <code>Double</code> value is * infinitely large in magnitude, <code>false</code> otherwise. * * @return <code>true</code> if the value represented by this object is * positive infinity or negative infinity; * <code>false</code> otherwise. */ public boolean isInfinite() { return isInfinite(value); } /** * Returns a string representation of this <code>Double</code> object. * The primitive <code>double</code> value represented by this * object is converted to a string exactly as if by the method * <code>toString</code> of one argument. * * @return a <code>String</code> representation of this object. * @see java.lang.Double#toString(double) */ public String toString() { return String.valueOf(value); } /** * Returns the value of this <code>Double</code> as a <code>byte</code> (by * casting to a <code>byte</code>). * * @return the <code>double</code> value represented by this object * converted to type <code>byte</code> * @since JDK1.1 */ public byte byteValue() { return (byte)value; } /** * Returns the value of this <code>Double</code> as a * <code>short</code> (by casting to a <code>short</code>). * * @return the <code>double</code> value represented by this object * converted to type <code>short</code> * @since JDK1.1 */ public short shortValue() { return (short)value; } /** * Returns the value of this <code>Double</code> as an * <code>int</code> (by casting to type <code>int</code>). * * @return the <code>double</code> value represented by this object * converted to type <code>int</code> */ public int intValue() { return (int)value; } /** * Returns the value of this <code>Double</code> as a * <code>long</code> (by casting to type <code>long</code>). * * @return the <code>double</code> value represented by this object * converted to type <code>long</code> */ public long longValue() { return (long)value; } /** * Returns the <code>float</code> value of this * <code>Double</code> object. * * @return the <code>double</code> value represented by this object * converted to type <code>float</code> * @since JDK1.0 */ public float floatValue() { return (float)value; } /** * Returns the <code>double</code> value of this * <code>Double</code> object. * * @return the <code>double</code> value represented by this object */ public double doubleValue() { return (double)value; } /** * Returns a hash code for this <code>Double</code> object. The * result is the exclusive OR of the two halves of the * <code>long</code> integer bit representation, exactly as * produced by the method {@link #doubleToLongBits(double)}, of * the primitive <code>double</code> value represented by this * <code>Double</code> object. That is, the hash code is the value * of the expression: * <blockquote><pre> * (int)(v^(v&gt;&gt;&gt;32)) * </pre></blockquote> * where <code>v</code> is defined by: * <blockquote><pre> * long v = Double.doubleToLongBits(this.doubleValue()); * </pre></blockquote> * * @return a <code>hash code</code> value for this object. */ public int hashCode() { long bits = doubleToLongBits(value); return (int)(bits ^ (bits >>> 32)); } /** * Compares this object against the specified object. The result * is <code>true</code> if and only if the argument is not * <code>null</code> and is a <code>Double</code> object that * represents a <code>double</code> that has the same value as the * <code>double</code> represented by this object. For this * purpose, two <code>double</code> values are considered to be * the same if and only if the method {@link * #doubleToLongBits(double)} returns the identical * <code>long</code> value when applied to each. * <p> * Note that in most cases, for two instances of class * <code>Double</code>, <code>d1</code> and <code>d2</code>, the * value of <code>d1.equals(d2)</code> is <code>true</code> if and * only if * <blockquote><pre> * d1.doubleValue()&nbsp;== d2.doubleValue() * </pre></blockquote> * <p> * also has the value <code>true</code>. However, there are two * exceptions: * <ul> * <li>If <code>d1</code> and <code>d2</code> both represent * <code>Double.NaN</code>, then the <code>equals</code> method * returns <code>true</code>, even though * <code>Double.NaN==Double.NaN</code> has the value * <code>false</code>. * <li>If <code>d1</code> represents <code>+0.0</code> while * <code>d2</code> represents <code>-0.0</code>, or vice versa, * the <code>equal</code> test has the value <code>false</code>, * even though <code>+0.0==-0.0</code> has the value <code>true</code>. * </ul> * This definition allows hash tables to operate properly. * @param obj the object to compare with. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. * @see java.lang.Double#doubleToLongBits(double) */ public boolean equals(Object obj) { return (obj instanceof Double) && (doubleToLongBits(((Double)obj).value) == doubleToLongBits(value)); } /** * Returns a representation of the specified floating-point value * according to the IEEE 754 floating-point "double * format" bit layout. * <p> * Bit 63 (the bit that is selected by the mask * <code>0x8000000000000000L</code>) represents the sign of the * floating-point number. Bits * 62-52 (the bits that are selected by the mask * <code>0x7ff0000000000000L</code>) represent the exponent. Bits 51-0 * (the bits that are selected by the mask * <code>0x000fffffffffffffL</code>) represent the significand * (sometimes called the mantissa) of the floating-point number. * <p> * If the argument is positive infinity, the result is * <code>0x7ff0000000000000L</code>. * <p> * If the argument is negative infinity, the result is * <code>0xfff0000000000000L</code>. * <p> * If the argument is NaN, the result is * <code>0x7ff8000000000000L</code>. * <p> * In all cases, the result is a <code>long</code> integer that, when * given to the {@link #longBitsToDouble(long)} method, will produce a * floating-point value the same as the argument to * <code>doubleToLongBits</code> (except all NaN values are * collapsed to a single &quot;canonical&quot; NaN value). * * @param value a <code>double</code> precision floating-point number. * @return the bits that represent the floating-point number. */ public static long doubleToLongBits(double value) { long result = doubleToRawLongBits(value); // Check for NaN based on values of bit fields, maximum // exponent and nonzero significand. if ( ((result & DoubleConsts.EXP_BIT_MASK) == DoubleConsts.EXP_BIT_MASK) && (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L) result = 0x7ff8000000000000L; return result; } /** * Returns a representation of the specified floating-point value * according to the IEEE 754 floating-point "double * format" bit layout, preserving Not-a-Number (NaN) values. * <p> * Bit 63 (the bit that is selected by the mask * <code>0x8000000000000000L</code>) represents the sign of the * floating-point number. Bits * 62-52 (the bits that are selected by the mask * <code>0x7ff0000000000000L</code>) represent the exponent. Bits 51-0 * (the bits that are selected by the mask * <code>0x000fffffffffffffL</code>) represent the significand * (sometimes called the mantissa) of the floating-point number. * <p> * If the argument is positive infinity, the result is * <code>0x7ff0000000000000L</code>. * <p> * If the argument is negative infinity, the result is * <code>0xfff0000000000000L</code>. * <p> * If the argument is NaN, the result is the <code>long</code> * integer representing the actual NaN value. Unlike the * <code>doubleToLongBits</code> method, * <code>doubleToRawLongBits</code> does not collapse all the bit * patterns encoding a NaN to a single &quot;canonical&quot; NaN * value. * <p> * In all cases, the result is a <code>long</code> integer that, * when given to the {@link #longBitsToDouble(long)} method, will * produce a floating-point value the same as the argument to * <code>doubleToRawLongBits</code>. * * @param value a <code>double</code> precision floating-point number. * @return the bits that represent the floating-point number. * @since 1.3 */ public static native long doubleToRawLongBits(double value); /** * Returns the <code>double</code> value corresponding to a given * bit representation. * The argument is considered to be a representation of a * floating-point value according to the IEEE 754 floating-point * "double format" bit layout. * <p> * If the argument is <code>0x7ff0000000000000L</code>, the result * is positive infinity. * <p> * If the argument is <code>0xfff0000000000000L</code>, the result * is negative infinity. * <p> * If the argument is any value in the range * <code>0x7ff0000000000001L</code> through * <code>0x7fffffffffffffffL</code> or in the range * <code>0xfff0000000000001L</code> through * <code>0xffffffffffffffffL</code>, the result is a NaN. No IEEE * 754 floating-point operation provided by Java can distinguish * between two NaN values of the same type with different bit * patterns. Distinct values of NaN are only distinguishable by * use of the <code>Double.doubleToRawLongBits</code> method. * <p> * In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three * values that can be computed from the argument: * <blockquote><pre> * int s = ((bits &gt;&gt; 63) == 0) ? 1 : -1; * int e = (int)((bits &gt;&gt; 52) & 0x7ffL); * long m = (e == 0) ? * (bits & 0xfffffffffffffL) &lt;&lt; 1 : * (bits & 0xfffffffffffffL) | 0x10000000000000L; * </pre></blockquote> * Then the floating-point result equals the value of the mathematical * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-1075</sup>. *<p> * Note that this method may not be able to return a * <code>double</code> NaN with exactly same bit pattern as the * <code>long</code> argument. IEEE 754 distinguishes between two * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The * differences between the two kinds of NaN are generally not * visible in Java. Arithmetic operations on signaling NaNs turn * them into quiet NaNs with a different, but often similar, bit * pattern. However, on some processors merely copying a * signaling NaN also performs that conversion. In particular, * copying a signaling NaN to return it to the calling method * may perform this conversion. So <code>longBitsToDouble</code> * may not be able to return a <code>double</code> with a * signaling NaN bit pattern. Consequently, for some * <code>long</code> values, * <code>doubleToRawLongBits(longBitsToDouble(start))</code> may * <i>not</i> equal <code>start</code>. Moreover, which * particular bit patterns represent signaling NaNs is platform * dependent; although all NaN bit patterns, quiet or signaling, * must be in the NaN range identified above. * * @param bits any <code>long</code> integer. * @return the <code>double</code> floating-point value with the same * bit pattern. */ public static native double longBitsToDouble(long bits); /** * Compares two <code>Double</code> objects numerically. There * are two ways in which comparisons performed by this method * differ from those performed by the Java language numerical * comparison operators (<code>&lt;, &lt;=, ==, &gt;= &gt;</code>) * when applied to primitive <code>double</code> values: * <ul><li> * <code>Double.NaN</code> is considered by this method * to be equal to itself and greater than all other * <code>double</code> values (including * <code>Double.POSITIVE_INFINITY</code>). * <li> * <code>0.0d</code> is considered by this method to be greater * than <code>-0.0d</code>. * </ul> * This ensures that the <i>natural ordering</i> of * <tt>Double</tt> objects imposed by this method is <i>consistent * with equals</i>. * * @param anotherDouble the <code>Double</code> to be compared. * @return the value <code>0</code> if <code>anotherDouble</code> is * numerically equal to this <code>Double</code>; a value * less than <code>0</code> if this <code>Double</code> * is numerically less than <code>anotherDouble</code>; * and a value greater than <code>0</code> if this * <code>Double</code> is numerically greater than * <code>anotherDouble</code>. * * @since 1.2 */ public int compareTo(Double anotherDouble) { return Double.compare(value, anotherDouble.value); } /** * Compares the two specified <code>double</code> values. The sign * of the integer value returned is the same as that of the * integer that would be returned by the call: * <pre> * new Double(d1).compareTo(new Double(d2)) * </pre> * * @param d1 the first <code>double</code> to compare * @param d2 the second <code>double</code> to compare * @return the value <code>0</code> if <code>d1</code> is * numerically equal to <code>d2</code>; a value less than * <code>0</code> if <code>d1</code> is numerically less than * <code>d2</code>; and a value greater than <code>0</code> * if <code>d1</code> is numerically greater than * <code>d2</code>. * @since 1.4 */ public static int compare(double d1, double d2) { if (d1 < d2) return -1; // Neither val is NaN, thisVal is smaller if (d1 > d2) return 1; // Neither val is NaN, thisVal is larger long thisBits = Double.doubleToLongBits(d1); long anotherBits = Double.doubleToLongBits(d2); return (thisBits == anotherBits ? 0 : // Values are equal (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1)); // (0.0, -0.0) or (NaN, !NaN) } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -9172774392245257468L; }
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Wed 12 Jul 2017 at 16:10:00 PST by ian morris nieves // modified on Sat 23 February 2008 at 10:32:25 PST by lamport // modified on Fri Aug 10 15:07:47 PDT 2001 by yuanyu /*************************************************************************** * Change to model values made by LL on 23 Feb 2008: * * ------ * * A model value whose name is "x_str" for any character x and string str * * is said to have TYPE 'x'. Otherwise, it is said to be untyped. It is * * an error to test if a typed model value is equal to any value except a * * model value that is either untyped or has the same type. (As before, * * an untyped model value is unequal to any value except itself.) * * * * This was implemented by adding a `type' field to a ModelValue object * * and making changes to the following classes: * * * * changed member method * * module/Integers.java * * module/Naturals.java * * module/Sequences.java * * module/Strings.java * * value/IntervalValue.java CHECK THIS with mv \notin 1..2 * * value/SetOfFcnsValue.java * * value/SetOfRcdsValue.java * * value/SetOfTuplesValue.java * * value/StringValue.java * * changed equals method * * value/BoolValue.java * * value/FcnRcdValue.java * * value/IntValue.java * * value/RecordValue.java * * value/SetEnumValue.java * ***************************************************************************/ package tlc2.value.impl; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import tlc2.tool.FingerprintException; import tlc2.util.FP64; import tlc2.value.IMVPerm; import tlc2.value.IModelValue; import tlc2.value.IValue; import tlc2.value.IValueOutputStream; import tlc2.value.Values; import util.Assert; import util.UniqueString; public class ModelValue extends Value implements IModelValue { /** * A method to reset the model values * All callers should make sure that the model value class has been initialized */ public static void init() { count = 0; mvTable = new Hashtable<String, ModelValue>(); mvs = null; } /** * Workround to the static usage */ static { init(); } private static int count; private static Hashtable<String, ModelValue> mvTable; // SZ Mar 9, 2009: public accessed field, this will cause troubles public static ModelValue[] mvs; public UniqueString val; public int index; public char type; // type = 0 means untyped. /* Constructor */ private ModelValue(String val) { // SZ 11.04.2009: changed access method this.val = UniqueString.uniqueStringOf(val); this.index = count++; if ( (val.length() > 2) && (val.charAt(1) == '_')) { this.type = val.charAt(0) ; } else { this.type = 0 ; } } /* Make str a new model value, if it is not one yet. */ public static Value make(String str) { ModelValue mv = (ModelValue)mvTable.get(str); if (mv != null) return mv; mv = new ModelValue(str); mvTable.put(str, mv); return mv; } public static Value add(String str) { ModelValue mv = (ModelValue)mvTable.get(str); if (mv != null) return mv; mv = new ModelValue(str); mvTable.put(str, mv); // Contrary to the make method above, this method can be invoked // *after* setValues below has been called from Spec. Thus, we // re-create mvs here. However, this will only work if add is // called by SpecProcessor as part of constant processing. add // cannot be called from the initial predicate, let alone the // next-state relation. Except bogus behavior such as // FingerprintException, NullPointers, ... or serialization // and deserialization in the StateQueue to fail. setValues(); return mv; } /* Collect all the model values defined thus far. */ public static void setValues() { mvs = new ModelValue[mvTable.size()]; Enumeration Enum = mvTable.elements(); while (Enum.hasMoreElements()) { ModelValue mv = (ModelValue)Enum.nextElement(); mvs[mv.index] = mv; } } @Override public final byte getKind() { return MODELVALUE; } /* * #### Typed Model Values * * One way that TLC finds bugs is by reporting an error if it tries to compare * two incomparable values&mdash;for example, a string and a set. The use of * model values can cause TLC to miss bugs because it will compare a model value * to any value without complaining (finding it unequal to anything but itself). * Typed model values have been introduced to solve this problem. * * For any character &tau;, a model value whose name begins with the * two-character string "&tau;\_" is defined to have type &tau;. For example, * the model value _x\_1_ has type _x_. Any other model value is untyped. TLC * treats untyped model values as before, being willing to compare them to * anything. However it reports an error if it tries to compare a typed model * value to anything other than a model value of the same type or an untyped * model value. Thus, TLC will find the model value _x_1_ unequal to the model * values _x_ab2_ and _none_, but will report an error if it tries to compare * _x\_1_ to _a\_1_. */ @Override public final int compareTo(Object obj) { try { if (this.type == 0) { if (obj instanceof ModelValue) { return this.val.compareTo(((ModelValue) obj).val); } else { return -1; } } if (obj instanceof ModelValue) { ModelValue mobj = (ModelValue) obj; if ((mobj.type == this.type) || (mobj.type == 0)) { return this.val.compareTo(((ModelValue) obj).val); } else { Assert.fail("Attempted to compare the differently-typed model values " + Values.ppr(this.toString()) + " and " + Values.ppr(mobj.toString()), getSource()); } } Assert.fail("Attempted to compare the typed model value " + Values.ppr(this.toString()) + " and non-model value\n" + Values.ppr(obj.toString()), getSource()); return -1; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final boolean equals(Object obj) { try { if (this.type == 0) { return (obj instanceof ModelValue && this.val.equals(((ModelValue)obj).val)); } if (obj instanceof ModelValue) { ModelValue mobj = (ModelValue) obj ; if ( (mobj.type == this.type) || (mobj.type == 0) ) { return mobj.val == this.val ; } else { Assert.fail("Attempted to check equality " + "of the differently-typed model values " + Values.ppr(this.toString()) + " and " + Values.ppr(mobj.toString()), getSource()); } } Assert.fail("Attempted to check equality of typed model value " + Values.ppr(this.toString()) + " and non-model value\n" + Values.ppr(obj.toString()), getSource()) ; return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final int modelValueCompareTo(final Object obj){ try { if (this.type != 0) { Assert.fail("Attempted to compare the typed model value " + Values.ppr(this.toString()) + " and the non-model value\n" + Values.ppr(obj.toString()), getSource()) ; } return 1 ; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } /************************************************************************* * The following two methods are used used to check if this model value * * equal to or a member of non-model value obj. They return false if * * this model value is untyped and raise an exception if it is typed. * *************************************************************************/ public final boolean modelValueEquals(Object obj){ try { if (this.type != 0) { Assert.fail("Attempted to check equality of the typed model value " + Values.ppr(this.toString()) + " and the non-model value\n" + Values.ppr(obj.toString()), getSource()) ; } return false ; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final boolean modelValueMember(Object obj){ try { if (this.type != 0) { Assert.fail("Attempted to check if the typed model value " + Values.ppr(this.toString()) + " is an element of\n" + Values.ppr(obj.toString()), getSource()) ; } return false ; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean member(Value elem) { try { Assert.fail("Attempted to check if the value:\n" + Values.ppr(elem.toString()) + "\nis an element of the model value " + Values.ppr(this.toString()), getSource()); return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isFinite() { try { Assert.fail("Attempted to check if the model value " + Values.ppr(this.toString()) + " is a finite set.", getSource()); return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value takeExcept(ValueExcept ex) { try { if (ex.idx < ex.path.length) { Assert.fail("Attempted to apply EXCEPT construct to the model value " + Values.ppr(this.toString()) + ".", getSource()); } return ex.value; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value takeExcept(ValueExcept[] exs) { try { if (exs.length != 0) { Assert.fail("Attempted to apply EXCEPT construct to the model value " + Values.ppr(this.toString()) + ".", getSource()); } return this; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final int size() { try { Assert.fail("Attempted to compute the number of elements in the model value " + Values.ppr(this.toString()) + ".", getSource()); return 0; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public boolean mutates() { return false; } @Override public final boolean isNormalized() { return true; } @Override public final Value normalize() { /*nop*/return this; } @Override public final boolean isDefined() { return true; } @Override public final IValue deepCopy() { return this; } @Override public final boolean assignable(Value val) { try { return ((val instanceof ModelValue) && this.val.equals(((ModelValue)val).val)); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public void write(IValueOutputStream vos) throws IOException { vos.writeByte(MODELVALUE); vos.writeShort((short) index); } /* The fingerprint methods */ @Override public final long fingerPrint(long fp) { try { return this.val.fingerPrint(FP64.Extend(fp, MODELVALUE)); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final IValue permute(IMVPerm perm) { try { IValue res = perm.get(this); if (res == null) return this; return res; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } /* The string representation. */ @Override public final StringBuffer toString(StringBuffer sb, int offset, boolean ignored) { try { return sb.append(this.val); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } // The presence of this field is justified by a small number of ModelValue // instances being created overall. private Object data; @Override public boolean hasData() { return data != null; } @Override public Object getData() { return data; } @Override public Object setData(final Object obj) { this.data = obj; return obj; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis2.jaxws.server.endpoint; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.description.AxisService; import org.apache.axis2.jaxws.ExceptionFactory; import org.apache.axis2.jaxws.addressing.util.EndpointReferenceUtils; import org.apache.axis2.jaxws.binding.BindingUtils; import org.apache.axis2.jaxws.description.DescriptionFactory; import org.apache.axis2.jaxws.description.EndpointDescription; import org.apache.axis2.jaxws.description.ServiceDescription; import org.apache.axis2.jaxws.i18n.Messages; import org.apache.axis2.transport.http.HTTPWorkerFactory; import org.apache.axis2.transport.http.server.SimpleHttpServer; import org.apache.axis2.transport.http.server.WorkerFactory; import org.w3c.dom.Element; import javax.xml.namespace.QName; import javax.xml.transform.Source; import javax.xml.ws.Binding; import javax.xml.ws.EndpointReference; import javax.xml.ws.WebServiceException; import javax.xml.ws.wsaddressing.W3CEndpointReference; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; public class EndpointImpl extends javax.xml.ws.Endpoint { private boolean published; private Object implementor; private EndpointDescription endpointDesc; private Binding binding; private SimpleHttpServer server; private List<Source> metadata; private Map<String, Object> properties; private Executor executor; public EndpointImpl(Object o) { implementor = o; initialize(); } public EndpointImpl(Object o, Binding bnd, EndpointDescription ed) { implementor = o; endpointDesc = ed; initialize(); } private void initialize() { if (implementor == null) { throw ExceptionFactory.makeWebServiceException(Messages.getMessage("initErr")); } // If we don't have the necessary metadata, let's go ahead and // create it. if (endpointDesc == null) { ServiceDescription sd = DescriptionFactory.createServiceDescription(implementor.getClass()); endpointDesc = sd.getEndpointDescriptions_AsCollection().iterator().next(); } if (endpointDesc != null && binding == null) { binding = BindingUtils.createBinding(endpointDesc); } published = false; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#getMetadata() */ public List<Source> getMetadata() { return this.metadata; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#setMetadata(java.util.List) */ public void setMetadata(List<Source> list) { this.metadata = list; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#getProperties() */ public Map<String, Object> getProperties() { return this.properties; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#setProperties(java.util.Map) */ public void setProperties(Map<String, Object> properties) { this.properties = properties; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#getBinding() */ public Binding getBinding() { return binding; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#getExecutor() */ public Executor getExecutor() { return this.executor; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#getImplementor() */ public Object getImplementor() { return implementor; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#isPublished() */ public boolean isPublished() { return published; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#publish(java.lang.Object) */ public void publish(Object obj) { } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#publish(java.lang.String) */ public void publish(String s) { int port = -1; String address = s; try { URI uri = new URI(s); port = uri.getPort(); } catch (URISyntaxException e) { } // Default to 8080 if(port == -1){ port = 8080; address = s + ":" + port; } ConfigurationContext ctx = endpointDesc.getServiceDescription().getAxisConfigContext(); if (endpointDesc.getEndpointAddress() == null) endpointDesc.setEndpointAddress(address); try { // For some reason the AxisService has not been added to the ConfigurationContext // at this point, so we need to do it for the service to be available. AxisService svc = endpointDesc.getAxisService(); ctx.getAxisConfiguration().addService(svc); } catch (AxisFault e) { throw ExceptionFactory.makeWebServiceException(e); } // Remove the default "axis2" context root. ctx.setContextRoot("/"); WorkerFactory wf = new HTTPWorkerFactory(); try { server = new SimpleHttpServer(ctx, wf, port); server.init(); server.start(); } catch (IOException e) { throw ExceptionFactory.makeWebServiceException(e); } published = true; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#setExecutor(java.util.concurrent.Executor) */ public void setExecutor(Executor executor) { this.executor = executor; } /* * (non-Javadoc) * @see javax.xml.ws.Endpoint#stop() */ public void stop() { try { if(server != null) { server.destroy(); } } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } @Override public <T extends EndpointReference> T getEndpointReference(Class<T> clazz, Element... referenceParameters) { if (!isPublished()) { throw new WebServiceException("Endpoint is not published"); } if (!BindingUtils.isSOAPBinding(binding.getBindingID())) { throw new UnsupportedOperationException("This method is unsupported for the binding: " + binding.getBindingID()); } EndpointReference jaxwsEPR = null; String addressingNamespace = EndpointReferenceUtils.getAddressingNamespace(clazz); String address = endpointDesc.getEndpointAddress(); QName serviceName = endpointDesc.getServiceQName(); QName portName = endpointDesc.getPortQName(); String wsdlLocation = null; if (metadata != null) { Source wsdlSource = metadata.get(0); if (wsdlSource != null) { wsdlLocation = wsdlSource.getSystemId(); } } org.apache.axis2.addressing.EndpointReference axis2EPR = EndpointReferenceUtils.createAxis2EndpointReference(address, serviceName, portName, wsdlLocation, addressingNamespace); try { EndpointReferenceUtils.addReferenceParameters(axis2EPR, referenceParameters); jaxwsEPR = EndpointReferenceUtils.convertFromAxis2(axis2EPR, addressingNamespace); } catch (Exception e) { throw ExceptionFactory. makeWebServiceException(Messages.getMessage("endpointRefCreationError"), e); } return clazz.cast(jaxwsEPR); } @Override public EndpointReference getEndpointReference(Element... referenceParameters) { return getEndpointReference(W3CEndpointReference.class, referenceParameters); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.spi.PrestoException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimaps; import org.apache.hadoop.fs.Path; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import static com.facebook.presto.hive.HiveErrorCode.HIVE_CONCURRENT_MODIFICATION_DETECTED; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class PartitionUpdate { private final String name; private final UpdateMode updateMode; private final Path writePath; private final Path targetPath; private final List<FileWriteInfo> fileWriteInfos; private final long rowCount; private final long inMemoryDataSizeInBytes; private final long onDiskDataSizeInBytes; @JsonCreator public PartitionUpdate( @JsonProperty("name") String name, @JsonProperty("updateMode") UpdateMode updateMode, @JsonProperty("writePath") String writePath, @JsonProperty("targetPath") String targetPath, @JsonProperty("fileWriteInfos") List<FileWriteInfo> fileWriteInfos, @JsonProperty("rowCount") long rowCount, @JsonProperty("inMemoryDataSizeInBytes") long inMemoryDataSizeInBytes, @JsonProperty("onDiskDataSizeInBytes") long onDiskDataSizeInBytes) { this( name, updateMode, new Path(requireNonNull(writePath, "writePath is null")), new Path(requireNonNull(targetPath, "targetPath is null")), fileWriteInfos, rowCount, inMemoryDataSizeInBytes, onDiskDataSizeInBytes); } public PartitionUpdate( String name, UpdateMode updateMode, Path writePath, Path targetPath, List<FileWriteInfo> fileWriteInfos, long rowCount, long inMemoryDataSizeInBytes, long onDiskDataSizeInBytes) { this.name = requireNonNull(name, "name is null"); this.updateMode = requireNonNull(updateMode, "updateMode is null"); this.writePath = requireNonNull(writePath, "writePath is null"); this.targetPath = requireNonNull(targetPath, "targetPath is null"); this.fileWriteInfos = ImmutableList.copyOf(requireNonNull(fileWriteInfos, "fileWriteInfos is null")); checkArgument(rowCount >= 0, "rowCount is negative: %d", rowCount); this.rowCount = rowCount; checkArgument(inMemoryDataSizeInBytes >= 0, "inMemoryDataSizeInBytes is negative: %d", inMemoryDataSizeInBytes); this.inMemoryDataSizeInBytes = inMemoryDataSizeInBytes; checkArgument(onDiskDataSizeInBytes >= 0, "onDiskDataSizeInBytes is negative: %d", onDiskDataSizeInBytes); this.onDiskDataSizeInBytes = onDiskDataSizeInBytes; } @JsonProperty public String getName() { return name; } @JsonProperty public UpdateMode getUpdateMode() { return updateMode; } public Path getWritePath() { return writePath; } public Path getTargetPath() { return targetPath; } @JsonProperty public List<FileWriteInfo> getFileWriteInfos() { return fileWriteInfos; } @JsonProperty("targetPath") public String getJsonSerializableTargetPath() { return targetPath.toString(); } @JsonProperty("writePath") public String getJsonSerializableWritePath() { return writePath.toString(); } @JsonProperty public long getRowCount() { return rowCount; } @JsonProperty public long getInMemoryDataSizeInBytes() { return inMemoryDataSizeInBytes; } @JsonProperty public long getOnDiskDataSizeInBytes() { return onDiskDataSizeInBytes; } @Override public String toString() { return toStringHelper(this) .add("name", name) .add("updateMode", updateMode) .add("writePath", writePath) .add("targetPath", targetPath) .add("fileWriteInfos", fileWriteInfos) .add("rowCount", rowCount) .add("inMemoryDataSizeInBytes", inMemoryDataSizeInBytes) .add("onDiskDataSizeInBytes", onDiskDataSizeInBytes) .toString(); } public HiveBasicStatistics getStatistics() { return new HiveBasicStatistics(fileWriteInfos.size(), rowCount, inMemoryDataSizeInBytes, onDiskDataSizeInBytes); } public static List<PartitionUpdate> mergePartitionUpdates(Iterable<PartitionUpdate> unMergedUpdates) { ImmutableList.Builder<PartitionUpdate> partitionUpdates = ImmutableList.builder(); for (Collection<PartitionUpdate> partitionGroup : Multimaps.index(unMergedUpdates, PartitionUpdate::getName).asMap().values()) { PartitionUpdate firstPartition = partitionGroup.iterator().next(); ImmutableList.Builder<FileWriteInfo> allFileWriterInfos = ImmutableList.builder(); long totalRowCount = 0; long totalInMemoryDataSizeInBytes = 0; long totalOnDiskDataSizeInBytes = 0; for (PartitionUpdate partition : partitionGroup) { // verify partitions have the same new flag, write path and target path // this shouldn't happen but could if another user added a partition during the write if (partition.getUpdateMode() != firstPartition.getUpdateMode() || !partition.getWritePath().equals(firstPartition.getWritePath()) || !partition.getTargetPath().equals(firstPartition.getTargetPath())) { throw new PrestoException(HIVE_CONCURRENT_MODIFICATION_DETECTED, format("Partition %s was added or modified during INSERT", firstPartition.getName())); } allFileWriterInfos.addAll(partition.getFileWriteInfos()); totalRowCount += partition.getRowCount(); totalInMemoryDataSizeInBytes += partition.getInMemoryDataSizeInBytes(); totalOnDiskDataSizeInBytes += partition.getOnDiskDataSizeInBytes(); } partitionUpdates.add(new PartitionUpdate(firstPartition.getName(), firstPartition.getUpdateMode(), firstPartition.getWritePath(), firstPartition.getTargetPath(), allFileWriterInfos.build(), totalRowCount, totalInMemoryDataSizeInBytes, totalOnDiskDataSizeInBytes)); } return partitionUpdates.build(); } public enum UpdateMode { NEW, APPEND, OVERWRITE, } public static class FileWriteInfo { private final String writeFileName; private final String targetFileName; private final Optional<Long> fileSize; @JsonCreator public FileWriteInfo( @JsonProperty("writeFileName") String writeFileName, @JsonProperty("targetFileName") String targetFileName, @JsonProperty("fileSize") Optional<Long> fileSize) { this.writeFileName = requireNonNull(writeFileName, "writeFileName is null"); this.targetFileName = requireNonNull(targetFileName, "targetFileName is null"); this.fileSize = requireNonNull(fileSize, "fileSize is null"); } @JsonProperty public String getWriteFileName() { return writeFileName; } @JsonProperty public String getTargetFileName() { return targetFileName; } @JsonProperty public Optional<Long> getFileSize() { return fileSize; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FileWriteInfo)) { return false; } FileWriteInfo that = (FileWriteInfo) o; return Objects.equals(writeFileName, that.writeFileName) && Objects.equals(targetFileName, that.targetFileName) && Objects.equals(fileSize, that.fileSize); } @Override public int hashCode() { return Objects.hash(writeFileName, targetFileName, fileSize); } @Override public String toString() { return toStringHelper(this) .add("writeFileName", writeFileName) .add("targetFileName", targetFileName) .add("fileSize", fileSize) .toString(); } } }
///* Copyright (c) 2009 Barcelona Supercomputing Center - Centro Nacional // de Supercomputacion and Konrad-Zuse-Zentrum fuer Informationstechnik Berlin. // // This file is part of XtreemFS. XtreemFS is part of XtreemOS, a Linux-based // Grid Operating System, see <http://www.xtreemos.eu> for more details. // The XtreemOS project has been developed with the financial support of the // European Commission's IST program under contract #FP6-033576. // // XtreemFS is free software: you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free // Software Foundation, either version 2 of the License, or (at your option) // any later version. // // XtreemFS is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with XtreemFS. If not, see <http://www.gnu.org/licenses/>. // */ ///* // * AUTHORS: Felix Langner (ZIB) // */ //package org.xtreemfs.sandbox; // //import java.net.InetSocketAddress; //import java.util.HashMap; //import java.util.LinkedList; //import java.util.List; //import java.util.Map; //import java.util.Random; //import java.util.UUID; // //import org.xtreemfs.common.clients.Client; //import org.xtreemfs.dir.ErrorCodes; //import org.xtreemfs.foundation.TimeSync; //import org.xtreemfs.foundation.logging.Logging; //import org.xtreemfs.foundation.oncrpc.client.RPCNIOSocketClient; //import org.xtreemfs.foundation.oncrpc.client.RPCResponse; //import org.xtreemfs.interfaces.AddressMapping; //import org.xtreemfs.interfaces.AddressMappingSet; //import org.xtreemfs.interfaces.Service; //import org.xtreemfs.interfaces.ServiceDataMap; //import org.xtreemfs.interfaces.ServiceSet; //import org.xtreemfs.interfaces.ServiceType; //import org.xtreemfs.interfaces.StringSet; //import org.xtreemfs.interfaces.UserCredentials; //import org.xtreemfs.interfaces.DIRInterface.DIRException; //import org.xtreemfs.mrc.client.MRCClient; // ///** // * <p> // * Test of the MRC master-slave replication as an feature of BabuDB, // * without SSL. // * </p> // * // * <p> // * To use this test, setup some MRCs with replication enabled and // * give their addresses to this application. Define which of them should // * be the master. // * </p> // * // * @since 10/14/2009 // * @author flangner // */ //public class mrc_replication_test { // // private final static Random random = new Random(); // private static MRCClient masterClient; // // private final static int LOOKUP_MODE = 1; // private final static int LOOKUP_PERCENTAGE = 50; // private final static int INSERT_MODE = 2; // private final static int INSERT_PERCENTAGE = 40; // private final static int DELETE_MODE = 3; // private final static int DELETE_PERCENTAGE = 10; // // private final static long CHECK_INTERVAL = 15*60*1000; // // private final static int MAX_HISTORY_SIZE = 10000; // // private static int registeredServices = 0; // private static int registeredFiles = 0; // // private static Map<String,Service> availableServices = // new HashMap<String, Service>(); // private static Map<String,AddressMapping> availableAddressMappings = // new HashMap<String,AddressMapping>(); // // private static List<MRCClient> participants = // new LinkedList<MRCClient>(); // // /** // * @param args // * @throws Exception // */ // public static void main(String[] args) throws Exception { // System.out.println("LONGRUNTEST OF THE DIR master-slave replication"); // // Logging.start(Logging.LEVEL_ERROR); // try { // TimeSync.initialize(null, 60000, 50); // } catch (Exception ex) { // ex.printStackTrace(); // System.exit(1); // } // // // administrator details // StringSet gids = new StringSet(); // gids.add(""); // UserCredentials creds = new UserCredentials("", gids, ""); // // // master connection setup // RPCNIOSocketClient rpcClient = // new RPCNIOSocketClient(null, (int) CHECK_INTERVAL, (int) (CHECK_INTERVAL+20000), Client.getExceptionParsers()); // rpcClient.start(); // // // get the parameters // if (args.length!=2) usage(); // masterClient = new MRCClient(rpcClient,parseAddress(args[0])); // // if (args[1].indexOf(",") == -1) { // participants.add(new MRCClient(rpcClient, parseAddress(args[1]))); // } else { // for (String adr : args[1].split(",")) { // participants.add(new MRCClient(rpcClient, parseAddress(adr))); // } // } // // assert(LOOKUP_PERCENTAGE+DELETE_PERCENTAGE+INSERT_PERCENTAGE == 100); // // // run the test // System.out.println("Setting up the configuration ..."); // // RPCResponse<Object> rp = null; // try { // // TODO rebuild test // //rp = masterClient.replication_toMaster(null, creds); // rp.get(); // } catch (DIRException e) { // if (e.getError_code() == ErrorCodes.NOT_ENOUGH_PARTICIPANTS) // error("There where not enough participants available to" + // " perform this operation."); // else if (e.getError_code() == ErrorCodes.AUTH_FAILED) // error("You are not authorized to perform this operation."); // else throw e; // } finally { // if (rp!=null) rp.freeBuffers(); // } // // long start = System.currentTimeMillis(); // long operationCount = 0; // System.out.println("Done! The test begins:"); // // while (true) { // // perform a consistency check // long now = System.currentTimeMillis(); // if ((start+CHECK_INTERVAL) < now) { // System.out.println("Throughput: "+((double) (operationCount/ // (CHECK_INTERVAL/1000)))+" operations/second"); // operationCount = 0; // // performConsistencyCheck(); // start = System.currentTimeMillis(); // } else { // if (random.nextBoolean()) // performFileOperation(); // else // performServiceOperation(); // operationCount++; // } // } // } // // /** // * <p> // * Checks the data on synchronous slave-DIRs. // * </p> // * @throws Exception // */ // private static void performConsistencyCheck() throws Exception { // performConsistencyCheck(masterClient); // for (MRCClient participant : participants) { // performConsistencyCheck(participant); // } // } // // /** // * <p> // * Checks the consistency of the DIR service given by its client. // * </p> // * @param client // */ // private static void performConsistencyCheck(MRCClient client) { // try { // for (String uuid : availableAddressMappings.keySet()) { // performFileLookup(uuid, client); // } // for (String uuid : availableServices.keySet()) { // performServiceLookup(uuid, client); // } // System.out.println("Participant '"+client.getDefaultServerAddress()+ // "' is up-to-date and consistent."); // } catch (Exception e) { // System.out.println("Participant '"+client.getDefaultServerAddress()+ // "' is NOT up-to-date or inconsistent, because: " + // e.getMessage()); // } // } // // /** // * Performs an file operation on the MRC. // * @throws Exception // */ // private static void performFileOperation() throws Exception { // if (registeredFiles != 0) { // switch (mode()) { // case LOOKUP_MODE : // performFileLookup(randomMappingKey(), masterClient); // break; // // case INSERT_MODE : // performFileInsert(); // break; // // case DELETE_MODE : // performFileDelete(); // break; // // default : assert (false); // } // } else { // performFileInsert(); // } // } // // /** // * Performs an Service DIR operation. // * @throws Exception // */ // private static void performServiceOperation() throws Exception { // if (registeredServices != 0) { // switch (mode()) { // case LOOKUP_MODE : // performServiceLookup(randomServiceKey(), masterClient); // break; // // case INSERT_MODE : // performServiceInsert(); // break; // // case DELETE_MODE : // performServiceDelete(); // break; // // default : assert (false); // } // } else { // performServiceInsert(); // } // } // // /** // * Performs an AddressMapping lookup for the given UUID. // * @param uuid // * @param c // * @throws Exception // */ // private static void performFileLookup(String uuid, MRCClient c) // throws Exception{ // // RPCResponse<AddressMappingSet> rp = null; // try { // /* TODO // c.open(null, credentials, path, flags, mode, w32attrs, coordinates); // rp = c.xtreemfs_address_mappings_get(null, uuid); */ // AddressMappingSet result = rp.get(); // // if (result.size() != 1) throw new Exception ((result.size() == 0) ? // "Mapping lost!" : "UUID not unique!"); // // if (!equals(availableAddressMappings.get(uuid), result.get(0))) // throw new Exception("Unequal address mapping detected!"); // } finally { // if (rp!=null) rp.freeBuffers(); // } // } // // /** // * Performs a Service lookup for the given UUID. // * @param uuid // * @param c // * @throws Exception // */ // private static void performServiceLookup(String uuid, MRCClient c) // throws Exception{ // // RPCResponse<ServiceSet> rp = null; // try { // // TODO rp = c.xtreemfs_service_get_by_uuid(null, uuid); // ServiceSet result = rp.get(); // // if (result.size() != 1) throw new Exception ((result.size() == 0) ? // "Service lost!" : "UUID not unique!"); // // if (!equals(availableServices.get(uuid), result.get(0))) // throw new Exception("Unequal service detected!"); // } finally { // if (rp!=null) rp.freeBuffers(); // } // } // // /** // * Performs an AdressMapping insert. // * @throws Exception // */ // private static void performFileInsert() throws Exception{ // // if (availableAddressMappings.size() == MAX_HISTORY_SIZE) // availableAddressMappings.remove(randomMappingKey()); // // AddressMappingSet load = new AddressMappingSet(); // AddressMapping mapping = randomMapping(); // availableAddressMappings.put(mapping.getUuid(), mapping); // load.add(mapping); // RPCResponse<Long> rp = null; // try { // // TODO rp = masterClient.xtreemfs_address_mappings_set(null, load); // long result = rp.get(); // assert(result == 1) : "A previous entry was modified unexpectedly."; // } finally { // if (rp != null) rp.freeBuffers(); // } // registeredFiles++; // } // // /** // * Performs a Service insert. // * @throws Exception // */ // private static void performServiceInsert() throws Exception{ // // if (availableServices.size() == MAX_HISTORY_SIZE) // availableServices.remove(randomServiceKey()); // // Service service = randomService(); // availableServices.put(service.getUuid(), service); // RPCResponse<Long> rp = null; // try { // // TODO rp = masterClient.xtreemfs_service_register(null, service); // long result = rp.get(); // assert(result == 1) : "A previous entry was modified unexpectedly."; // } finally { // if (rp != null) rp.freeBuffers(); // } // registeredServices++; // } // // /** // * Performs an AddressMapping delete. // * @throws Exception // */ // private static void performFileDelete() throws Exception{ // String uuid = new LinkedList<String>(availableAddressMappings.keySet()) // .get(random.nextInt(availableAddressMappings.size())); // RPCResponse<?> rp = null; // try { // //TODO rp = masterClient.xtreemfs_address_mappings_remove(null, uuid); // rp.get(); // } finally { // if (rp != null) rp.freeBuffers(); // } // availableAddressMappings.remove(uuid); // registeredFiles--; // } // // /** // * Performs a Service delete. // * @throws Exception // */ // private static void performServiceDelete() throws Exception{ // String uuid = new LinkedList<String>(availableServices.keySet()) // .get(random.nextInt(availableServices.size())); // RPCResponse<?> rp = null; // try { // // TODO rp = masterClient.xtreemfs_service_deregister(null, uuid); // rp.get(); // } finally { // if (rp != null) rp.freeBuffers(); // } // availableServices.remove(uuid); // registeredServices--; // } // // /** // * @return a random mode for the next step. // */ // private static int mode() { // int per = random.nextInt(100); // if (per<LOOKUP_PERCENTAGE) { // return LOOKUP_MODE; // } else if (per<LOOKUP_PERCENTAGE+INSERT_PERCENTAGE) { // return INSERT_MODE; // } else { // return DELETE_MODE; // } // } // // /** // * @return a random generated addressMapping. // */ // private static AddressMapping randomMapping(){ // UUID uuid = UUID.randomUUID(); // long version = 0; // String protocol = "oncrpc"; // byte[] addr = new byte[4]; // random.nextBytes(addr); // String address = String.valueOf(addr[0])+"."+String.valueOf(addr[1])+ // "."+String.valueOf(addr[2])+"."+String.valueOf(addr[3]); // int port = random.nextInt(65534)+1; // String match_network = "*"; // int ttl_s = 3600; // String uri = protocol+"://"+address+":"+port; // return new AddressMapping(uuid.toString(),version,protocol, // address,port,match_network,ttl_s,uri); // } // // /** // * @return UUID of a random key identifying an address mapping. // */ // private static String randomMappingKey() { // return new LinkedList<String>(availableAddressMappings.keySet()).get( // random.nextInt(availableAddressMappings.size())); // } // // /** // * @return a random generated service. // */ // private static Service randomService() { // ServiceType[] types = ServiceType.values(); // ServiceType type = types[random.nextInt(types.length)]; // UUID uuid = UUID.randomUUID(); // long version = 0; // String name = uuid.toString(); // long time = System.currentTimeMillis(); // ServiceDataMap data = new ServiceDataMap(); // return new Service(type, uuid.toString(), version, name, time, data); // } // // /** // * @return UUID of a random key identifying a service. // */ // private static String randomServiceKey() { // return new LinkedList<String>(availableServices.keySet()).get(random. // nextInt(availableServices.size())); // } // // /** // * // * @param org // * @param onSrv // * @return true, if the original mapping equals the mapping on the DIR for // * the given values. // */ // private static boolean equals(AddressMapping org, AddressMapping onSrv) { // return (org.getAddress().equals(onSrv.getAddress()) && // org.getMatch_network().equals(onSrv.getMatch_network()) && // org.getPort() == onSrv.getPort() && // org.getProtocol().equals(onSrv.getProtocol()) && // org.getTtl_s() == onSrv.getTtl_s() && // org.getUri().equals(onSrv.getUri()) && // org.getVersion()+1 == onSrv.getVersion()); // } // // /** // * // * @param org // * @param onSrv // * @return true, if the original service equals the service on the DIR for // * the given values. // */ // private static boolean equals(Service org, Service onSrv) { // return (org.getName().equals(onSrv.getName()) && // org.getType().equals(onSrv.getType()) && // org.getData().equals(onSrv.getData()) && // org.getVersion()+1 == onSrv.getVersion()); // } // // /** // * Can exit with an error, if the given string was illegal. // * // * @param adr // * @return the parsed {@link InetSocketAddress}. // */ // private static InetSocketAddress parseAddress (String adr){ // String[] comp = adr.split(":"); // if (comp.length!=2){ // error("Address '"+adr+"' is illegal!"); // return null; // } // // try { // int port = Integer.parseInt(comp[1]); // return new InetSocketAddress(comp[0],port); // } catch (NumberFormatException e) { // error("Address '"+adr+"' is illegal! Because: "+comp[1]+" is not a number."); // return null; // } // } // // /** // * Prints the error <code>message</code> and delegates to usage(). // * @param message // */ // private static void error(String message) { // System.err.println(message); // usage(); // } // // /** // * Prints out usage information and terminates the application. // */ // public static void usage(){ // System.out.println("dir_replication_test <master_address:port> <slave_address:port>[,<slave_address:port>]"); // System.out.println(" "+"<master_address:port> address of the DIR that has to be declared to master"); // System.out.println(" "+"<slave_address:port> participants of the replication separated by ','"); // System.exit(1); // } //}
// Template Source: BaseMethodParameterSet.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models; import com.microsoft.graph.models.Prompt; import com.microsoft.graph.models.RecordOperation; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.gson.JsonObject; import java.util.EnumSet; import java.util.ArrayList; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Call Record Response Parameter Set. */ public class CallRecordResponseParameterSet { /** * The prompts. * */ @SerializedName(value = "prompts", alternate = {"Prompts"}) @Expose @Nullable public java.util.List<Prompt> prompts; /** * The barge In Allowed. * */ @SerializedName(value = "bargeInAllowed", alternate = {"BargeInAllowed"}) @Expose @Nullable public Boolean bargeInAllowed; /** * The initial Silence Timeout In Seconds. * */ @SerializedName(value = "initialSilenceTimeoutInSeconds", alternate = {"InitialSilenceTimeoutInSeconds"}) @Expose @Nullable public Integer initialSilenceTimeoutInSeconds; /** * The max Silence Timeout In Seconds. * */ @SerializedName(value = "maxSilenceTimeoutInSeconds", alternate = {"MaxSilenceTimeoutInSeconds"}) @Expose @Nullable public Integer maxSilenceTimeoutInSeconds; /** * The max Record Duration In Seconds. * */ @SerializedName(value = "maxRecordDurationInSeconds", alternate = {"MaxRecordDurationInSeconds"}) @Expose @Nullable public Integer maxRecordDurationInSeconds; /** * The play Beep. * */ @SerializedName(value = "playBeep", alternate = {"PlayBeep"}) @Expose @Nullable public Boolean playBeep; /** * The stop Tones. * */ @SerializedName(value = "stopTones", alternate = {"StopTones"}) @Expose @Nullable public java.util.List<String> stopTones; /** * The client Context. * */ @SerializedName(value = "clientContext", alternate = {"ClientContext"}) @Expose @Nullable public String clientContext; /** * Instiaciates a new CallRecordResponseParameterSet */ public CallRecordResponseParameterSet() {} /** * Instiaciates a new CallRecordResponseParameterSet * @param builder builder bearing the parameters to initialize from */ protected CallRecordResponseParameterSet(@Nonnull final CallRecordResponseParameterSetBuilder builder) { this.prompts = builder.prompts; this.bargeInAllowed = builder.bargeInAllowed; this.initialSilenceTimeoutInSeconds = builder.initialSilenceTimeoutInSeconds; this.maxSilenceTimeoutInSeconds = builder.maxSilenceTimeoutInSeconds; this.maxRecordDurationInSeconds = builder.maxRecordDurationInSeconds; this.playBeep = builder.playBeep; this.stopTones = builder.stopTones; this.clientContext = builder.clientContext; } /** * Gets a new builder for the body * @return a new builder */ @Nonnull public static CallRecordResponseParameterSetBuilder newBuilder() { return new CallRecordResponseParameterSetBuilder(); } /** * Fluent builder for the CallRecordResponseParameterSet */ public static final class CallRecordResponseParameterSetBuilder { /** * The prompts parameter value */ @Nullable protected java.util.List<Prompt> prompts; /** * Sets the Prompts * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withPrompts(@Nullable final java.util.List<Prompt> val) { this.prompts = val; return this; } /** * The bargeInAllowed parameter value */ @Nullable protected Boolean bargeInAllowed; /** * Sets the BargeInAllowed * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withBargeInAllowed(@Nullable final Boolean val) { this.bargeInAllowed = val; return this; } /** * The initialSilenceTimeoutInSeconds parameter value */ @Nullable protected Integer initialSilenceTimeoutInSeconds; /** * Sets the InitialSilenceTimeoutInSeconds * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withInitialSilenceTimeoutInSeconds(@Nullable final Integer val) { this.initialSilenceTimeoutInSeconds = val; return this; } /** * The maxSilenceTimeoutInSeconds parameter value */ @Nullable protected Integer maxSilenceTimeoutInSeconds; /** * Sets the MaxSilenceTimeoutInSeconds * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withMaxSilenceTimeoutInSeconds(@Nullable final Integer val) { this.maxSilenceTimeoutInSeconds = val; return this; } /** * The maxRecordDurationInSeconds parameter value */ @Nullable protected Integer maxRecordDurationInSeconds; /** * Sets the MaxRecordDurationInSeconds * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withMaxRecordDurationInSeconds(@Nullable final Integer val) { this.maxRecordDurationInSeconds = val; return this; } /** * The playBeep parameter value */ @Nullable protected Boolean playBeep; /** * Sets the PlayBeep * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withPlayBeep(@Nullable final Boolean val) { this.playBeep = val; return this; } /** * The stopTones parameter value */ @Nullable protected java.util.List<String> stopTones; /** * Sets the StopTones * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withStopTones(@Nullable final java.util.List<String> val) { this.stopTones = val; return this; } /** * The clientContext parameter value */ @Nullable protected String clientContext; /** * Sets the ClientContext * @param val the value to set it to * @return the current builder object */ @Nonnull public CallRecordResponseParameterSetBuilder withClientContext(@Nullable final String val) { this.clientContext = val; return this; } /** * Instanciates a new CallRecordResponseParameterSetBuilder */ @Nullable protected CallRecordResponseParameterSetBuilder(){} /** * Buils the resulting body object to be passed to the request * @return the body object to pass to the request */ @Nonnull public CallRecordResponseParameterSet build() { return new CallRecordResponseParameterSet(this); } } /** * Gets the functions options from the properties that have been set * @return a list of function options for the request */ @Nonnull public java.util.List<com.microsoft.graph.options.FunctionOption> getFunctionOptions() { final ArrayList<com.microsoft.graph.options.FunctionOption> result = new ArrayList<>(); if(this.prompts != null) { result.add(new com.microsoft.graph.options.FunctionOption("prompts", prompts)); } if(this.bargeInAllowed != null) { result.add(new com.microsoft.graph.options.FunctionOption("bargeInAllowed", bargeInAllowed)); } if(this.initialSilenceTimeoutInSeconds != null) { result.add(new com.microsoft.graph.options.FunctionOption("initialSilenceTimeoutInSeconds", initialSilenceTimeoutInSeconds)); } if(this.maxSilenceTimeoutInSeconds != null) { result.add(new com.microsoft.graph.options.FunctionOption("maxSilenceTimeoutInSeconds", maxSilenceTimeoutInSeconds)); } if(this.maxRecordDurationInSeconds != null) { result.add(new com.microsoft.graph.options.FunctionOption("maxRecordDurationInSeconds", maxRecordDurationInSeconds)); } if(this.playBeep != null) { result.add(new com.microsoft.graph.options.FunctionOption("playBeep", playBeep)); } if(this.stopTones != null) { result.add(new com.microsoft.graph.options.FunctionOption("stopTones", stopTones)); } if(this.clientContext != null) { result.add(new com.microsoft.graph.options.FunctionOption("clientContext", clientContext)); } return result; } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.abelana; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.google.identitytoolkit.GitkitUser; import com.squareup.picasso.Picasso; /** * The BaseActivity is primarily responsible for implementing the Android navigation drawer. * It is the BaseActivity that other activities can extend. In this case, FeedActivity serves * as an extension. * Code for the navigation drawer adapted from the sample at * http://developer.android.com/training/implementing-navigation/nav-drawer.html */ public class BaseActivity extends Activity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private String[] mNavItems; /* Navigation Drawer menu items start indexing at 1, because the header view is interpreted * as the 0th element, though it is not tappable. */ protected static final int NAVDRAWER_ITEM_HOME = 1; protected static final int NAVDRAWER_ITEM_PROFILE = 2; protected static final int NAVDRAWER_ITEM_FOLLOWING = 3; protected static final int NAVDRAWER_ITEM_SETTINGS = 4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTitle = mDrawerTitle = getTitle(); mNavItems = getResources().getStringArray(R.array.nav_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); //initialize Data class to retrieve navigation drawer icons and text Data data = new Data(); /* Add the header to the navigation drawer. Pulls the user's name, email address * and photo from the Google Identity Toolkit. The photo is placed into a custom * ImageView which gives the circle effect. Image loading over the network is done * with Picasso, a library from Square. */ View header = View.inflate(this, R.layout.navdrawer_header, null); BezelImageView imageView = (BezelImageView) header.findViewById(R.id.profile_image); UserInfoStore client = new UserInfoStore(getApplicationContext()); GitkitUser user = client.getSavedGitkitUser(); Log.v("foo", "user is " + user); Picasso.with(getApplicationContext()).load(client.getSavedGitkitUser().getPhotoUrl()) .into(imageView); TextView email = (TextView) header.findViewById(R.id.profile_email_text); email.setText(Data.mEmail); TextView name = (TextView) header.findViewById(R.id.profile_name_text); name.setText(Data.mDisplayName); // set up the drawer's list view with mNavItems and click listener mDrawerList.addHeaderView(header, null, false); mDrawerList.setAdapter(new NavDrawerAdapter(getApplicationContext(), R.layout.list_item_navdrawer, data.mNavItems)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.app_name, /* "open drawer" description for accessibility */ R.string.app_name /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { selectItem(NAVDRAWER_ITEM_HOME); } } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action mNavItems related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); //menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } /* The click listener for ListView in the navigation drawer */ private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } /* Handles the flow from tapping items in the navigation drawer. * All new screens come from fragment transactions. Settings is an exception * because of the way Settings are implemented in Android. */ private void selectItem(int position) { FragmentManager fragmentManager = getFragmentManager(); if (position == NAVDRAWER_ITEM_SETTINGS) { Intent intent = new Intent(getApplicationContext(), SettingsActivity.class); startActivity(intent); } if (position == NAVDRAWER_ITEM_FOLLOWING) { FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.content_frame, new FriendsFragment()) .commit(); } if (position == NAVDRAWER_ITEM_HOME) { FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.content_frame, new FeedFragment()) .commit(); } if (position == NAVDRAWER_ITEM_PROFILE) { FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.content_frame, new ProfileFragment()) .commit(); } //update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); setTitle(mNavItems[position]); mDrawerLayout.closeDrawer(mDrawerList); } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simpleworkflow.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/swf-2012-01-25/SignalWorkflowExecution" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SignalWorkflowExecutionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the domain containing the workflow execution to signal. * </p> */ private String domain; /** * <p> * The workflowId of the workflow execution to signal. * </p> */ private String workflowId; /** * <p> * The runId of the workflow execution to signal. * </p> */ private String runId; /** * <p> * The name of the signal. This name must be meaningful to the target workflow. * </p> */ private String signalName; /** * <p> * Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's history. * </p> */ private String input; /** * <p> * The name of the domain containing the workflow execution to signal. * </p> * * @param domain * The name of the domain containing the workflow execution to signal. */ public void setDomain(String domain) { this.domain = domain; } /** * <p> * The name of the domain containing the workflow execution to signal. * </p> * * @return The name of the domain containing the workflow execution to signal. */ public String getDomain() { return this.domain; } /** * <p> * The name of the domain containing the workflow execution to signal. * </p> * * @param domain * The name of the domain containing the workflow execution to signal. * @return Returns a reference to this object so that method calls can be chained together. */ public SignalWorkflowExecutionRequest withDomain(String domain) { setDomain(domain); return this; } /** * <p> * The workflowId of the workflow execution to signal. * </p> * * @param workflowId * The workflowId of the workflow execution to signal. */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * <p> * The workflowId of the workflow execution to signal. * </p> * * @return The workflowId of the workflow execution to signal. */ public String getWorkflowId() { return this.workflowId; } /** * <p> * The workflowId of the workflow execution to signal. * </p> * * @param workflowId * The workflowId of the workflow execution to signal. * @return Returns a reference to this object so that method calls can be chained together. */ public SignalWorkflowExecutionRequest withWorkflowId(String workflowId) { setWorkflowId(workflowId); return this; } /** * <p> * The runId of the workflow execution to signal. * </p> * * @param runId * The runId of the workflow execution to signal. */ public void setRunId(String runId) { this.runId = runId; } /** * <p> * The runId of the workflow execution to signal. * </p> * * @return The runId of the workflow execution to signal. */ public String getRunId() { return this.runId; } /** * <p> * The runId of the workflow execution to signal. * </p> * * @param runId * The runId of the workflow execution to signal. * @return Returns a reference to this object so that method calls can be chained together. */ public SignalWorkflowExecutionRequest withRunId(String runId) { setRunId(runId); return this; } /** * <p> * The name of the signal. This name must be meaningful to the target workflow. * </p> * * @param signalName * The name of the signal. This name must be meaningful to the target workflow. */ public void setSignalName(String signalName) { this.signalName = signalName; } /** * <p> * The name of the signal. This name must be meaningful to the target workflow. * </p> * * @return The name of the signal. This name must be meaningful to the target workflow. */ public String getSignalName() { return this.signalName; } /** * <p> * The name of the signal. This name must be meaningful to the target workflow. * </p> * * @param signalName * The name of the signal. This name must be meaningful to the target workflow. * @return Returns a reference to this object so that method calls can be chained together. */ public SignalWorkflowExecutionRequest withSignalName(String signalName) { setSignalName(signalName); return this; } /** * <p> * Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's history. * </p> * * @param input * Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's * history. */ public void setInput(String input) { this.input = input; } /** * <p> * Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's history. * </p> * * @return Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's * history. */ public String getInput() { return this.input; } /** * <p> * Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's history. * </p> * * @param input * Data to attach to the <code>WorkflowExecutionSignaled</code> event in the target workflow execution's * history. * @return Returns a reference to this object so that method calls can be chained together. */ public SignalWorkflowExecutionRequest withInput(String input) { setInput(input); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDomain() != null) sb.append("Domain: ").append(getDomain()).append(","); if (getWorkflowId() != null) sb.append("WorkflowId: ").append(getWorkflowId()).append(","); if (getRunId() != null) sb.append("RunId: ").append(getRunId()).append(","); if (getSignalName() != null) sb.append("SignalName: ").append(getSignalName()).append(","); if (getInput() != null) sb.append("Input: ").append(getInput()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SignalWorkflowExecutionRequest == false) return false; SignalWorkflowExecutionRequest other = (SignalWorkflowExecutionRequest) obj; if (other.getDomain() == null ^ this.getDomain() == null) return false; if (other.getDomain() != null && other.getDomain().equals(this.getDomain()) == false) return false; if (other.getWorkflowId() == null ^ this.getWorkflowId() == null) return false; if (other.getWorkflowId() != null && other.getWorkflowId().equals(this.getWorkflowId()) == false) return false; if (other.getRunId() == null ^ this.getRunId() == null) return false; if (other.getRunId() != null && other.getRunId().equals(this.getRunId()) == false) return false; if (other.getSignalName() == null ^ this.getSignalName() == null) return false; if (other.getSignalName() != null && other.getSignalName().equals(this.getSignalName()) == false) return false; if (other.getInput() == null ^ this.getInput() == null) return false; if (other.getInput() != null && other.getInput().equals(this.getInput()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDomain() == null) ? 0 : getDomain().hashCode()); hashCode = prime * hashCode + ((getWorkflowId() == null) ? 0 : getWorkflowId().hashCode()); hashCode = prime * hashCode + ((getRunId() == null) ? 0 : getRunId().hashCode()); hashCode = prime * hashCode + ((getSignalName() == null) ? 0 : getSignalName().hashCode()); hashCode = prime * hashCode + ((getInput() == null) ? 0 : getInput().hashCode()); return hashCode; } @Override public SignalWorkflowExecutionRequest clone() { return (SignalWorkflowExecutionRequest) super.clone(); } }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/automl/v1beta1/service.proto package com.google.cloud.automl.v1beta1; /** * * * <pre> * Request message for [AutoMl.DeleteModel][google.cloud.automl.v1beta1.AutoMl.DeleteModel]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.DeleteModelRequest} */ public final class DeleteModelRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.DeleteModelRequest) DeleteModelRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteModelRequest.newBuilder() to construct. private DeleteModelRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteModelRequest() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteModelRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private DeleteModelRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.DeleteModelRequest.class, com.google.cloud.automl.v1beta1.DeleteModelRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.automl.v1beta1.DeleteModelRequest)) { return super.equals(obj); } com.google.cloud.automl.v1beta1.DeleteModelRequest other = (com.google.cloud.automl.v1beta1.DeleteModelRequest) obj; if (!getName().equals(other.getName())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.automl.v1beta1.DeleteModelRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for [AutoMl.DeleteModel][google.cloud.automl.v1beta1.AutoMl.DeleteModel]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.DeleteModelRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.automl.v1beta1.DeleteModelRequest) com.google.cloud.automl.v1beta1.DeleteModelRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.DeleteModelRequest.class, com.google.cloud.automl.v1beta1.DeleteModelRequest.Builder.class); } // Construct using com.google.cloud.automl.v1beta1.DeleteModelRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_descriptor; } @java.lang.Override public com.google.cloud.automl.v1beta1.DeleteModelRequest getDefaultInstanceForType() { return com.google.cloud.automl.v1beta1.DeleteModelRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.automl.v1beta1.DeleteModelRequest build() { com.google.cloud.automl.v1beta1.DeleteModelRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.automl.v1beta1.DeleteModelRequest buildPartial() { com.google.cloud.automl.v1beta1.DeleteModelRequest result = new com.google.cloud.automl.v1beta1.DeleteModelRequest(this); result.name_ = name_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.automl.v1beta1.DeleteModelRequest) { return mergeFrom((com.google.cloud.automl.v1beta1.DeleteModelRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.automl.v1beta1.DeleteModelRequest other) { if (other == com.google.cloud.automl.v1beta1.DeleteModelRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.automl.v1beta1.DeleteModelRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.automl.v1beta1.DeleteModelRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * * * <pre> * Required. Resource name of the model being deleted. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.automl.v1beta1.DeleteModelRequest) } // @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.DeleteModelRequest) private static final com.google.cloud.automl.v1beta1.DeleteModelRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.automl.v1beta1.DeleteModelRequest(); } public static com.google.cloud.automl.v1beta1.DeleteModelRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteModelRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteModelRequest>() { @java.lang.Override public DeleteModelRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DeleteModelRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DeleteModelRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteModelRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.automl.v1beta1.DeleteModelRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver12; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import com.google.common.collect.ImmutableSet; import java.util.List; import com.google.common.collect.ImmutableList; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFFeaturesReplyVer12 implements OFFeaturesReply { private static final Logger logger = LoggerFactory.getLogger(OFFeaturesReplyVer12.class); // version: 1.2 final static byte WIRE_VERSION = 3; final static int MINIMUM_LENGTH = 32; // maximum OF message length: 16 bit, unsigned final static int MAXIMUM_LENGTH = 0xFFFF; private final static long DEFAULT_XID = 0x0L; private final static DatapathId DEFAULT_DATAPATH_ID = DatapathId.NONE; private final static long DEFAULT_N_BUFFERS = 0x0L; private final static short DEFAULT_N_TABLES = (short) 0x0; private final static Set<OFCapabilities> DEFAULT_CAPABILITIES = ImmutableSet.<OFCapabilities>of(); private final static long DEFAULT_RESERVED = 0x0L; private final static List<OFPortDesc> DEFAULT_PORTS = ImmutableList.<OFPortDesc>of(); // OF message fields private final long xid; private final DatapathId datapathId; private final long nBuffers; private final short nTables; private final Set<OFCapabilities> capabilities; private final long reserved; private final List<OFPortDesc> ports; // // Immutable default instance final static OFFeaturesReplyVer12 DEFAULT = new OFFeaturesReplyVer12( DEFAULT_XID, DEFAULT_DATAPATH_ID, DEFAULT_N_BUFFERS, DEFAULT_N_TABLES, DEFAULT_CAPABILITIES, DEFAULT_RESERVED, DEFAULT_PORTS ); // package private constructor - used by readers, builders, and factory OFFeaturesReplyVer12(long xid, DatapathId datapathId, long nBuffers, short nTables, Set<OFCapabilities> capabilities, long reserved, List<OFPortDesc> ports) { if(datapathId == null) { throw new NullPointerException("OFFeaturesReplyVer12: property datapathId cannot be null"); } if(capabilities == null) { throw new NullPointerException("OFFeaturesReplyVer12: property capabilities cannot be null"); } if(ports == null) { throw new NullPointerException("OFFeaturesReplyVer12: property ports cannot be null"); } this.xid = U32.normalize(xid); this.datapathId = datapathId; this.nBuffers = U32.normalize(nBuffers); this.nTables = U8.normalize(nTables); this.capabilities = capabilities; this.reserved = U32.normalize(reserved); this.ports = ports; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.FEATURES_REPLY; } @Override public long getXid() { return xid; } @Override public DatapathId getDatapathId() { return datapathId; } @Override public long getNBuffers() { return nBuffers; } @Override public short getNTables() { return nTables; } @Override public Set<OFCapabilities> getCapabilities() { return capabilities; } @Override public Set<OFActionType> getActions()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property actions not supported in version 1.2"); } @Override public List<OFPortDesc> getPorts() { return ports; } @Override public long getReserved() { return reserved; } @Override public OFAuxId getAuxiliaryId()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property auxiliaryId not supported in version 1.2"); } public OFFeaturesReply.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFFeaturesReply.Builder { final OFFeaturesReplyVer12 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean datapathIdSet; private DatapathId datapathId; private boolean nBuffersSet; private long nBuffers; private boolean nTablesSet; private short nTables; private boolean capabilitiesSet; private Set<OFCapabilities> capabilities; private boolean reservedSet; private long reserved; private boolean portsSet; private List<OFPortDesc> ports; BuilderWithParent(OFFeaturesReplyVer12 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.FEATURES_REPLY; } @Override public long getXid() { return xid; } @Override public OFFeaturesReply.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public DatapathId getDatapathId() { return datapathId; } @Override public OFFeaturesReply.Builder setDatapathId(DatapathId datapathId) { this.datapathId = datapathId; this.datapathIdSet = true; return this; } @Override public long getNBuffers() { return nBuffers; } @Override public OFFeaturesReply.Builder setNBuffers(long nBuffers) { this.nBuffers = nBuffers; this.nBuffersSet = true; return this; } @Override public short getNTables() { return nTables; } @Override public OFFeaturesReply.Builder setNTables(short nTables) { this.nTables = nTables; this.nTablesSet = true; return this; } @Override public Set<OFCapabilities> getCapabilities() { return capabilities; } @Override public OFFeaturesReply.Builder setCapabilities(Set<OFCapabilities> capabilities) { this.capabilities = capabilities; this.capabilitiesSet = true; return this; } @Override public Set<OFActionType> getActions()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property actions not supported in version 1.2"); } @Override public OFFeaturesReply.Builder setActions(Set<OFActionType> actions) throws UnsupportedOperationException { throw new UnsupportedOperationException("Property actions not supported in version 1.2"); } @Override public List<OFPortDesc> getPorts() { return ports; } @Override public OFFeaturesReply.Builder setPorts(List<OFPortDesc> ports) { this.ports = ports; this.portsSet = true; return this; } @Override public long getReserved() { return reserved; } @Override public OFFeaturesReply.Builder setReserved(long reserved) { this.reserved = reserved; this.reservedSet = true; return this; } @Override public OFAuxId getAuxiliaryId()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property auxiliaryId not supported in version 1.2"); } @Override public OFFeaturesReply.Builder setAuxiliaryId(OFAuxId auxiliaryId) throws UnsupportedOperationException { throw new UnsupportedOperationException("Property auxiliaryId not supported in version 1.2"); } @Override public OFFeaturesReply build() { long xid = this.xidSet ? this.xid : parentMessage.xid; DatapathId datapathId = this.datapathIdSet ? this.datapathId : parentMessage.datapathId; if(datapathId == null) throw new NullPointerException("Property datapathId must not be null"); long nBuffers = this.nBuffersSet ? this.nBuffers : parentMessage.nBuffers; short nTables = this.nTablesSet ? this.nTables : parentMessage.nTables; Set<OFCapabilities> capabilities = this.capabilitiesSet ? this.capabilities : parentMessage.capabilities; if(capabilities == null) throw new NullPointerException("Property capabilities must not be null"); long reserved = this.reservedSet ? this.reserved : parentMessage.reserved; List<OFPortDesc> ports = this.portsSet ? this.ports : parentMessage.ports; if(ports == null) throw new NullPointerException("Property ports must not be null"); // return new OFFeaturesReplyVer12( xid, datapathId, nBuffers, nTables, capabilities, reserved, ports ); } } static class Builder implements OFFeaturesReply.Builder { // OF message fields private boolean xidSet; private long xid; private boolean datapathIdSet; private DatapathId datapathId; private boolean nBuffersSet; private long nBuffers; private boolean nTablesSet; private short nTables; private boolean capabilitiesSet; private Set<OFCapabilities> capabilities; private boolean reservedSet; private long reserved; private boolean portsSet; private List<OFPortDesc> ports; @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.FEATURES_REPLY; } @Override public long getXid() { return xid; } @Override public OFFeaturesReply.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public DatapathId getDatapathId() { return datapathId; } @Override public OFFeaturesReply.Builder setDatapathId(DatapathId datapathId) { this.datapathId = datapathId; this.datapathIdSet = true; return this; } @Override public long getNBuffers() { return nBuffers; } @Override public OFFeaturesReply.Builder setNBuffers(long nBuffers) { this.nBuffers = nBuffers; this.nBuffersSet = true; return this; } @Override public short getNTables() { return nTables; } @Override public OFFeaturesReply.Builder setNTables(short nTables) { this.nTables = nTables; this.nTablesSet = true; return this; } @Override public Set<OFCapabilities> getCapabilities() { return capabilities; } @Override public OFFeaturesReply.Builder setCapabilities(Set<OFCapabilities> capabilities) { this.capabilities = capabilities; this.capabilitiesSet = true; return this; } @Override public Set<OFActionType> getActions()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property actions not supported in version 1.2"); } @Override public OFFeaturesReply.Builder setActions(Set<OFActionType> actions) throws UnsupportedOperationException { throw new UnsupportedOperationException("Property actions not supported in version 1.2"); } @Override public List<OFPortDesc> getPorts() { return ports; } @Override public OFFeaturesReply.Builder setPorts(List<OFPortDesc> ports) { this.ports = ports; this.portsSet = true; return this; } @Override public long getReserved() { return reserved; } @Override public OFFeaturesReply.Builder setReserved(long reserved) { this.reserved = reserved; this.reservedSet = true; return this; } @Override public OFAuxId getAuxiliaryId()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property auxiliaryId not supported in version 1.2"); } @Override public OFFeaturesReply.Builder setAuxiliaryId(OFAuxId auxiliaryId) throws UnsupportedOperationException { throw new UnsupportedOperationException("Property auxiliaryId not supported in version 1.2"); } // @Override public OFFeaturesReply build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; DatapathId datapathId = this.datapathIdSet ? this.datapathId : DEFAULT_DATAPATH_ID; if(datapathId == null) throw new NullPointerException("Property datapathId must not be null"); long nBuffers = this.nBuffersSet ? this.nBuffers : DEFAULT_N_BUFFERS; short nTables = this.nTablesSet ? this.nTables : DEFAULT_N_TABLES; Set<OFCapabilities> capabilities = this.capabilitiesSet ? this.capabilities : DEFAULT_CAPABILITIES; if(capabilities == null) throw new NullPointerException("Property capabilities must not be null"); long reserved = this.reservedSet ? this.reserved : DEFAULT_RESERVED; List<OFPortDesc> ports = this.portsSet ? this.ports : DEFAULT_PORTS; if(ports == null) throw new NullPointerException("Property ports must not be null"); return new OFFeaturesReplyVer12( xid, datapathId, nBuffers, nTables, capabilities, reserved, ports ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFFeaturesReply> { @Override public OFFeaturesReply readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 3 byte version = bb.readByte(); if(version != (byte) 0x3) throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got="+version); // fixed value property type == 6 byte type = bb.readByte(); if(type != (byte) 0x6) throw new OFParseError("Wrong type: Expected=OFType.FEATURES_REPLY(6), got="+type); int length = U16.f(bb.readShort()); if(length < MINIMUM_LENGTH) throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); DatapathId datapathId = DatapathId.of(bb.readLong()); long nBuffers = U32.f(bb.readInt()); short nTables = U8.f(bb.readByte()); // pad: 3 bytes bb.skipBytes(3); Set<OFCapabilities> capabilities = OFCapabilitiesSerializerVer12.readFrom(bb); long reserved = U32.f(bb.readInt()); List<OFPortDesc> ports = ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFPortDescVer12.READER); OFFeaturesReplyVer12 featuresReplyVer12 = new OFFeaturesReplyVer12( xid, datapathId, nBuffers, nTables, capabilities, reserved, ports ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", featuresReplyVer12); return featuresReplyVer12; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFFeaturesReplyVer12Funnel FUNNEL = new OFFeaturesReplyVer12Funnel(); static class OFFeaturesReplyVer12Funnel implements Funnel<OFFeaturesReplyVer12> { private static final long serialVersionUID = 1L; @Override public void funnel(OFFeaturesReplyVer12 message, PrimitiveSink sink) { // fixed value property version = 3 sink.putByte((byte) 0x3); // fixed value property type = 6 sink.putByte((byte) 0x6); // FIXME: skip funnel of length sink.putLong(message.xid); message.datapathId.putTo(sink); sink.putLong(message.nBuffers); sink.putShort(message.nTables); // skip pad (3 bytes) OFCapabilitiesSerializerVer12.putTo(message.capabilities, sink); sink.putLong(message.reserved); FunnelUtils.putList(message.ports, sink); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFFeaturesReplyVer12> { @Override public void write(ByteBuf bb, OFFeaturesReplyVer12 message) { int startIndex = bb.writerIndex(); // fixed value property version = 3 bb.writeByte((byte) 0x3); // fixed value property type = 6 bb.writeByte((byte) 0x6); // length is length of variable message, will be updated at the end int lengthIndex = bb.writerIndex(); bb.writeShort(U16.t(0)); bb.writeInt(U32.t(message.xid)); bb.writeLong(message.datapathId.getLong()); bb.writeInt(U32.t(message.nBuffers)); bb.writeByte(U8.t(message.nTables)); // pad: 3 bytes bb.writeZero(3); OFCapabilitiesSerializerVer12.writeTo(bb, message.capabilities); bb.writeInt(U32.t(message.reserved)); ChannelUtils.writeList(bb, message.ports); // update length field int length = bb.writerIndex() - startIndex; if (length > MAXIMUM_LENGTH) { throw new IllegalArgumentException("OFFeaturesReplyVer12: message length (" + length + ") exceeds maximum (0xFFFF)"); } bb.setShort(lengthIndex, length); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFFeaturesReplyVer12("); b.append("xid=").append(xid); b.append(", "); b.append("datapathId=").append(datapathId); b.append(", "); b.append("nBuffers=").append(nBuffers); b.append(", "); b.append("nTables=").append(nTables); b.append(", "); b.append("capabilities=").append(capabilities); b.append(", "); b.append("reserved=").append(reserved); b.append(", "); b.append("ports=").append(ports); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFFeaturesReplyVer12 other = (OFFeaturesReplyVer12) obj; if( xid != other.xid) return false; if (datapathId == null) { if (other.datapathId != null) return false; } else if (!datapathId.equals(other.datapathId)) return false; if( nBuffers != other.nBuffers) return false; if( nTables != other.nTables) return false; if (capabilities == null) { if (other.capabilities != null) return false; } else if (!capabilities.equals(other.capabilities)) return false; if( reserved != other.reserved) return false; if (ports == null) { if (other.ports != null) return false; } else if (!ports.equals(other.ports)) return false; return true; } @Override public boolean equalsIgnoreXid(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFFeaturesReplyVer12 other = (OFFeaturesReplyVer12) obj; // ignore XID if (datapathId == null) { if (other.datapathId != null) return false; } else if (!datapathId.equals(other.datapathId)) return false; if( nBuffers != other.nBuffers) return false; if( nTables != other.nTables) return false; if (capabilities == null) { if (other.capabilities != null) return false; } else if (!capabilities.equals(other.capabilities)) return false; if( reserved != other.reserved) return false; if (ports == null) { if (other.ports != null) return false; } else if (!ports.equals(other.ports)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((datapathId == null) ? 0 : datapathId.hashCode()); result = prime * (int) (nBuffers ^ (nBuffers >>> 32)); result = prime * result + nTables; result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode()); result = prime * (int) (reserved ^ (reserved >>> 32)); result = prime * result + ((ports == null) ? 0 : ports.hashCode()); return result; } @Override public int hashCodeIgnoreXid() { final int prime = 31; int result = 1; // ignore XID result = prime * result + ((datapathId == null) ? 0 : datapathId.hashCode()); result = prime * (int) (nBuffers ^ (nBuffers >>> 32)); result = prime * result + nTables; result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode()); result = prime * (int) (reserved ^ (reserved >>> 32)); result = prime * result + ((ports == null) ? 0 : ports.hashCode()); return result; } }
package org.jgroups.tests; import org.jgroups.Address; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.blocks.MethodCall; import org.jgroups.blocks.RequestOptions; import org.jgroups.blocks.RpcDispatcher; import org.jgroups.protocols.*; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.protocols.pbcast.NAKACK2; import org.jgroups.protocols.pbcast.STABLE; import org.jgroups.stack.Protocol; import org.jgroups.stack.ProtocolStack; import org.jgroups.util.Util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Tests https://issues.jboss.org/browse/JGRP-1675 * @author Bela Ban * @since 3.5 */ public class RemoteGetStressTest { protected JChannel[] channels; protected List<Address> target_members; // B, C, D protected RpcDispatcher[] dispatchers; protected Random random = new Random(); protected static final int NUM_THREADS=40; protected static final int SIZE=100 * 1000; // size of a GET response protected static final byte[] BUF=new byte[SIZE]; protected static final MethodCall GET_METHOD; protected static final long TIMEOUT=3 * 60 * 1000; // ms protected static final AtomicInteger count=new AtomicInteger(1); protected static final RequestOptions OPTIONS=RequestOptions.SYNC().timeout(TIMEOUT) .flags(Message.Flag.OOB).anycasting(true); protected static boolean USE_SLEEPS=true; static { try { Method get_method=RemoteGetStressTest.class.getMethod("get"); GET_METHOD=new MethodCall(get_method); } catch(NoSuchMethodException e) { throw new RuntimeException(e); } } protected void start() throws Exception { String[] names={"A", "B", "C", "D"}; channels=new JChannel[4]; dispatchers=new RpcDispatcher[channels.length]; for(int i=0; i < channels.length; i++) { channels[i]=createChannel(names[i]); dispatchers[i]=new RpcDispatcher(channels[i], this); channels[i].connect("cluster"); } Util.waitUntilAllChannelsHaveSameView(10000, 500, channels); System.out.println("view A: " + channels[0].getView()); target_members=Arrays.asList(channels[1].getAddress(), channels[2].getAddress(), channels[3].getAddress()); final AtomicInteger success=new AtomicInteger(0), failure=new AtomicInteger(0); if(USE_SLEEPS) insertDISCARD(channels[0], 0.2); long start=System.currentTimeMillis(); Invoker[] invokers=new Invoker[NUM_THREADS]; for(int i=0; i < invokers.length; i++) { invokers[i]=new Invoker(dispatchers[0], success, failure); invokers[i].start(); } for(Invoker invoker: invokers) invoker.join(); long time=System.currentTimeMillis() - start; System.out.println("\n\n**** success: " + success + ", failure=" + failure + ", time=" + time + " ms"); Util.keyPress("enter to terminate"); stop(); } protected void stop() { for(RpcDispatcher disp: dispatchers) disp.stop(); Util.close(channels); } protected static JChannel createChannel(String name) throws Exception { Protocol[] protocols={ new SHARED_LOOPBACK().setValue("thread_pool_min_threads", 1) .setValue("thread_pool_max_threads", 5), new SHARED_LOOPBACK_PING(), new NAKACK2(), new UNICAST3(), new STABLE(), new GMS(), new UFC(), new MFC().setValue("max_credits", 2000000).setValue("min_threshold", 0.4), new FRAG2().fragSize(8000), }; return new JChannel(protocols).name(name); } public static BigObject get() { return new BigObject(count.getAndIncrement()); } public static void main(String[] args) throws Exception { RemoteGetStressTest test=new RemoteGetStressTest(); test.start(); } protected Address randomMember() { return Util.pickRandomElement(target_members); } protected static void insertDISCARD(JChannel ch, double discard_rate) throws Exception { TP transport=ch.getProtocolStack().getTransport(); DISCARD discard=new DISCARD(); discard.setUpDiscardRate(discard_rate); ch.getProtocolStack().insertProtocol(discard, ProtocolStack.Position.ABOVE, transport.getClass()); } protected class Invoker extends Thread { protected final RpcDispatcher disp; protected final AtomicInteger success, failure; public Invoker(RpcDispatcher disp, AtomicInteger success, AtomicInteger failure) { this.disp=disp; this.success=success; this.failure=failure; } public void run() { ArrayList<Address> targets = new ArrayList<>(channels[0].getView().getMembers()); targets.remove(random.nextInt(targets.size())); Collections.rotate(targets, random.nextInt(targets.size())); Future<BigObject>[] futures = new Future[targets.size()]; for(int i=0; i < targets.size(); i++) { Address target=targets.get(i); try { futures[i]=disp.callRemoteMethodWithFuture(target, GET_METHOD, OPTIONS); } catch(Exception e) { e.printStackTrace(); } } for(Future<BigObject> future: futures) { if(future == null) continue; try { BigObject result=future.get(TIMEOUT, TimeUnit.MILLISECONDS); if(result != null) { System.out.println("received object #" + result.num); success.incrementAndGet(); return; } } catch(Exception e) { e.printStackTrace(); } } failure.incrementAndGet(); } } public static class BigObject implements Serializable { private static final long serialVersionUID=1265292900051224502L; int num; public BigObject(int num) { this.num = num; } public BigObject() { } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); byte[] buf = new byte[SIZE]; out.write(buf); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); byte[] buf = new byte[SIZE]; in.read(buf); if(USE_SLEEPS) Util.sleepRandom(1, 10); } @Override public String toString() { return "BigObject#" + num; } } }
/* * Copyright (C) 2014-2016 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.lang.tests.parsing.oop; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.eclipse.xtext.common.types.JvmTypeConstraint; import org.eclipse.xtext.common.types.JvmTypeParameter; import io.sarl.lang.sarl.SarlAction; import io.sarl.lang.sarl.SarlAgent; import io.sarl.lang.sarl.SarlBehavior; import io.sarl.lang.sarl.SarlBehaviorUnit; import io.sarl.lang.sarl.SarlCapacity; import io.sarl.lang.sarl.SarlCapacityUses; import io.sarl.lang.sarl.SarlClass; import io.sarl.lang.sarl.SarlEvent; import io.sarl.lang.sarl.SarlField; import io.sarl.lang.sarl.SarlInterface; import io.sarl.lang.sarl.SarlPackage; import io.sarl.lang.sarl.SarlScript; import io.sarl.lang.sarl.SarlSkill; import io.sarl.lang.validation.IssueCodes; import io.sarl.tests.api.AbstractSarlTest; import org.eclipse.xtext.common.types.JvmVisibility; import org.eclipse.xtext.common.types.TypesPackage; import org.eclipse.xtext.diagnostics.Diagnostic; import org.eclipse.xtext.junit4.util.ParseHelper; import org.eclipse.xtext.junit4.validation.ValidationTestHelper; import org.eclipse.xtext.xbase.XNumberLiteral; import org.eclipse.xtext.xbase.XStringLiteral; import org.eclipse.xtext.xbase.XbasePackage; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.google.common.base.Strings; import com.google.inject.Inject; /** * @author $Author: sgalland$ * @version $Name$ $Revision$ $Date$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ @RunWith(Suite.class) @SuiteClasses({ InterfaceParsingTest.TopInterfaceTest.class, InterfaceParsingTest.InsideClassTest.class, InterfaceParsingTest.InsideAgentTest.class, InterfaceParsingTest.InsideBehaviorTest.class, InterfaceParsingTest.InsideSkillTest.class, InterfaceParsingTest.GenericTest.class, }) @SuppressWarnings("all") public class InterfaceParsingTest { public static class TopInterfaceTest extends AbstractSarlTest { protected SarlInterface getInterface(SarlScript script) { return (SarlInterface) script.getXtendTypes().get(0); } @Test public void classmodifier_public() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public interface I1 { }"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertFalse(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_none() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 { }"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertFalse(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_private() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "private interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 7, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_protected() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "protected interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 9, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "package interface I1 { }"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.DEFAULT, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertFalse(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_abstract() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "abstract interface I1 { }"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertFalse(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_static() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "static interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 6, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_dispatch() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "dispatch interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 8, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "final interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 5, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_strictfp() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "strictfp interface I1 { }"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertFalse(interf.isStatic()); assertTrue(interf.isStrictFloatingPoint()); } @Test public void classmodifier_native() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "native interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 6, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_volatile() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "volatile interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 8, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_synchronized() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "synchronized interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 12, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_transient() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "transient interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 32, 9, "Illegal modifier for the interface I1; only public, package, abstract & strictfp are permitted"); } @Test public void classmodifier_abstract_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "abstract final interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 41, 5, "The interface I1 can either be abstract or final, not both"); } @Test public void classmodifier_public_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public private interface I1 { }"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 39, 7, "The interface I1 can only set one of public / package / protected / private"); } } public static class InsideClassTest extends AbstractSarlTest { protected SarlInterface getInterface(SarlScript script) { SarlClass enclosing = (SarlClass) script.getXtendTypes().get(0); return (SarlInterface) enclosing.getMembers().get(0); } @Test public void classmodifier_public() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " public interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_none() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_private() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " private interface I1 { }", "}"), false); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PRIVATE, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_protected() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " protected interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " package interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.DEFAULT, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_abstract() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " abstract interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_static() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " static interface I1 { }", "}"), false); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_dispatch() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " dispatch interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 8, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 5, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_strictfp() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " strictfp interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertTrue(interf.isStrictFloatingPoint()); } @Test public void classmodifier_native() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " native interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 6, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_volatile() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " volatile interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 8, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_synchronized() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " synchronized interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 12, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_transient() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " transient interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 9, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_abstract_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " abstract final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 73, 5, "The interface I1 can either be abstract or final, not both"); } @Test public void classmodifier_public_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public class EnclosingClass {", " public private interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 71, 7, "The interface I1 can only set one of public / package / protected / private"); } } public static class InsideAgentTest extends AbstractSarlTest { protected SarlInterface getInterface(SarlScript script) { SarlAgent enclosing = (SarlAgent) script.getXtendTypes().get(0); return (SarlInterface) enclosing.getMembers().get(0); } @Test public void classmodifier_public() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " public interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 6); } @Test public void classmodifier_none() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_private() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " private interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PRIVATE, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_protected() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " protected interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " package interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.DEFAULT, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_abstract() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " abstract interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_static() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " static interface I1 { }", "}"), false); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_dispatch() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " dispatch interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 8); } @Test public void classmodifier_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 5); } @Test public void classmodifier_strictfp() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " strictfp interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertTrue(interf.isStrictFloatingPoint()); } @Test public void classmodifier_native() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " native interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 6); } @Test public void classmodifier_volatile() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " volatile interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 8); } @Test public void classmodifier_synchronized() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " synchronized interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 12); } @Test public void classmodifier_transient() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " transient interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 64, 9); } @Test public void classmodifier_abstract_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " abstract final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 73, 5, "abstract or final, not both"); } @Test public void classmodifier_public_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public agent EnclosingAgent {", " public private interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 71, 7, "public / package / protected / private"); } } public static class InsideBehaviorTest extends AbstractSarlTest { protected SarlInterface getInterface(SarlScript script) { SarlBehavior enclosing = (SarlBehavior) script.getXtendTypes().get(0); return (SarlInterface) enclosing.getMembers().get(0); } @Test public void classmodifier_public() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " public interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_none() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_private() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " private interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PRIVATE, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_protected() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " protected interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " package interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.DEFAULT, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_abstract() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " abstract interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_static() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " static interface I1 { }", "}"), false); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_dispatch() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " dispatch interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 70, 8, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 70, 5, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_strictfp() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " strictfp interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertTrue(interf.isStrictFloatingPoint()); } @Test public void classmodifier_native() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " native interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 70, 6, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_volatile() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " volatile interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 70, 8, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_synchronized() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " synchronized interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 70, 12, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_transient() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " transient interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 70, 9, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_abstract_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " abstract final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 79, 5, "The interface I1 can either be abstract or final, not both"); } @Test public void classmodifier_public_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public behavior EnclosingBehavior {", " public private interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 77, 7, "The interface I1 can only set one of public / package / protected / private"); } } public static class InsideSkillTest extends AbstractSarlTest { protected SarlInterface getInterface(SarlScript script) { SarlSkill enclosing = (SarlSkill) script.getXtendTypes().get(1); return (SarlInterface) enclosing.getMembers().get(0); } @Test public void classmodifier_public() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " public interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PUBLIC, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_none() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_private() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " private interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PRIVATE, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_protected() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " protected interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " package interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.DEFAULT, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_abstract() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " abstract interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_static() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " static interface I1 { }", "}"), false); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertFalse(interf.isStrictFloatingPoint()); } @Test public void classmodifier_dispatch() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " dispatch interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 101, 8, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 101, 5, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_strictfp() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " strictfp interface I1 { }", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = getInterface(mas); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertNullOrEmpty(interf.getExtends()); assertEquals(JvmVisibility.PROTECTED, interf.getVisibility()); assertEquals(0, interf.getMembers().size()); assertFalse(interf.isAnonymous()); assertFalse(interf.isFinal()); assertFalse(interf.isLocal()); assertTrue(interf.isStatic()); assertTrue(interf.isStrictFloatingPoint()); } @Test public void classmodifier_native() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " native interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 101, 6, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_volatile() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " volatile interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 101, 8, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_synchronized() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " synchronized interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 101, 12, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_transient() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " transient interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 101, 9, "Illegal modifier for the interface I1; only public, package, protected, private, static, abstract & strictfp are permitted"); } @Test public void classmodifier_abstract_final() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " abstract final interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 110, 5, "The interface I1 can either be abstract or final, not both"); } @Test public void classmodifier_public_package() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "public capacity C1 { }", "public skill EnclosingSkill implements C1 {", " public private interface I1 { }", "}"), false); validate(mas).assertError( SarlPackage.eINSTANCE.getSarlInterface(), org.eclipse.xtend.core.validation.IssueCodes.INVALID_MODIFIER, 108, 7, "The interface I1 can only set one of public / package / protected / private"); } } public static class GenericTest extends AbstractSarlTest { @Test public void interfaceGeneric_X() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1<X> {", " def setX(param : X)", " def getX : X", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); // assertEquals(1, interf.getTypeParameters().size()); // JvmTypeParameter parameter = interf.getTypeParameters().get(0); assertEquals("X", parameter.getName()); assertNullOrEmpty(parameter.getConstraints()); } @Test public void interfaceGeneric_XextendsNumber() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1<X extends Number> {", " def setX(param : X)", " def getX : X", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); // assertEquals(1, interf.getTypeParameters().size()); // JvmTypeParameter parameter = interf.getTypeParameters().get(0); assertEquals("X", parameter.getName()); assertEquals(1, parameter.getConstraints().size()); // JvmTypeConstraint constraint = parameter.getConstraints().get(0); assertEquals("java.lang.Number", constraint.getTypeReference().getIdentifier()); assertTrue(constraint.getIdentifier().startsWith("extends")); } @Test public void interfaceGeneric_XY() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1<X,Y> {", " def getY : Y", " def setX(param : X)", " def getX : X", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); // assertEquals(2, interf.getTypeParameters().size()); // JvmTypeParameter parameter1 = interf.getTypeParameters().get(0); assertEquals("X", parameter1.getName()); assertNullOrEmpty(parameter1.getConstraints()); // JvmTypeParameter parameter2 = interf.getTypeParameters().get(1); assertEquals("Y", parameter2.getName()); assertNullOrEmpty(parameter2.getConstraints()); } @Test public void interfaceGeneric_XYextendsX() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1<X,Y extends X> {", " def getY : Y", " def setX(param : X)", " def getX : X", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); // assertEquals(2, interf.getTypeParameters().size()); // JvmTypeParameter parameter1 = interf.getTypeParameters().get(0); assertEquals("X", parameter1.getName()); assertNullOrEmpty(parameter1.getConstraints()); // JvmTypeParameter parameter2 = interf.getTypeParameters().get(1); assertEquals("Y", parameter2.getName()); assertEquals(1, parameter2.getConstraints().size()); // JvmTypeConstraint constraint = parameter2.getConstraints().get(0); assertEquals("X", constraint.getTypeReference().getIdentifier()); assertTrue(constraint.getIdentifier().startsWith("extends")); } @Test public void interfaceGeneric_XextendsYY() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1<X extends Y,Y> {", " def getY : Y", " def setX(param : X)", " def getX : X", "}"), false); validate(mas).assertError( TypesPackage.eINSTANCE.getJvmParameterizedTypeReference(), org.eclipse.xtext.xbase.validation.IssueCodes.TYPE_PARAMETER_FORWARD_REFERENCE, 55, 1, "Illegal forward reference to type parameter Y"); } @Test public void functionGeneric_X_sarlNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def setX(param : X) : void with X", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(1, action.getTypeParameters().size()); // JvmTypeParameter parameter = action.getTypeParameters().get(0); assertEquals("X", parameter.getName()); assertNullOrEmpty(parameter.getConstraints()); } @Test public void functionGeneric_X_javaNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def <X> setX(param : X) : void", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(1, action.getTypeParameters().size()); // JvmTypeParameter parameter = action.getTypeParameters().get(0); assertEquals("X", parameter.getName()); assertNullOrEmpty(parameter.getConstraints()); } @Test public void functionGeneric_XextendsNumber_sarlNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def setX(param : X) : void with X extends Number", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(1, action.getTypeParameters().size()); // JvmTypeParameter parameter = action.getTypeParameters().get(0); assertEquals("X", parameter.getName()); assertEquals(1, parameter.getConstraints().size()); // JvmTypeConstraint constraint = parameter.getConstraints().get(0); assertEquals("java.lang.Number", constraint.getTypeReference().getIdentifier()); assertTrue(constraint.getIdentifier().startsWith("extends")); } @Test public void functionGeneric_XextendsNumber_javaNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def <X extends Number> setX(param : X) : void", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(1, action.getTypeParameters().size()); // JvmTypeParameter parameter = action.getTypeParameters().get(0); assertEquals("X", parameter.getName()); assertEquals(1, parameter.getConstraints().size()); // JvmTypeConstraint constraint = parameter.getConstraints().get(0); assertEquals("java.lang.Number", constraint.getTypeReference().getIdentifier()); assertTrue(constraint.getIdentifier().startsWith("extends")); } @Test public void functionGeneric_XY_sarlNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def setX(param : X) : void with X, Y", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(2, action.getTypeParameters().size()); // JvmTypeParameter parameter1 = action.getTypeParameters().get(0); assertEquals("X", parameter1.getName()); assertNullOrEmpty(parameter1.getConstraints()); // JvmTypeParameter parameter2 = action.getTypeParameters().get(1); assertEquals("Y", parameter2.getName()); assertNullOrEmpty(parameter2.getConstraints()); } @Test public void functionGeneric_XY_javaNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def <X, Y> setX(param : X) : void", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(2, action.getTypeParameters().size()); // JvmTypeParameter parameter1 = action.getTypeParameters().get(0); assertEquals("X", parameter1.getName()); assertNullOrEmpty(parameter1.getConstraints()); // JvmTypeParameter parameter2 = action.getTypeParameters().get(1); assertEquals("Y", parameter2.getName()); assertNullOrEmpty(parameter2.getConstraints()); } @Test public void functionGeneric_XYextendsX_sarlNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def setX(param : X) : void with X, Y extends X", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(2, action.getTypeParameters().size()); // JvmTypeParameter parameter1 = action.getTypeParameters().get(0); assertEquals("X", parameter1.getName()); assertNullOrEmpty(parameter1.getConstraints()); // JvmTypeParameter parameter2 = action.getTypeParameters().get(1); assertEquals("Y", parameter2.getName()); assertEquals(1, parameter2.getConstraints().size()); // JvmTypeConstraint constraint = parameter2.getConstraints().get(0); assertEquals("X", constraint.getTypeReference().getIdentifier()); assertTrue(constraint.getIdentifier().startsWith("extends")); } @Test public void functionGeneric_XYextendsX_javaNotation() throws Exception { SarlScript mas = file(multilineString( "package io.sarl.lang.tests.test", "interface I1 {", " def <X, Y extends X> setX(param : X) : void", "}"), true); assertEquals("io.sarl.lang.tests.test", mas.getPackage()); SarlInterface interf = (SarlInterface) mas.getXtendTypes().get(0); assertNotNull(interf); // assertEquals("I1", interf.getName()); assertEquals(1, interf.getMembers().size()); // SarlAction action = (SarlAction) interf.getMembers().get(0); assertEquals("setX", action.getName()); assertEquals(2, action.getTypeParameters().size()); // JvmTypeParameter parameter1 = action.getTypeParameters().get(0); assertEquals("X", parameter1.getName()); assertNullOrEmpty(parameter1.getConstraints()); // JvmTypeParameter parameter2 = action.getTypeParameters().get(1); assertEquals("Y", parameter2.getName()); assertEquals(1, parameter2.getConstraints().size()); // JvmTypeConstraint constraint = parameter2.getConstraints().get(0); assertEquals("X", constraint.getTypeReference().getIdentifier()); assertTrue(constraint.getIdentifier().startsWith("extends")); } } }
/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; import org.joda.time.field.FieldUtils; import org.joda.time.field.ImpreciseDateTimeField; /** * Provides time calculations for the month of the year component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.2, refactored from GJMonthOfYearDateTimeField */ class BasicMonthOfYearDateTimeField extends ImpreciseDateTimeField { /** Serialization version */ private static final long serialVersionUID = -8258715387168736L; private static final int MIN = DateTimeConstants.JANUARY; private final BasicChronology iChronology; private final int iMax; private final int iLeapMonth; /** * Restricted constructor. * * @param leapMonth the month of year that leaps */ BasicMonthOfYearDateTimeField(BasicChronology chronology, int leapMonth) { super(DateTimeFieldType.monthOfYear(), chronology.getAverageMillisPerMonth()); iChronology = chronology; iMax = iChronology.getMaxMonth(); iLeapMonth = leapMonth; } //----------------------------------------------------------------------- public boolean isLenient() { return false; } //----------------------------------------------------------------------- /** * Get the Month component of the specified time instant. * * @see org.joda.time.DateTimeField#get(long) * @see org.joda.time.ReadableDateTime#getMonthOfYear() * @param instant the time instant in millis to query. * @return the month extracted from the input. */ public int get(long instant) { return iChronology.getMonthOfYear(instant); } //----------------------------------------------------------------------- /** * Add the specified month to the specified time instant. * The amount added may be negative.<p> * If the new month has less total days than the specified * day of the month, this value is coerced to the nearest * sane value. e.g.<p> * 07-31 - (1 month) = 06-30<p> * 03-31 - (1 month) = 02-28 or 02-29 depending<p> * * @see org.joda.time.DateTimeField#add * @see org.joda.time.ReadWritableDateTime#addMonths(int) * @param instant the time instant in millis to update. * @param months the months to add (can be negative). * @return the updated time instant. */ public long add(long instant, int months) { if (months == 0) { return instant; // the easy case } // // Save time part first. // long timePart = iChronology.getMillisOfDay(instant); // // // Get this year and month. // int thisYear = iChronology.getYear(instant); int thisMonth = iChronology.getMonthOfYear(instant, thisYear); // ---------------------------------------------------------- // // Do not refactor without careful consideration. // Order of calculation is important. // int yearToUse; // Initially, monthToUse is zero-based int monthToUse = thisMonth - 1 + months; if (monthToUse >= 0) { yearToUse = thisYear + (monthToUse / iMax); monthToUse = (monthToUse % iMax) + 1; } else { yearToUse = thisYear + (monthToUse / iMax) - 1; monthToUse = Math.abs(monthToUse); int remMonthToUse = monthToUse % iMax; // Take care of the boundary condition if (remMonthToUse == 0) { remMonthToUse = iMax; } monthToUse = iMax - remMonthToUse + 1; // Take care of the boundary condition if (monthToUse == 1) { yearToUse += 1; } } // End of do not refactor. // ---------------------------------------------------------- // // Quietly force DOM to nearest sane value. // int dayToUse = iChronology.getDayOfMonth(instant, thisYear, thisMonth); int maxDay = iChronology.getDaysInYearMonth(yearToUse, monthToUse); if (dayToUse > maxDay) { dayToUse = maxDay; } // // get proper date part, and return result // long datePart = iChronology.getYearMonthDayMillis(yearToUse, monthToUse, dayToUse); return datePart + timePart; } //----------------------------------------------------------------------- public long add(long instant, long months) { int i_months = (int)months; if (i_months == months) { return add(instant, i_months); } // Copied from add(long, int) and modified slightly: long timePart = iChronology.getMillisOfDay(instant); int thisYear = iChronology.getYear(instant); int thisMonth = iChronology.getMonthOfYear(instant, thisYear); long yearToUse; long monthToUse = thisMonth - 1 + months; if (monthToUse >= 0) { yearToUse = thisYear + (monthToUse / iMax); monthToUse = (monthToUse % iMax) + 1; } else { yearToUse = thisYear + (monthToUse / iMax) - 1; monthToUse = Math.abs(monthToUse); int remMonthToUse = (int)(monthToUse % iMax); if (remMonthToUse == 0) { remMonthToUse = iMax; } monthToUse = iMax - remMonthToUse + 1; if (monthToUse == 1) { yearToUse += 1; } } if (yearToUse < iChronology.getMinYear() || yearToUse > iChronology.getMaxYear()) { throw new IllegalArgumentException ("Magnitude of add amount is too large: " + months); } int i_yearToUse = (int)yearToUse; int i_monthToUse = (int)monthToUse; int dayToUse = iChronology.getDayOfMonth(instant, thisYear, thisMonth); int maxDay = iChronology.getDaysInYearMonth(i_yearToUse, i_monthToUse); if (dayToUse > maxDay) { dayToUse = maxDay; } long datePart = iChronology.getYearMonthDayMillis(i_yearToUse, i_monthToUse, dayToUse); return datePart + timePart; } //----------------------------------------------------------------------- public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) { // overridden as superclass algorithm can't handle // 2004-02-29 + 48 months -> 2008-02-29 type dates if (valueToAdd == 0) { return values; } if (partial.size() > 0 && partial.getFieldType(0).equals(DateTimeFieldType.monthOfYear()) && fieldIndex == 0) { // month is largest field and being added to, such as month-day int curMonth0 = partial.getValue(0) - 1; int newMonth = ((curMonth0 + (valueToAdd % 12) + 12) % 12) + 1; return set(partial, 0, values, newMonth); } if (DateTimeUtils.isContiguous(partial)) { long instant = 0L; for (int i = 0, isize = partial.size(); i < isize; i++) { instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]); } instant = add(instant, valueToAdd); return iChronology.get(partial, instant); } else { return super.add(partial, fieldIndex, values, valueToAdd); } } //----------------------------------------------------------------------- /** * Add to the Month component of the specified time instant * wrapping around within that component if necessary. * * @see org.joda.time.DateTimeField#addWrapField * @param instant the time instant in millis to update. * @param months the months to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int months) { return set(instant, FieldUtils.getWrappedValue(get(instant), months, MIN, iMax)); } //----------------------------------------------------------------------- public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant < subtrahendInstant) { return -getDifference(subtrahendInstant, minuendInstant); } int minuendYear = iChronology.getYear(minuendInstant); int minuendMonth = iChronology.getMonthOfYear(minuendInstant, minuendYear); int subtrahendYear = iChronology.getYear(subtrahendInstant); int subtrahendMonth = iChronology.getMonthOfYear(subtrahendInstant, subtrahendYear); long difference = (minuendYear - subtrahendYear) * ((long) iMax) + minuendMonth - subtrahendMonth; // Before adjusting for remainder, account for special case of add // where the day-of-month is forced to the nearest sane value. int minuendDom = iChronology.getDayOfMonth (minuendInstant, minuendYear, minuendMonth); if (minuendDom == iChronology.getDaysInYearMonth(minuendYear, minuendMonth)) { // Last day of the minuend month... int subtrahendDom = iChronology.getDayOfMonth (subtrahendInstant, subtrahendYear, subtrahendMonth); if (subtrahendDom > minuendDom) { // ...and day of subtrahend month is larger. // Note: This works fine, but it ideally shouldn't invoke other // fields from within a field. subtrahendInstant = iChronology.dayOfMonth().set(subtrahendInstant, minuendDom); } } // Inlined remainder method to avoid duplicate calls. long minuendRem = minuendInstant - iChronology.getYearMonthMillis(minuendYear, minuendMonth); long subtrahendRem = subtrahendInstant - iChronology.getYearMonthMillis(subtrahendYear, subtrahendMonth); if (minuendRem < subtrahendRem) { difference--; } return difference; } //----------------------------------------------------------------------- /** * Set the Month component of the specified time instant.<p> * If the new month has less total days than the specified * day of the month, this value is coerced to the nearest * sane value. e.g.<p> * 07-31 to month 6 = 06-30<p> * 03-31 to month 2 = 02-28 or 02-29 depending<p> * * @param instant the time instant in millis to update. * @param month the month (1,12) to update the time to. * @return the updated time instant. * @throws IllegalArgumentException if month is invalid */ public long set(long instant, int month) { FieldUtils.verifyValueBounds(this, month, MIN, iMax); // int thisYear = iChronology.getYear(instant); // int thisDom = iChronology.getDayOfMonth(instant, thisYear); int maxDom = iChronology.getDaysInYearMonth(thisYear, month); if (thisDom > maxDom) { // Quietly force DOM to nearest sane value. thisDom = maxDom; } // Return newly calculated millis value return iChronology.getYearMonthDayMillis(thisYear, month, thisDom) + iChronology.getMillisOfDay(instant); } //----------------------------------------------------------------------- public DurationField getRangeDurationField() { return iChronology.years(); } //----------------------------------------------------------------------- public boolean isLeap(long instant) { int thisYear = iChronology.getYear(instant); if (iChronology.isLeapYear(thisYear)) { return (iChronology.getMonthOfYear(instant, thisYear) == iLeapMonth); } return false; } //----------------------------------------------------------------------- public int getLeapAmount(long instant) { return isLeap(instant) ? 1 : 0; } //----------------------------------------------------------------------- public DurationField getLeapDurationField() { return iChronology.days(); } //----------------------------------------------------------------------- public int getMinimumValue() { return MIN; } //----------------------------------------------------------------------- public int getMaximumValue() { return iMax; } //----------------------------------------------------------------------- public long roundFloor(long instant) { int year = iChronology.getYear(instant); int month = iChronology.getMonthOfYear(instant, year); return iChronology.getYearMonthMillis(year, month); } //----------------------------------------------------------------------- public long remainder(long instant) { return instant - roundFloor(instant); } //----------------------------------------------------------------------- /** * Serialization singleton */ private Object readResolve() { return iChronology.monthOfYear(); } }
/* * Copyright 2012 Terlici Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.terlici.dragndroplist; import android.content.Context; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.ListView; import android.widget.Adapter; import android.widget.WrapperListAdapter; import com.terlici.dragndroplist.DragNDropAdapter; public class DragNDropListView extends ListView { public static interface OnItemDragNDropListener { public void onItemDrag(DragNDropListView parent, View view, int position, long id); public void onItemDrop(DragNDropListView parent, View view, int startPosition, int endPosition, long id); } boolean mDragMode; WindowManager mWm; int mStartPosition = INVALID_POSITION; int mDragPointOffset; // Used to adjust drag view location int mDragHandler = 0; ImageView mDragView; OnItemDragNDropListener mDragNDropListener; private void init() { mWm = (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE); } public DragNDropListView(Context context) { super(context); init(); } public DragNDropListView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DragNDropListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void setOnItemDragNDropListener(OnItemDragNDropListener listener) { mDragNDropListener = listener; } public void setDragNDropAdapter(DragNDropAdapter adapter) { mDragHandler = adapter.getDragHandler(); setAdapter(adapter); } /** * If the motion event was inside a handler view. * * @param ev * @return true if it is a dragging move, false otherwise. */ public boolean isDrag(MotionEvent ev) { if (mDragMode) return true; if (mDragHandler == 0) return false; int x = (int)ev.getX(); int y = (int)ev.getY(); int startposition = pointToPosition(x,y); if (startposition == INVALID_POSITION) return false; int childposition = startposition - getFirstVisiblePosition(); View parent = getChildAt(childposition); View handler = parent.findViewById(mDragHandler); if (handler == null) return false; int top = parent.getTop() + handler.getTop(); int bottom = top + handler.getHeight(); int left = parent.getLeft() + handler.getLeft(); int right = left + handler.getWidth(); return left <= x && x <= right && top <= y && y <= bottom; } public boolean isDragging() { return mDragMode; } public View getDragView() { return mDragView; } @Override public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); final int x = (int)ev.getX(); final int y = (int)ev.getY(); if (action == MotionEvent.ACTION_DOWN && isDrag(ev)) mDragMode = true; if (!mDragMode || !isDraggingEnabled) return super.onTouchEvent(ev); switch (action) { case MotionEvent.ACTION_DOWN: mStartPosition = pointToPosition(x, y); if (mStartPosition != INVALID_POSITION) { int childPosition = mStartPosition - getFirstVisiblePosition(); mDragPointOffset = y - getChildAt(childPosition).getTop(); mDragPointOffset -= ((int)ev.getRawY()) - y; startDrag(childPosition, y); drag(0, y); } break; case MotionEvent.ACTION_MOVE: drag(0, y); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: default: mDragMode = false; if (mStartPosition != INVALID_POSITION) { // check if the position is a header/footer int actualPosition = pointToPosition(x,y); if (actualPosition > (getCount() - getFooterViewsCount()) - 1) actualPosition = INVALID_POSITION; stopDrag(mStartPosition - getFirstVisiblePosition(), actualPosition); } break; } return true; } /** * Prepare the drag view. * * @param childIndex * @param y */ private void startDrag(int childIndex, int y) { View item = getChildAt(childIndex); if (item == null) return; long id = getItemIdAtPosition(mStartPosition); if (mDragNDropListener != null) mDragNDropListener.onItemDrag(this, item, mStartPosition, id); Adapter adapter = getAdapter(); DragNDropAdapter dndAdapter; // if exists a footer/header we have our adapter wrapped if (adapter instanceof WrapperListAdapter) { dndAdapter = (DragNDropAdapter)((WrapperListAdapter)adapter).getWrappedAdapter(); } else { dndAdapter = (DragNDropAdapter)adapter; } dndAdapter.onItemDrag(this, item, mStartPosition, id); item.setDrawingCacheEnabled(true); // Create a copy of the drawing cache so that it does not get recycled // by the framework when the list tries to clean up memory Bitmap bitmap = Bitmap.createBitmap(item.getDrawingCache()); WindowManager.LayoutParams mWindowParams = new WindowManager.LayoutParams(); mWindowParams.gravity = Gravity.TOP; mWindowParams.x = 0; mWindowParams.y = y - mDragPointOffset; mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT; mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT; mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; mWindowParams.format = PixelFormat.TRANSLUCENT; mWindowParams.windowAnimations = 0; Context context = getContext(); ImageView v = new ImageView(context); v.setImageBitmap(bitmap); mWm.addView(v, mWindowParams); mDragView = v; item.setVisibility(View.INVISIBLE); item.invalidate(); // We have not changed anything else. } /** * Release all dragging resources. * * @param childIndex */ private void stopDrag(int childIndex, int endPosition) { if (mDragView == null) return; View item = getChildAt(childIndex); if (endPosition != INVALID_POSITION) { long id = getItemIdAtPosition(mStartPosition); if (mDragNDropListener != null) mDragNDropListener.onItemDrop(this, item, mStartPosition, endPosition, id); Adapter adapter = getAdapter(); DragNDropAdapter dndAdapter; // if exists a footer/header we have our adapter wrapped if (adapter instanceof WrapperListAdapter) { dndAdapter = (DragNDropAdapter)((WrapperListAdapter)adapter).getWrappedAdapter(); } else { dndAdapter = (DragNDropAdapter)adapter; } dndAdapter.onItemDrop(this, item, mStartPosition, endPosition, id); } mDragView.setVisibility(GONE); mWm.removeView(mDragView); mDragView.setImageDrawable(null); mDragView = null; item.setDrawingCacheEnabled(false); item.destroyDrawingCache(); item.setVisibility(View.VISIBLE); mStartPosition = INVALID_POSITION; invalidateViews(); // We have changed the adapter data, so change everything } /** * Move the drag view. * * @param x * @param y */ private void drag(int x, int y) { if (mDragView == null) return; WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams)mDragView.getLayoutParams(); layoutParams.x = x; layoutParams.y = y - mDragPointOffset; mWm.updateViewLayout(mDragView, layoutParams); } private boolean isDraggingEnabled = true; public void setDraggingEnabled(boolean draggingEnabled) { this.isDraggingEnabled = draggingEnabled; } }
/* Copyright (c) 2011-2013, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.intel.friend.invitation; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class ReadEngine implements Runnable { static final String LOGC = ReadEngine.class.getCanonicalName(); InputStream mStream; IDataStreamEventListener mListener; Thread mReadEngineThread; volatile boolean mRunning = true; private final int MSG_STATUS = 1; private final int MSG_DATA = 2; private static final int HEADER_SIZE_STATUS = 6; private static String TAG_STATUS = "status"; private static String ATTR_VALUE = "value"; public ReadEngine(InputStream stream, IDataStreamEventListener listener) { this.mStream = stream; this.mReadChannel = Channels.newChannel(stream); this.mListener = listener; mReadEngineThread = new Thread(this); mReadEngineThread.setDaemon(true); mReadEngineThread.setName("Read Engine Thread"); mReadEngineThread.start(); } private void statusAvailable(String statusCode) { int value = Integer.parseInt(statusCode); mListener.statusAvailable(value); } ReadableByteChannel mReadChannel; public static byte[] readChannel(ReadableByteChannel rc, int numBytes) { if (rc == null || numBytes < 0) { return null; } ByteBuffer b = null; final int maxRetry = 10; int retry = 0; while (b == null) { try { b = ByteBuffer.allocate(numBytes); } catch (OutOfMemoryError oome) { b = null; System.gc(); try { Thread.sleep(500); } catch (InterruptedException e) { } retry++; if (retry > maxRetry) { return null; } } } int totalRead = 0; int read = 0; while (totalRead < numBytes) { try { read = 0; read = rc.read(b); if (read == -1) { return null; } totalRead += read; } catch (IOException e) { return null; } } return b.array(); } /** * Parses 4 bytes from a byte[] * * @param buffer * @param offset * @return */ private int parseInt(byte[] buffer, int offset) { int ret = ((buffer[offset + 0] & 0xff) << 24) | ((buffer[offset + 1] & 0xff) << 16) | ((buffer[offset + 2] & 0xff) << 8) | (buffer[offset + 3] & 0xff); return ret; } /** * Parses 2 bytes from a byte[] * * @param buffer * @param offset * @return */ private short parseShort(byte[] buffer, int offset) { short ret = (short) ((buffer[offset + 0] << 8) + (buffer[offset + 1] & 0xFF)); return ret; } public void run() { byte[] buffer = null; mRunning = true; while (mRunning) { try { buffer = readChannel(mReadChannel, 2); int type = 0; if (buffer == null) { mRunning = false; } type = parseShort(buffer, 0); buffer = readChannel(mReadChannel, 4); if (buffer == null) { mRunning = false; continue; } int size = parseInt(buffer, 0); if (size < 0) { mRunning = false; break; } if (type == MSG_STATUS) { buffer = readChannel(mReadChannel, size - HEADER_SIZE_STATUS); String bufferString = null; try { if (buffer != null) bufferString = new String(buffer); buffer = null; } catch (OutOfMemoryError e) { bufferString = null; buffer = null; } if (bufferString == null) { mRunning = false; continue; } parseStatus(bufferString); } } catch (Exception ie) { } } // End running loop } private void parseStatus(String dataString) { if (dataString == null || dataString.compareTo("") == 0) return; try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Reader reader = new StringReader(dataString); Document dom = builder.parse(new InputSource(reader)); // REQUEST NodeList items = dom.getElementsByTagName(TAG_STATUS); String statusCode = null; for (int i = 0; i < items.getLength(); i++) { Node item = items.item(i); NamedNodeMap attrs = item.getAttributes(); for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); if (attr.getNodeName().compareToIgnoreCase(ATTR_VALUE) == 0) { statusCode = attr.getNodeValue(); statusAvailable(statusCode); break; } } } } catch (Exception e) { } } public void stop() { mRunning = false; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.api.records; import java.io.Serializable; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.classification.InterfaceStability.Stable; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.util.Records; /** * <p><code>ResourceRequest</code> represents the request made by an * application to the <code>ResourceManager</code> to obtain various * <code>Container</code> allocations.</p> * * <p>It includes: * <ul> * <li>{@link Priority} of the request.</li> * <li> * The <em>name</em> of the machine or rack on which the allocation is * desired. A special value of <em>*</em> signifies that * <em>any</em> host/rack is acceptable to the application. * </li> * <li>{@link Resource} required for each request.</li> * <li> * Number of containers, of above specifications, which are required * by the application. * </li> * <li> * A boolean <em>relaxLocality</em> flag, defaulting to <code>true</code>, * which tells the <code>ResourceManager</code> if the application wants * locality to be loose (i.e. allows fall-through to rack or <em>any</em>) * or strict (i.e. specify hard constraint on resource allocation). * </li> * </ul> * </p> * * @see Resource * @see ApplicationMasterProtocol#allocate(org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest) */ @Public @Stable public abstract class ResourceRequest implements Comparable<ResourceRequest> { @Public @Stable public static ResourceRequest newInstance(Priority priority, String hostName, Resource capability, int numContainers) { return newInstance(priority, hostName, capability, numContainers, true); } @Public @Stable public static ResourceRequest newInstance(Priority priority, String hostName, Resource capability, int numContainers, boolean relaxLocality) { return newInstance(priority, hostName, capability, numContainers, relaxLocality, null); } @Public @Stable public static ResourceRequest newInstance(Priority priority, String hostName, Resource capability, int numContainers, boolean relaxLocality, String labelExpression) { ResourceRequest request = Records.newRecord(ResourceRequest.class); request.setPriority(priority); request.setResourceName(hostName); request.setCapability(capability); request.setNumContainers(numContainers); request.setRelaxLocality(relaxLocality); request.setNodeLabelExpression(labelExpression); return request; } @Public @Stable public static class ResourceRequestComparator implements java.util.Comparator<ResourceRequest>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(ResourceRequest r1, ResourceRequest r2) { // Compare priority, host and capability int ret = r1.getPriority().compareTo(r2.getPriority()); if (ret == 0) { String h1 = r1.getResourceName(); String h2 = r2.getResourceName(); ret = h1.compareTo(h2); } if (ret == 0) { ret = r1.getCapability().compareTo(r2.getCapability()); } return ret; } } /** * The constant string representing no locality. * It should be used by all references that want to pass an arbitrary host * name in. */ public static final String ANY = "*"; /** * Check whether the given <em>host/rack</em> string represents an arbitrary * host name. * * @param hostName <em>host/rack</em> on which the allocation is desired * @return whether the given <em>host/rack</em> string represents an arbitrary * host name */ @Public @Stable public static boolean isAnyLocation(String hostName) { return ANY.equals(hostName); } /** * Get the <code>Priority</code> of the request. * @return <code>Priority</code> of the request */ @Public @Stable public abstract Priority getPriority(); /** * Set the <code>Priority</code> of the request * @param priority <code>Priority</code> of the request */ @Public @Stable public abstract void setPriority(Priority priority); /** * Get the resource (e.g. <em>host/rack</em>) on which the allocation * is desired. * * A special value of <em>*</em> signifies that <em>any</em> resource * (host/rack) is acceptable. * * @return resource (e.g. <em>host/rack</em>) on which the allocation * is desired */ @Public @Stable public abstract String getResourceName(); /** * Set the resource name (e.g. <em>host/rack</em>) on which the allocation * is desired. * * A special value of <em>*</em> signifies that <em>any</em> resource name * (e.g. host/rack) is acceptable. * * @param resourceName (e.g. <em>host/rack</em>) on which the * allocation is desired */ @Public @Stable public abstract void setResourceName(String resourceName); /** * Get the <code>Resource</code> capability of the request. * @return <code>Resource</code> capability of the request */ @Public @Stable public abstract Resource getCapability(); /** * Set the <code>Resource</code> capability of the request * @param capability <code>Resource</code> capability of the request */ @Public @Stable public abstract void setCapability(Resource capability); /** * Get the number of containers required with the given specifications. * @return number of containers required with the given specifications */ @Public @Stable public abstract int getNumContainers(); /** * Set the number of containers required with the given specifications * @param numContainers number of containers required with the given * specifications */ @Public @Stable public abstract void setNumContainers(int numContainers); /** * Get whether locality relaxation is enabled with this * <code>ResourceRequest</code>. Defaults to true. * * @return whether locality relaxation is enabled with this * <code>ResourceRequest</code>. */ @Public @Stable public abstract boolean getRelaxLocality(); /** * <p>For a request at a network hierarchy level, set whether locality can be relaxed * to that level and beyond.<p> * * <p>If the flag is off on a rack-level <code>ResourceRequest</code>, * containers at that request's priority will not be assigned to nodes on that * request's rack unless requests specifically for those nodes have also been * submitted.<p> * * <p>If the flag is off on an {@link ResourceRequest#ANY}-level * <code>ResourceRequest</code>, containers at that request's priority will * only be assigned on racks for which specific requests have also been * submitted.<p> * * <p>For example, to request a container strictly on a specific node, the * corresponding rack-level and any-level requests should have locality * relaxation set to false. Similarly, to request a container strictly on a * specific rack, the corresponding any-level request should have locality * relaxation set to false.<p> * * @param relaxLocality whether locality relaxation is enabled with this * <code>ResourceRequest</code>. */ @Public @Stable public abstract void setRelaxLocality(boolean relaxLocality); /** * Get node-label-expression for this Resource Request. If this is set, all * containers allocated to satisfy this resource-request will be only on those * nodes that satisfy this node-label-expression * * @return node-label-expression */ @Public @Evolving public abstract String getNodeLabelExpression(); /** * Set node label expression of this resource request. Now only * support AND(&&), in the future will provide support for OR(||), NOT(!). * * Examples: * - GPU && LARGE_MEM, ask for node has label GPU and LARGE_MEM together * - "" (empty) means ask for node doesn't have label on it, this is default * behavior * * @param nodelabelExpression node-label-expression of this ResourceRequest */ @Public @Evolving public abstract void setNodeLabelExpression(String nodelabelExpression); @Override public int hashCode() { final int prime = 2153; int result = 2459; Resource capability = getCapability(); String hostName = getResourceName(); Priority priority = getPriority(); result = prime * result + ((capability == null) ? 0 : capability.hashCode()); result = prime * result + ((hostName == null) ? 0 : hostName.hashCode()); result = prime * result + getNumContainers(); result = prime * result + ((priority == null) ? 0 : priority.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ResourceRequest other = (ResourceRequest) obj; Resource capability = getCapability(); if (capability == null) { if (other.getCapability() != null) return false; } else if (!capability.equals(other.getCapability())) return false; String hostName = getResourceName(); if (hostName == null) { if (other.getResourceName() != null) return false; } else if (!hostName.equals(other.getResourceName())) return false; if (getNumContainers() != other.getNumContainers()) return false; Priority priority = getPriority(); if (priority == null) { if (other.getPriority() != null) return false; } else if (!priority.equals(other.getPriority())) return false; if (getNodeLabelExpression() == null) { if (other.getNodeLabelExpression() != null) { return false; } } else { // do normalize on label expression before compare String label1 = getNodeLabelExpression().replaceAll("[\\t ]", ""); String label2 = other.getNodeLabelExpression() == null ? null : other .getNodeLabelExpression().replaceAll("[\\t ]", ""); if (!label1.equals(label2)) { return false; } } return true; } @Override public int compareTo(ResourceRequest other) { int priorityComparison = this.getPriority().compareTo(other.getPriority()); if (priorityComparison == 0) { int hostNameComparison = this.getResourceName().compareTo(other.getResourceName()); if (hostNameComparison == 0) { int capabilityComparison = this.getCapability().compareTo(other.getCapability()); if (capabilityComparison == 0) { return this.getNumContainers() - other.getNumContainers(); } else { return capabilityComparison; } } else { return hostNameComparison; } } else { return priorityComparison; } } }
/****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.allseen.timeservice.sample.server.logic; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import org.alljoyn.bus.ErrorReplyBusException; import org.allseen.timeservice.Schedule; import org.allseen.timeservice.Schedule.WeekDay; import org.allseen.timeservice.TimeServiceException; import org.allseen.timeservice.sample.server.ui.TimeSampleServer; import org.allseen.timeservice.server.Alarm; import android.content.Context; import android.text.format.Time; import android.util.Log; /** * Represents an Alarm {@link org.allseen.timeservice.server.Alarm}. * Sets an Alarm to expire. Upon designated time reached, a relevant signal is emitted. * Calculates the alarm's designated time relatively to the system time. * In case the time of the clock changes, the time of the alarm is updated accordingly. */ public class ServerAlarm extends Alarm { /** * Log Tag */ private static final String TAG = "ServerAlarm"; /** * Milliseconds in a day */ private static final long DAY_MSEC = 24 * 60 * 60 * 1000; /** * Timer to activate TimeTask */ private Timer timer = new Timer(); /** * Stores context */ private final Context context; /** * {@link Schedule} */ private Schedule schedule; /** * Alarm title */ private String title; /** * Is Alarm enabled */ private boolean isEnabled; /** * Constructor */ public ServerAlarm(Context context) { super(); this.context = context; Time t = new Time(Time.getCurrentTimezone()); t.setToNow(); org.allseen.timeservice.Time ts = new org.allseen.timeservice.Time((byte) 0, (byte) 0, (byte) 0, (short) 0); schedule = new Schedule(ts); title = ""; // in case the clock has changed we need to update the alarm with regards to the new time TimeOffsetManager.getInstance().registerTimeChangeListener(new TimeChangeListener() { @Override public void timeHasChanged(long newTime) { if (isEnabled) { Log.d(TAG, "Clock has changed updating Alarm [" + getObjectPath() + "]"); startNewTimer(); } } }); TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm has been created"); } @Override public Schedule getSchedule() { TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm getSchedule request"); return schedule; } @Override public void setSchedule(Schedule schedule) throws ErrorReplyBusException { TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm setSchedule request"); this.schedule = schedule; if (isEnabled) { startNewTimer(); } } @Override public String getTitle() { TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm getTitle request"); return title; } @Override public void setTitle(String title) { TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm setTitle request"); this.title = title; } @Override public boolean isEnabled() { TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm isEnabled request"); return isEnabled; } @Override public void setEnabled(boolean enabled) { TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm setEnabled request"); this.isEnabled = enabled; if (isEnabled) { startNewTimer(); } else { timer.cancel(); timer.purge(); timer = new Timer(); } } @Override public void alarmReached() throws TimeServiceException { Log.d(TAG, "alarmReached for [" + getObjectPath() + "]"); TimeSampleServer.sendMessage(context, TimeSampleServer.ALARM_EVENT_ACTION, getObjectPath(), "Alarm alarmReached Event"); super.alarmReached(); } /** * Starts a new timer. Checks if it's a one time Alarm ,in this case use the {@link Timer#schedule(TimerTask, long)} else use {@link Timer#scheduleAtFixedRate(TimerTask, long, long)} */ private void startNewTimer() { timer.cancel(); timer.purge(); timer = new Timer(); final ServerAlarm alarm = this; // use the server clock date and fill with the alarm schedule time . Calendar rawAlarmTime = TimeOffsetManager.getInstance().getCurrentServerTime(); rawAlarmTime.set(Calendar.HOUR_OF_DAY, schedule.getTime().getHour()); rawAlarmTime.set(Calendar.MINUTE, schedule.getTime().getMinute()); rawAlarmTime.set(Calendar.SECOND, schedule.getTime().getSeconds()); rawAlarmTime.set(Calendar.MILLISECOND, schedule.getTime().getMilliseconds()); Log.d(TAG, "Original Alarm received for [" + getObjectPath() + "] is " + TimeOffsetManager.getInstance().getDateAndTimeDisplayFormat().format(rawAlarmTime.getTime())); Calendar alarmInServerTime = Calendar.getInstance(); alarmInServerTime.setTimeInMillis(rawAlarmTime.getTimeInMillis() + TimeOffsetManager.getInstance().getTimeDifference()); Log.d(TAG, "Calculated for [" + getObjectPath() + "] is " + TimeOffsetManager.getInstance().getDateAndTimeDisplayFormat().format(alarmInServerTime.getTime())); if (schedule.getWeekDays().size() == 0) { // In this case the alarm is a one time alarm. timer.schedule(new TimerTask() { @Override public void run() { try { alarm.alarmReached(); Log.d(TAG, "Alarms expired for [" + getObjectPath() + "]"); } catch (TimeServiceException e) { Log.e(TAG, "Unable to send alarmReached signal", e); } } }, alarmInServerTime.getTime()); } else { // In this case the alarm is a recurring alarm. timer.schedule(new TimerTask() { @Override public void run() { // Calendar.DAY_OF_WEEK gives us the day in range of 1-7 boolean alarmExpired = false; for (WeekDay weekDay : schedule.getWeekDays()) { // WeekDay ordinal is 0-6 if (weekDay.ordinal() == TimeOffsetManager.getInstance().getCurrentServerTime().get(Calendar.DAY_OF_WEEK) - 1) { alarmExpired = true; break; } } if (alarmExpired) { try { alarm.alarmReached(); Log.d(TAG, "Alarms expired for [" + getObjectPath() + "]"); } catch (TimeServiceException e) { Log.e(TAG, "Unable to send alarmReached signal", e); } } } }, alarmInServerTime.getTime(), DAY_MSEC); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.optimizer.physical; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.Context; import org.apache.hadoop.hive.ql.exec.ConditionalTask; import org.apache.hadoop.hive.ql.exec.MapJoinOperator; import org.apache.hadoop.hive.ql.exec.Operator; import org.apache.hadoop.hive.ql.exec.SparkHashTableSinkOperator; import org.apache.hadoop.hive.ql.exec.Task; import org.apache.hadoop.hive.ql.exec.TaskFactory; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.exec.spark.SparkTask; import org.apache.hadoop.hive.ql.lib.Dispatcher; import org.apache.hadoop.hive.ql.lib.Node; import org.apache.hadoop.hive.ql.lib.TaskGraphWalker; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.plan.BaseWork; import org.apache.hadoop.hive.ql.plan.ConditionalResolver; import org.apache.hadoop.hive.ql.plan.ConditionalResolverSkewJoin; import org.apache.hadoop.hive.ql.plan.ConditionalWork; import org.apache.hadoop.hive.ql.plan.BucketMapJoinContext; import org.apache.hadoop.hive.ql.plan.MapJoinDesc; import org.apache.hadoop.hive.ql.plan.MapWork; import org.apache.hadoop.hive.ql.plan.MapredLocalWork; import org.apache.hadoop.hive.ql.plan.OperatorDesc; import org.apache.hadoop.hive.ql.plan.SparkBucketMapJoinContext; import org.apache.hadoop.hive.ql.plan.SparkHashTableSinkDesc; import org.apache.hadoop.hive.ql.plan.SparkWork; public class SparkMapJoinResolver implements PhysicalPlanResolver { // prevents a task from being processed multiple times private final Set<Task<? extends Serializable>> visitedTasks = new HashSet<>(); @Override public PhysicalContext resolve(PhysicalContext pctx) throws SemanticException { Dispatcher dispatcher = new SparkMapJoinTaskDispatcher(pctx); TaskGraphWalker graphWalker = new TaskGraphWalker(dispatcher); ArrayList<Node> topNodes = new ArrayList<Node>(); topNodes.addAll(pctx.getRootTasks()); graphWalker.startWalking(topNodes, null); return pctx; } // Check whether the specified BaseWork's operator tree contains a operator // of the specified operator class private boolean containsOp(BaseWork work, Class<?> clazz) { Set<Operator<?>> matchingOps = getOp(work, clazz); return matchingOps != null && !matchingOps.isEmpty(); } private boolean containsOp(SparkWork sparkWork, Class<?> clazz) { for (BaseWork work : sparkWork.getAllWorkUnsorted()) { if (containsOp(work, clazz)) { return true; } } return false; } public static Set<Operator<?>> getOp(BaseWork work, Class<?> clazz) { Set<Operator<?>> ops = new HashSet<Operator<?>>(); if (work instanceof MapWork) { Collection<Operator<?>> opSet = ((MapWork) work).getAliasToWork().values(); Stack<Operator<?>> opStack = new Stack<Operator<?>>(); opStack.addAll(opSet); while (!opStack.empty()) { Operator<?> op = opStack.pop(); ops.add(op); if (op.getChildOperators() != null) { opStack.addAll(op.getChildOperators()); } } } else { ops.addAll(work.getAllOperators()); } Set<Operator<? extends OperatorDesc>> matchingOps = new HashSet<Operator<? extends OperatorDesc>>(); for (Operator<? extends OperatorDesc> op : ops) { if (clazz.isInstance(op)) { matchingOps.add(op); } } return matchingOps; } @SuppressWarnings("unchecked") class SparkMapJoinTaskDispatcher implements Dispatcher { private final PhysicalContext physicalContext; // For each BaseWork with MJ operator, we build a SparkWork for its small table BaseWorks // This map records such information private final Map<BaseWork, SparkWork> sparkWorkMap; // SparkWork dependency graph - from a SparkWork with MJ operators to all // of its parent SparkWorks for the small tables private final Map<SparkWork, List<SparkWork>> dependencyGraph; public SparkMapJoinTaskDispatcher(PhysicalContext pc) { super(); physicalContext = pc; sparkWorkMap = new LinkedHashMap<BaseWork, SparkWork>(); dependencyGraph = new LinkedHashMap<SparkWork, List<SparkWork>>(); } // Move the specified work from the sparkWork to the targetWork // Note that, in order not to break the graph (since we need it for the edges), // we don't remove the work from the sparkWork here. The removal is done later. private void moveWork(SparkWork sparkWork, BaseWork work, SparkWork targetWork) { List<BaseWork> parentWorks = sparkWork.getParents(work); if (sparkWork != targetWork) { targetWork.add(work); // If any child work for this work is already added to the targetWork earlier, // we should connect this work with it for (BaseWork childWork : sparkWork.getChildren(work)) { if (targetWork.contains(childWork)) { targetWork.connect(work, childWork, sparkWork.getEdgeProperty(work, childWork)); } } } if (!containsOp(work, MapJoinOperator.class)) { for (BaseWork parent : parentWorks) { moveWork(sparkWork, parent, targetWork); } } else { // Create a new SparkWork for all the small tables of this work SparkWork parentWork = new SparkWork(physicalContext.conf.getVar(HiveConf.ConfVars.HIVEQUERYID)); // copy cloneToWork to ensure RDD cache still works parentWork.setCloneToWork(sparkWork.getCloneToWork()); dependencyGraph.get(targetWork).add(parentWork); dependencyGraph.put(parentWork, new ArrayList<SparkWork>()); // this work is now moved to the parentWork, thus we should // update this information in sparkWorkMap sparkWorkMap.put(work, parentWork); for (BaseWork parent : parentWorks) { if (containsOp(parent, SparkHashTableSinkOperator.class)) { moveWork(sparkWork, parent, parentWork); } else { moveWork(sparkWork, parent, targetWork); } } } } private void generateLocalWork(SparkTask originalTask) { SparkWork originalWork = originalTask.getWork(); Collection<BaseWork> allBaseWorks = originalWork.getAllWork(); Context ctx = physicalContext.getContext(); for (BaseWork work : allBaseWorks) { if (work.getMapRedLocalWork() == null) { if (containsOp(work, SparkHashTableSinkOperator.class) || containsOp(work, MapJoinOperator.class)) { work.setMapRedLocalWork(new MapredLocalWork()); } Set<Operator<?>> ops = getOp(work, MapJoinOperator.class); if (ops == null || ops.isEmpty()) { continue; } Path tmpPath = Utilities.generateTmpPath(ctx.getMRTmpPath(), originalTask.getId()); MapredLocalWork bigTableLocalWork = work.getMapRedLocalWork(); List<Operator<? extends OperatorDesc>> dummyOps = new ArrayList<Operator<? extends OperatorDesc>>(work.getDummyOps()); bigTableLocalWork.setDummyParentOp(dummyOps); bigTableLocalWork.setTmpPath(tmpPath); // In one work, only one map join operator can be bucketed SparkBucketMapJoinContext bucketMJCxt = null; for (Operator<? extends OperatorDesc> op : ops) { MapJoinOperator mapJoinOp = (MapJoinOperator) op; MapJoinDesc mapJoinDesc = mapJoinOp.getConf(); if (mapJoinDesc.isBucketMapJoin()) { bucketMJCxt = new SparkBucketMapJoinContext(mapJoinDesc); bucketMJCxt.setBucketMatcherClass( org.apache.hadoop.hive.ql.exec.DefaultBucketMatcher.class); bucketMJCxt.setPosToAliasMap(mapJoinOp.getPosToAliasMap()); ((MapWork) work).setUseBucketizedHiveInputFormat(true); bigTableLocalWork.setBucketMapjoinContext(bucketMJCxt); bigTableLocalWork.setInputFileChangeSensitive(true); break; } } for (BaseWork parentWork : originalWork.getParents(work)) { Set<Operator<?>> hashTableSinkOps = getOp(parentWork, SparkHashTableSinkOperator.class); if (hashTableSinkOps == null || hashTableSinkOps.isEmpty()) { continue; } MapredLocalWork parentLocalWork = parentWork.getMapRedLocalWork(); parentLocalWork.setTmpHDFSPath(tmpPath); if (bucketMJCxt != null) { // We only need to update the work with the hashtable // sink operator with the same mapjoin desc. We can tell // that by comparing the bucket file name mapping map // instance. They should be exactly the same one due to // the way how the bucket mapjoin context is constructed. for (Operator<? extends OperatorDesc> op : hashTableSinkOps) { SparkHashTableSinkOperator hashTableSinkOp = (SparkHashTableSinkOperator) op; SparkHashTableSinkDesc hashTableSinkDesc = hashTableSinkOp.getConf(); BucketMapJoinContext original = hashTableSinkDesc.getBucketMapjoinContext(); if (original != null && original.getBucketFileNameMapping() == bucketMJCxt.getBucketFileNameMapping()) { ((MapWork) parentWork).setUseBucketizedHiveInputFormat(true); parentLocalWork.setBucketMapjoinContext(bucketMJCxt); parentLocalWork.setInputFileChangeSensitive(true); break; } } } } } } } // Create a new SparkTask for the specified SparkWork, recursively compute // all the parent SparkTasks that this new task is depend on, if they don't already exists. private SparkTask createSparkTask(SparkTask originalTask, SparkWork sparkWork, Map<SparkWork, SparkTask> createdTaskMap, ConditionalTask conditionalTask) { if (createdTaskMap.containsKey(sparkWork)) { return createdTaskMap.get(sparkWork); } SparkTask resultTask = originalTask.getWork() == sparkWork ? originalTask : (SparkTask) TaskFactory.get(sparkWork, physicalContext.conf); if (!dependencyGraph.get(sparkWork).isEmpty()) { for (SparkWork parentWork : dependencyGraph.get(sparkWork)) { SparkTask parentTask = createSparkTask(originalTask, parentWork, createdTaskMap, conditionalTask); parentTask.addDependentTask(resultTask); } } else { if (originalTask != resultTask) { List<Task<? extends Serializable>> parentTasks = originalTask.getParentTasks(); if (parentTasks != null && parentTasks.size() > 0) { // avoid concurrent modification originalTask.setParentTasks(new ArrayList<Task<? extends Serializable>>()); for (Task<? extends Serializable> parentTask : parentTasks) { parentTask.addDependentTask(resultTask); parentTask.removeDependentTask(originalTask); } } else { if (conditionalTask == null) { physicalContext.addToRootTask(resultTask); physicalContext.removeFromRootTask(originalTask); } else { updateConditionalTask(conditionalTask, originalTask, resultTask); } } } } createdTaskMap.put(sparkWork, resultTask); return resultTask; } @Override public Object dispatch(Node nd, Stack<Node> stack, Object... nos) throws SemanticException { Task<? extends Serializable> currentTask = (Task<? extends Serializable>) nd; if(currentTask.isMapRedTask()) { if (currentTask instanceof ConditionalTask) { List<Task<? extends Serializable>> taskList = ((ConditionalTask) currentTask).getListTasks(); for (Task<? extends Serializable> tsk : taskList) { if (tsk instanceof SparkTask) { processCurrentTask((SparkTask) tsk, (ConditionalTask) currentTask); visitedTasks.add(tsk); } } } else if (currentTask instanceof SparkTask) { processCurrentTask((SparkTask) currentTask, null); visitedTasks.add(currentTask); } } return null; } /** * @param sparkTask The current spark task we're processing. * @param conditionalTask If conditional task is not null, it means the current task is * wrapped in its task list. */ private void processCurrentTask(SparkTask sparkTask, ConditionalTask conditionalTask) { SparkWork sparkWork = sparkTask.getWork(); if (!visitedTasks.contains(sparkTask)) { dependencyGraph.clear(); sparkWorkMap.clear(); // Generate MapredLocalWorks for MJ and HTS generateLocalWork(sparkTask); dependencyGraph.put(sparkWork, new ArrayList<SparkWork>()); Set<BaseWork> leaves = sparkWork.getLeaves(); for (BaseWork leaf : leaves) { moveWork(sparkWork, leaf, sparkWork); } // Now remove all BaseWorks in all the childSparkWorks that we created // from the original SparkWork for (SparkWork newSparkWork : sparkWorkMap.values()) { for (BaseWork work : newSparkWork.getAllWorkUnsorted()) { sparkWork.remove(work); } } Map<SparkWork, SparkTask> createdTaskMap = new LinkedHashMap<SparkWork, SparkTask>(); // Now create SparkTasks from the SparkWorks, also set up dependency for (SparkWork work : dependencyGraph.keySet()) { createSparkTask(sparkTask, work, createdTaskMap, conditionalTask); } } else if (conditionalTask != null) { // We may need to update the conditional task's list. This happens when a common map join // task exists in the task list and has already been processed. In such a case, // the current task is the map join task and we need to replace it with // its parent, i.e. the small table task. if (sparkTask.getParentTasks() != null && sparkTask.getParentTasks().size() == 1 && sparkTask.getParentTasks().get(0) instanceof SparkTask) { SparkTask parent = (SparkTask) sparkTask.getParentTasks().get(0); if (containsOp(sparkWork, MapJoinOperator.class) && containsOp(parent.getWork(), SparkHashTableSinkOperator.class)) { updateConditionalTask(conditionalTask, sparkTask, parent); } } } } /** * Update the task/work list of this conditional task to replace originalTask with newTask. * For runtime skew join, also update dirToTaskMap for the conditional resolver */ private void updateConditionalTask(ConditionalTask conditionalTask, SparkTask originalTask, SparkTask newTask) { ConditionalWork conditionalWork = conditionalTask.getWork(); SparkWork originWork = originalTask.getWork(); SparkWork newWork = newTask.getWork(); List<Task<? extends Serializable>> listTask = conditionalTask.getListTasks(); List<Serializable> listWork = (List<Serializable>) conditionalWork.getListWorks(); int taskIndex = listTask.indexOf(originalTask); int workIndex = listWork.indexOf(originWork); if (taskIndex < 0 || workIndex < 0) { return; } listTask.set(taskIndex, newTask); listWork.set(workIndex, newWork); ConditionalResolver resolver = conditionalTask.getResolver(); if (resolver instanceof ConditionalResolverSkewJoin) { // get bigKeysDirToTaskMap ConditionalResolverSkewJoin.ConditionalResolverSkewJoinCtx context = (ConditionalResolverSkewJoin.ConditionalResolverSkewJoinCtx) conditionalTask .getResolverCtx(); HashMap<Path, Task<? extends Serializable>> bigKeysDirToTaskMap = context .getDirToTaskMap(); // to avoid concurrent modify the hashmap HashMap<Path, Task<? extends Serializable>> newbigKeysDirToTaskMap = new HashMap<Path, Task<? extends Serializable>>(); // reset the resolver for (Map.Entry<Path, Task<? extends Serializable>> entry : bigKeysDirToTaskMap.entrySet()) { Task<? extends Serializable> task = entry.getValue(); Path bigKeyDir = entry.getKey(); if (task.equals(originalTask)) { newbigKeysDirToTaskMap.put(bigKeyDir, newTask); } else { newbigKeysDirToTaskMap.put(bigKeyDir, task); } } context.setDirToTaskMap(newbigKeysDirToTaskMap); // update no skew task if (context.getNoSkewTask() != null && context.getNoSkewTask().equals(originalTask)) { List<Task<? extends Serializable>> noSkewTask = new ArrayList<>(); noSkewTask.add(newTask); context.setNoSkewTask(noSkewTask); } } } } }
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.picasso; import android.R; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.widget.ImageView; import android.widget.RemoteViews; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.IOException; import java.util.concurrent.CountDownLatch; import static com.squareup.picasso.Picasso.LoadedFrom.MEMORY; import static com.squareup.picasso.Picasso.RequestTransformer.IDENTITY; import static com.squareup.picasso.RemoteViewsAction.AppWidgetAction; import static com.squareup.picasso.RemoteViewsAction.NotificationAction; import static com.squareup.picasso.TestUtils.BITMAP_1; import static com.squareup.picasso.TestUtils.TRANSFORM_REQUEST_ANSWER; import static com.squareup.picasso.TestUtils.URI_1; import static com.squareup.picasso.TestUtils.URI_KEY_1; import static com.squareup.picasso.TestUtils.mockCallback; import static com.squareup.picasso.TestUtils.mockFitImageViewTarget; import static com.squareup.picasso.TestUtils.mockImageViewTarget; import static com.squareup.picasso.TestUtils.mockNotification; import static com.squareup.picasso.TestUtils.mockRemoteViews; import static com.squareup.picasso.TestUtils.mockTarget; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RequestCreatorTest { @Mock Picasso picasso; @Captor ArgumentCaptor<Action> actionCaptor; @Before public void shutUp() throws Exception { initMocks(this); when(picasso.transformRequest(any(Request.class))).thenAnswer(TRANSFORM_REQUEST_ANSWER); } @Test public void getOnMainCrashes() throws Exception { try { new RequestCreator(picasso, URI_1, 0).get(); fail("Calling get() on main thread should throw exception"); } catch (IllegalStateException expected) { } } @Test public void loadWithShutdownCrashes() throws Exception { picasso.shutdown = true; try { new RequestCreator(picasso, URI_1, 0).fetch(); fail("Should have crashed with a shutdown picasso."); } catch (IllegalStateException expected) { } } @Test public void getReturnsNullIfNullUriAndResourceId() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final Bitmap[] result = new Bitmap[1]; new Thread(new Runnable() { @Override public void run() { try { result[0] = new RequestCreator(picasso, null, 0).get(); } catch (IOException e) { fail(e.getMessage()); } finally { latch.countDown(); } } }).start(); latch.await(); assertThat(result[0]).isNull(); verifyZeroInteractions(picasso); } @Test public void fetchSubmitsFetchRequest() throws Exception { new RequestCreator(picasso, URI_1, 0).fetch(); verify(picasso).submit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(FetchAction.class); } @Test public void fetchWithFitThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).fit().fetch(); fail("Calling fetch() with fit() should throw an exception"); } catch (IllegalStateException expected) { } } @Test public void intoTargetWithNullThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).into((Target) null); fail("Calling into() with null Target should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoTargetWithFitThrows() throws Exception { try { Target target = mockTarget(); new RequestCreator(picasso, URI_1, 0).fit().into(target); fail("Calling into() target with fit() should throw exception"); } catch (IllegalStateException expected) { } } @Test public void intoTargetWithNullUriAndResourceIdSkipsAndCancels() throws Exception { Target target = mockTarget(); Drawable placeHolderDrawable = mock(Drawable.class); new RequestCreator(picasso, null, 0).placeholder(placeHolderDrawable).into(target); verify(picasso).cancelRequest(target); verify(target).onPrepareLoad(placeHolderDrawable); verifyNoMoreInteractions(picasso); } @Test public void intoTargetWithQuickMemoryCacheCheckDoesNotSubmit() throws Exception { when(picasso.quickMemoryCacheCheck(URI_KEY_1)).thenReturn(BITMAP_1); Target target = mockTarget(); new RequestCreator(picasso, URI_1, 0).into(target); verify(target).onBitmapLoaded(BITMAP_1, MEMORY); verify(picasso).cancelRequest(target); verify(picasso, never()).enqueueAndSubmit(any(Action.class)); } @Test public void intoTargetAndSkipMemoryCacheDoesNotCheckMemoryCache() throws Exception { Target target = mockTarget(); new RequestCreator(picasso, URI_1, 0).skipMemoryCache().into(target); verify(picasso, never()).quickMemoryCacheCheck(URI_KEY_1); } @Test public void intoTargetAndNotInCacheSubmitsTargetRequest() throws Exception { Target target = mockTarget(); Drawable placeHolderDrawable = mock(Drawable.class); new RequestCreator(picasso, URI_1, 0).placeholder(placeHolderDrawable).into(target); verify(target).onPrepareLoad(placeHolderDrawable); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(TargetAction.class); } @Test public void intoImageViewWithNullThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).into((ImageView) null); fail("Calling into() with null ImageView should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoImageViewWithNullUriAndResourceIdSkipsAndCancels() throws Exception { ImageView target = mockImageViewTarget(); new RequestCreator(picasso, null, 0).into(target); verify(picasso).cancelRequest(target); verify(picasso, never()).quickMemoryCacheCheck(anyString()); verify(picasso, never()).enqueueAndSubmit(any(Action.class)); } @Test public void intoImageViewWithQuickMemoryCacheCheckDoesNotSubmit() throws Exception { Picasso picasso = spy(new Picasso(Robolectric.application, mock(Dispatcher.class), Cache.NONE, null, IDENTITY, mock(Stats.class), true)); doReturn(BITMAP_1).when(picasso).quickMemoryCacheCheck(URI_KEY_1); ImageView target = mockImageViewTarget(); Callback callback = mockCallback(); new RequestCreator(picasso, URI_1, 0).into(target, callback); verify(target).setImageDrawable(any(PicassoDrawable.class)); verify(callback).onSuccess(); verify(picasso).cancelRequest(target); verify(picasso, never()).enqueueAndSubmit(any(Action.class)); } @Test public void intoImageViewSetsPlaceholderDrawable() throws Exception { Picasso picasso = spy(new Picasso(Robolectric.application, mock(Dispatcher.class), Cache.NONE, null, IDENTITY, mock(Stats.class), true)); ImageView target = mockImageViewTarget(); Drawable placeHolderDrawable = mock(Drawable.class); new RequestCreator(picasso, URI_1, 0).placeholder(placeHolderDrawable).into(target); verify(target).setImageDrawable(placeHolderDrawable); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class); } @Test public void intoImageViewSetsPlaceholderWithResourceId() throws Exception { Picasso picasso = spy(new Picasso(Robolectric.application, mock(Dispatcher.class), Cache.NONE, null, IDENTITY, mock(Stats.class), true)); ImageView target = mockImageViewTarget(); new RequestCreator(picasso, URI_1, 0).placeholder(R.drawable.picture_frame).into(target); verify(target).setImageResource(R.drawable.picture_frame); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class); } @Test public void cancelNotOnMainThreadCrashes() throws Exception { doCallRealMethod().when(picasso).cancelRequest(any(Target.class)); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { new RequestCreator(picasso, null, 0).into(mockTarget()); fail("Should have thrown IllegalStateException"); } catch (IllegalStateException ignored) { } finally { latch.countDown(); } } }).start(); latch.await(); } @Test public void intoNotOnMainThreadCrashes() throws Exception { doCallRealMethod().when(picasso).enqueueAndSubmit(any(Action.class)); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { new RequestCreator(picasso, URI_1, 0).into(mockImageViewTarget()); fail("Should have thrown IllegalStateException"); } catch (IllegalStateException ignored) { } finally { latch.countDown(); } } }).start(); latch.await(); } @Test public void intoImageViewAndNotInCacheSubmitsImageViewRequest() throws Exception { ImageView target = mockImageViewTarget(); new RequestCreator(picasso, URI_1, 0).into(target); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class); } @Test public void intoImageViewWithFitAndNoDimensionsQueuesDeferredImageViewRequest() throws Exception { ImageView target = mockFitImageViewTarget(true); when(target.getWidth()).thenReturn(0); when(target.getHeight()).thenReturn(0); new RequestCreator(picasso, URI_1, 0).fit().into(target); verify(picasso, never()).enqueueAndSubmit(any(Action.class)); verify(picasso).defer(eq(target), any(DeferredRequestCreator.class)); } @Test public void intoImageViewWithFitAndDimensionsQueuesImageViewRequest() throws Exception { ImageView target = mockFitImageViewTarget(true); when(target.getMeasuredWidth()).thenReturn(100); when(target.getMeasuredHeight()).thenReturn(100); new RequestCreator(picasso, URI_1, 0).fit().into(target); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class); } @Test public void intoImageViewAndSkipMemoryCacheDoesNotCheckMemoryCache() throws Exception { ImageView target = mockImageViewTarget(); new RequestCreator(picasso, URI_1, 0).skipMemoryCache().into(target); verify(picasso, never()).quickMemoryCacheCheck(URI_KEY_1); } @Test public void intoImageViewWithFitAndResizeThrows() throws Exception { try { ImageView target = mockImageViewTarget(); new RequestCreator(picasso, URI_1, 0).fit().resize(10, 10).into(target); fail("Calling into() ImageView with fit() and resize() should throw exception"); } catch (IllegalStateException expected) { } } @Test public void intoRemoteViewsWidgetQueuesAppWidgetAction() throws Exception { new RequestCreator(picasso, URI_1, 0).into(mockRemoteViews(), 0, new int[] { 1, 2, 3 }); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(AppWidgetAction.class); } @Test public void intoRemoteViewsNotificationQueuesNotificationAction() throws Exception { new RequestCreator(picasso, URI_1, 0).into(mockRemoteViews(), 0, 0, mockNotification()); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(NotificationAction.class); } @Test public void intoRemoteViewsNotificationWithNullRemoteViewsThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).into(null, 0, 0, mockNotification()); fail("Calling into() with null RemoteViews should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsWidgetWithPlaceholderDrawableThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).placeholder(new ColorDrawable(0)) .into(mockRemoteViews(), 0, new int[] { 1, 2, 3 }); fail("Calling into() with placeholder drawable should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsWidgetWithErrorDrawableThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).error(new ColorDrawable(0)) .into(mockRemoteViews(), 0, new int[] { 1, 2, 3 }); fail("Calling into() with error drawable should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsNotificationWithPlaceholderDrawableThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).placeholder(new ColorDrawable(0)) .into(mockRemoteViews(), 0, 0, mockNotification()); fail("Calling into() with error drawable should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsNotificationWithErrorDrawableThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).error(new ColorDrawable(0)) .into(mockRemoteViews(), 0, 0, mockNotification()); fail("Calling into() with error drawable should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsWidgetWithNullRemoteViewsThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).into(null, 0, new int[] { 1, 2, 3 }); fail("Calling into() with null RemoteViews should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsWidgetWithNullAppWidgetIdsThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).into(mockRemoteViews(), 0, null); fail("Calling into() with null appWidgetIds should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsNotificationWithNullNotificationThrows() throws Exception { try { new RequestCreator(picasso, URI_1, 0).into(mockRemoteViews(), 0, 0, null); fail("Calling into() with null Notification should throw exception"); } catch (IllegalArgumentException expected) { } } @Test public void intoRemoteViewsWidgetWithFitThrows() throws Exception { try { RemoteViews remoteViews = mockRemoteViews(); new RequestCreator(picasso, URI_1, 0).fit().into(remoteViews, 1, new int[] { 1, 2, 3 }); fail("Calling fit() into remote views should throw exception"); } catch (IllegalStateException expected) { } } @Test public void intoRemoteViewsNotificationWithFitThrows() throws Exception { try { RemoteViews remoteViews = mockRemoteViews(); new RequestCreator(picasso, URI_1, 0).fit().into(remoteViews, 1, 1, mockNotification()); fail("Calling fit() into remote views should throw exception"); } catch (IllegalStateException expected) { } } @Test public void invalidResize() throws Exception { try { new RequestCreator().resize(-1, 10); fail("Negative width should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().resize(10, -1); fail("Negative height should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().resize(0, 10); fail("Zero width should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().resize(10, 0); fail("Zero height should throw exception."); } catch (IllegalArgumentException expected) { } } @Test public void invalidCenterCrop() throws Exception { try { new RequestCreator().resize(10, 10).centerInside().centerCrop(); fail("Calling center crop after center inside should throw exception."); } catch (IllegalStateException expected) { } } @Test public void invalidCenterInside() throws Exception { try { new RequestCreator().resize(10, 10).centerInside().centerCrop(); fail("Calling center inside after center crop should throw exception."); } catch (IllegalStateException expected) { } } @Test public void invalidPlaceholderImage() throws Exception { try { new RequestCreator().placeholder(0); fail("Resource ID of zero should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().placeholder(1).placeholder(new ColorDrawable(0)); fail("Two placeholders should throw exception."); } catch (IllegalStateException expected) { } try { new RequestCreator().placeholder(new ColorDrawable(0)).placeholder(1); fail("Two placeholders should throw exception."); } catch (IllegalStateException expected) { } } @Test public void invalidErrorImage() throws Exception { try { new RequestCreator().error(0); fail("Resource ID of zero should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().error(null); fail("Null drawable should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().error(1).error(new ColorDrawable(0)); fail("Two placeholders should throw exception."); } catch (IllegalStateException expected) { } try { new RequestCreator().error(new ColorDrawable(0)).error(1); fail("Two placeholders should throw exception."); } catch (IllegalStateException expected) { } } @Test(expected = IllegalArgumentException.class) public void nullTransformationsInvalid() throws Exception { new RequestCreator().transform(null); } @Test public void nullTargetsInvalid() throws Exception { try { new RequestCreator().into((ImageView) null); fail("Null ImageView should throw exception."); } catch (IllegalArgumentException expected) { } try { new RequestCreator().into((Target) null); fail("Null Target should throw exception."); } catch (IllegalArgumentException expected) { } } }
/** * textureMain.java * * Main class for texture assignment. * * Students should not be modifying this file. */ import java.awt.*; import java.nio.*; import java.io.*; import java.awt.event.*; import javax.media.opengl.*; import javax.media.opengl.awt.GLCanvas; import javax.media.opengl.fixedfunc.*; import com.jogamp.opengl.util.texture.*; public class textureMain implements GLEventListener, KeyListener { /** * buffer info */ private int vbuffer[]; private int ebuffer[]; private int numVerts[]; /** * program and variable IDs */ public int shaderProgID; // texture values public textureParams tex; /** * shape info */ cgShape myShape; /** * my canvas */ GLCanvas myCanvas; /** * constructor */ public textureMain(GLCanvas G) { vbuffer = new int [1]; ebuffer = new int[1]; numVerts = new int [1]; myCanvas = G; tex = new textureParams(); G.addGLEventListener (this); G.addKeyListener (this); } private void errorCheck (GL2 gl2) { int code = gl2.glGetError(); if (code == GL.GL_NO_ERROR) System.err.println ("All is well"); else System.err.println ("Problem - error code : " + code); } /** * Called by the drawable to initiate OpenGL rendering by the client. */ public void display(GLAutoDrawable drawable) { // get GL GL2 gl2 = (drawable.getGL()).getGL2(); // clear your frame buffers gl2.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT ); // bind your vertex buffer gl2.glBindBuffer ( GL.GL_ARRAY_BUFFER, vbuffer[0]); // bind your element array buffer gl2.glBindBuffer ( GL.GL_ELEMENT_ARRAY_BUFFER, ebuffer[0]); // set up your attribute variables gl2.glUseProgram (shaderProgID); long dataSize = myShape.getNVerts() * 4l * 4l; int vPosition = gl2.glGetAttribLocation (shaderProgID, "vPosition"); gl2.glEnableVertexAttribArray ( vPosition ); gl2.glVertexAttribPointer (vPosition, 4, GL.GL_FLOAT, false, 0, 0l); int vTex = gl2.glGetAttribLocation (shaderProgID, "vTexCoord"); gl2.glEnableVertexAttribArray ( vTex ); gl2.glVertexAttribPointer (vTex, 2, GL.GL_FLOAT, false, 0, dataSize); // setup uniform variables for texture tex.setUpTextures (shaderProgID, gl2); // draw your shapes gl2.glDrawElements ( GL.GL_TRIANGLES, numVerts[0], GL.GL_UNSIGNED_SHORT, 0l); } /** * Notifies the listener to perform the release of all OpenGL * resources per GLContext, such as memory buffers and GLSL * programs. */ public void dispose(GLAutoDrawable drawable) { } /** * Called by the drawable immediately after the OpenGL context is * initialized. */ public void init(GLAutoDrawable drawable) { // get the gl object GL2 gl2 = drawable.getGL().getGL2(); // Load shaders shaderSetup myShaders = new shaderSetup(); shaderProgID = myShaders.readAndCompile (gl2, "vshader.glsl", "fshader.glsl"); if (shaderProgID == 0) { System.err.println ( myShaders.errorString(myShaders.shaderErrorCode) ); System.exit (1); } // Other GL initialization gl2.glEnable (GL.GL_DEPTH_TEST); gl2.glEnable (GL.GL_CULL_FACE); gl2.glCullFace ( GL.GL_BACK ); gl2.glFrontFace(GL.GL_CCW); gl2.glClearColor (1.0f, 1.0f, 1.0f, 1.0f); gl2.glDepthFunc (GL.GL_LEQUAL); gl2.glClearDepth (1.0f); // initially create a new Shape createShapes(gl2); // Load textures tex.loadTexture ("texture.jpg"); } /** * Called by the drawable during the first repaint after the component * has been resized. */ public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } /** * creates a new shape */ public void createShapes(GL2 gl2) { // clear the old shape myShape = new cgShape(); // clear the old shape myShape.clear(); // make a shape myShape.makeDefaultShape(); // get your vertices and elements Buffer points = myShape.getVertices(); Buffer elements = myShape.getElements(); Buffer texCoords = myShape.getUV(); // set up the vertex buffer int bf[] = new int[1]; gl2.glGenBuffers (1, bf, 0); vbuffer[0] = bf[0]; long vertBsize = myShape.getNVerts() * 4l * 4l; long tdataSize = myShape.getNVerts() * 2l * 4l; gl2.glBindBuffer ( GL.GL_ARRAY_BUFFER, vbuffer[0]); gl2.glBufferData ( GL.GL_ARRAY_BUFFER, vertBsize + tdataSize, null, GL.GL_STATIC_DRAW); gl2.glBufferSubData ( GL.GL_ARRAY_BUFFER, 0, vertBsize, points); gl2.glBufferSubData ( GL.GL_ARRAY_BUFFER, vertBsize, tdataSize, texCoords); gl2.glGenBuffers (1, bf, 0); ebuffer[0] = bf[0]; long eBuffSize = myShape.getNVerts() * 2l; gl2.glBindBuffer ( GL.GL_ELEMENT_ARRAY_BUFFER, ebuffer[0]); gl2.glBufferData ( GL.GL_ELEMENT_ARRAY_BUFFER, eBuffSize,elements, GL.GL_STATIC_DRAW); numVerts[0] = myShape.getNVerts(); } /** * Because I am a Key Listener...we'll only respond to key presses */ public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} /** * Invoked when a key has been pressed. */ public void keyPressed(KeyEvent e) { // Get the key that was pressed char key = e.getKeyChar(); // Respond appropriately switch( key ) { case 'q': case 'Q': System.exit( 0 ); break; } // do a redraw myCanvas.display(); } /** * main program */ public static void main(String [] args) { // GL setup GLProfile glp = GLProfile.getDefault(); GLCapabilities caps = new GLCapabilities(glp); GLCanvas canvas = new GLCanvas(caps); // create your tessMain textureMain myMain = new textureMain(canvas); Frame frame = new Frame("CG - Texture Assignment"); frame.setSize(512, 512); frame.add(canvas); frame.setVisible(true); // by default, an AWT Frame doesn't do anything when you click // the close button; this bit of code will terminate the program when // the window is asked to close frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
package share.manager.stock; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import share.manager.connection.ConnectionThread; import share.manager.utils.CompanyGraphicsBuilder; import share.manager.utils.RESTFunction; import share.manager.utils.ShareUtils; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class CompanyActivity extends Activity implements OnSharedPreferenceChangeListener { private ShareManager app; private ProgressDialog progDiag; private String name, tick, region; private SharedPreferences prefs; private RESTFunction currentFunc; private float monthlyHigh, monthlyLow, highestOpen, lowestOpen, highestClose, lowestClose; @SuppressLint("HandlerLeak") @SuppressWarnings("unchecked") private Handler threadConnectionHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (currentFunc) { case GET_COMPANY_RANGE_STOCK: createGraph((ArrayList<String>) msg.obj); getQuota(); break; case GET_COMPANY_STOCK: handleQuota((ArrayList<String>) msg.obj); progDiag.dismiss(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_company); String info = getIntent().getStringExtra("Tick"); String[] splitUp = info.split("\\|"); this.name = splitUp[0]; this.tick = splitUp[1]; this.region = splitUp[2]; setTitle(this.name); TextView regionText = (TextView) findViewById(R.id.region_company_text); regionText.setText("Financial region: " + this.region); prefs = PreferenceManager.getDefaultSharedPreferences(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) getActionBar() .setDisplayHomeAsUpEnabled(true); app = (ShareManager) getApplicationContext(); initCompany(); } private void initCompany() { progDiag = ProgressDialog.show(CompanyActivity.this, "", "Loading, please wait!", true); ((TextView) findViewById(R.id.last_days_label)).setText("Last " + app.getDays() + " days"); int daysToBacktrack = app.getDays() * -1; Calendar backtrack = Calendar.getInstance(); backtrack.add(Calendar.DATE, daysToBacktrack); Calendar current = Calendar.getInstance(); currentFunc = RESTFunction.GET_COMPANY_RANGE_STOCK; ConnectionThread dataThread = new ConnectionThread(app.yahooChart + ShareUtils.createChartLink(backtrack.get(Calendar.MONTH), backtrack.get(Calendar.DAY_OF_MONTH), backtrack.get(Calendar.YEAR), current.get(Calendar.MONTH), current.get(Calendar.DAY_OF_MONTH), current.get(Calendar.YEAR), app.getPeriodicity(), this.tick), threadConnectionHandler, this, RESTFunction.NONE); dataThread.start(); } private void createGraph(ArrayList<String> received) { ArrayList<String> dates = new ArrayList<String>(); ArrayList<Float> values = new ArrayList<Float>(), highs = new ArrayList<Float>(), lows = new ArrayList<Float>(), closes = new ArrayList<Float>(), opens = new ArrayList<Float>(); for (int i = 1; i < received.size(); i++) { String[] split = received.get(i).split(","); String close = split[4]; highs.add(Float.parseFloat(split[2].equals("N/A") ? "0.0" : split[2])); lows.add(Float.parseFloat(split[3].equals("N/A") ? "0.0" : split[3])); closes.add(Float.parseFloat(split[4].equals("N/A") ? "0.0" : split[4])); opens.add(Float.parseFloat(split[1].equals("N/A") ? "0.0" : split[1])); dates.add(split[0].split("-")[2] + "/" + split[0].split("-")[1]); values.add(Float.parseFloat(close)); } Collections.sort(highs); Collections.sort(lows); Collections.sort(closes); Collections.sort(opens); monthlyHigh = highs.get(highs.size() - 1); monthlyLow = lows.get(lows.size() - 1); highestOpen = opens.get(opens.size() - 1); lowestOpen = opens.get(0); highestClose = closes.get(closes.size() - 1); lowestClose = closes.get(0); new CompanyGraphicsBuilder(CompanyActivity.this, values, dates, null); } private void getQuota() { String link = app.yahooQuote + this.tick; currentFunc = RESTFunction.GET_COMPANY_STOCK; ConnectionThread dataThread = new ConnectionThread(link, threadConnectionHandler, CompanyActivity.this, currentFunc); dataThread.start(); } private void handleQuota(ArrayList<String> received) { String[] split = received.get(0).split(","); ((TextView) findViewById(R.id.today_high_value)).setText(split[8] .equals("N/A") ? "-" : split[8] + " $"); ((TextView) findViewById(R.id.today_low_value)).setText(split[7] .equals("N/A") ? "-" : split[7] + " $"); ((TextView) findViewById(R.id.today_open_value)).setText(split[5] .equals("N/A") ? "-" : split[5] + " $"); ((TextView) findViewById(R.id.today_close_value)).setText(split[6] .equals("N/A") ? "-" : split[6] + " $"); ((TextView) findViewById(R.id.today_volume_value)).setText(split[9] .equals("N/A") ? "-" : split[9]); ((TextView) findViewById(R.id.today_current_value)).setText(split[1] .equals("N/A") ? "-" : split[1] + " $"); ((TextView) findViewById(R.id.today_current_date_value)).setText(split[2] .replace("\"", "")); ((TextView) findViewById(R.id.last_days_highest_value)).setText(String .format("%.2f", monthlyHigh) + " $"); ((TextView) findViewById(R.id.last_days_lowest_value)).setText(String .format("%.2f", monthlyLow) + " $"); ((TextView) findViewById(R.id.last_days_highest_open_value)).setText(String .format("%.2f", highestOpen) + " $"); ((TextView) findViewById(R.id.last_days_highest_close_value)) .setText(String.format("%.2f", highestClose) + " $"); ((TextView) findViewById(R.id.last_days_lowest_open_value)).setText(String .format("%.2f", lowestOpen) + " $"); ((TextView) findViewById(R.id.last_days_lowest_close_value)).setText(String .format("%.2f", lowestClose) + " $"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.company, menu); return true; } // Response to the Up button in the action bar @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_settings: Intent intent = new Intent(CompanyActivity.this, SettingsActivity.class); startActivity(intent); app.setAccessedSettings(true); prefs.registerOnSharedPreferenceChangeListener(this); return true; } return super.onOptionsItemSelected(item); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equals(app.KEY_PREF_PERIODICITY)) app.setPeriodicity(prefs .getString(key, "d").charAt(0)); else if (key.equals(app.KEY_PREF_DAYS)) app.setDays(Integer.parseInt(prefs .getString(key, "30"))); else if (key.equals(app.KEY_PREF_CURRENCY)) app.setCurrency(prefs .getString(key, "usd")); } }
/* * (C) Copyright 2017-2020 OpenVidu (https://openvidu.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.openvidu.java.client; import com.google.gson.JsonObject; /** * See {@link io.openvidu.java.client.OpenVidu#createSession(SessionProperties)} */ public class SessionProperties { private MediaMode mediaMode; private RecordingMode recordingMode; private RecordingProperties defaultRecordingProperties; private String customSessionId; private String mediaNode; private VideoCodec forcedVideoCodec; private VideoCodec forcedVideoCodecResolved; private Boolean allowTranscoding; /** * Builder for {@link io.openvidu.java.client.SessionProperties} */ public static class Builder { private MediaMode mediaMode = MediaMode.ROUTED; private RecordingMode recordingMode = RecordingMode.MANUAL; private RecordingProperties defaultRecordingProperties = new RecordingProperties.Builder().build(); private String customSessionId = ""; private String mediaNode; private VideoCodec forcedVideoCodec = VideoCodec.MEDIA_SERVER_PREFERRED; private VideoCodec forcedVideoCodecResolved = VideoCodec.NONE; private Boolean allowTranscoding = false; /** * Returns the {@link io.openvidu.java.client.SessionProperties} object properly * configured */ public SessionProperties build() { return new SessionProperties(this.mediaMode, this.recordingMode, this.defaultRecordingProperties, this.customSessionId, this.mediaNode, this.forcedVideoCodec, this.forcedVideoCodecResolved, this.allowTranscoding); } /** * Call this method to set how the media streams will be sent and received by * your clients: routed through OpenVidu Media Node * (<code>MediaMode.ROUTED</code>) or attempting direct p2p connections * (<code>MediaMode.RELAYED</code>, <i>not available yet</i>)<br> * Default value is <code>MediaMode.ROUTED</code> */ public SessionProperties.Builder mediaMode(MediaMode mediaMode) { this.mediaMode = mediaMode; return this; } /** * Call this method to set whether the Session will be automatically recorded * ({@link RecordingMode#ALWAYS}) or not ({@link RecordingMode#MANUAL})<br> * Default value is {@link RecordingMode#MANUAL} */ public SessionProperties.Builder recordingMode(RecordingMode recordingMode) { this.recordingMode = recordingMode; return this; } /** * Call this method to set the default recording properties of this session. You * can easily override this value later when starting a * {@link io.openvidu.java.client.Recording} by providing new * {@link RecordingProperties}<br> * Default values defined in {@link RecordingProperties} class. */ public SessionProperties.Builder defaultRecordingProperties(RecordingProperties defaultRecordingProperties) { this.defaultRecordingProperties = defaultRecordingProperties; return this; } /** * Call this method to fix the sessionId that will be assigned to the session. * You can take advantage of this property to facilitate the mapping between * OpenVidu Server 'session' entities and your own 'session' entities. If this * parameter is undefined or an empty string, OpenVidu Server will generate a * random sessionId for you. */ public SessionProperties.Builder customSessionId(String customSessionId) { this.customSessionId = customSessionId; return this; } /** * <a href="https://docs.openvidu.io/en/stable/openvidu-pro/" * style="display: inline-block; background-color: rgb(0, 136, 170); color: * white; font-weight: bold; padding: 0px 5px; margin-right: 5px; border-radius: * 3px; font-size: 13px; line-height:21px; font-family: Montserrat, * sans-serif">PRO</a> Call this method to force the session to be hosted in the * Media Node with identifier <code>mediaNodeId</code> */ public SessionProperties.Builder mediaNode(String mediaNodeId) { this.mediaNode = mediaNodeId; return this; } /** * Define which video codec will be forcibly used for this session. * This forces all browsers/clients to use the same codec, which would * avoid transcoding in the media server (Kurento only). If * <code>forcedVideoCodec</code> is set to NONE, no codec will be forced. * * If the browser/client is not compatible with the specified codec, and * {@link #allowTranscoding(Boolean)} is <code>false</code>, an * exception will occur. * * If defined here, this parameter has prevalence over * OPENVIDU_STREAMS_FORCED_VIDEO_CODEC. * * Default is {@link VideoCodec#MEDIA_SERVER_PREFERRED}. */ public SessionProperties.Builder forcedVideoCodec(VideoCodec forcedVideoCodec) { this.forcedVideoCodec = forcedVideoCodec; return this; } /** * Actual video codec that will be forcibly used for this session. * This is the same as <code>forcedVideoCodec</code>, except when its * value is {@link VideoCodec#MEDIA_SERVER_PREFERRED}: in that case, * OpenVidu Server will fill this property with a resolved value, * depending on what is the configured media server. */ public SessionProperties.Builder forcedVideoCodecResolved(VideoCodec forcedVideoCodec) { this.forcedVideoCodecResolved = forcedVideoCodec; return this; } /** * Call this method to define if you want to allow transcoding in the media * server or not when {@link #forcedVideoCodec(VideoCodec)} is not compatible * with the browser/client.<br> * If defined here, this parameter has prevalence over * OPENVIDU_STREAMS_ALLOW_TRANSCODING. OPENVIDU_STREAMS_ALLOW_TRANSCODING * default is 'false' */ public SessionProperties.Builder allowTranscoding(Boolean allowTranscoding) { this.allowTranscoding = allowTranscoding; return this; } } protected SessionProperties() { this.mediaMode = MediaMode.ROUTED; this.recordingMode = RecordingMode.MANUAL; this.defaultRecordingProperties = new RecordingProperties.Builder().build(); this.customSessionId = ""; this.mediaNode = ""; } private SessionProperties(MediaMode mediaMode, RecordingMode recordingMode, RecordingProperties defaultRecordingProperties, String customSessionId, String mediaNode, VideoCodec forcedVideoCodec, VideoCodec forcedVideoCodecResolved, Boolean allowTranscoding) { this.mediaMode = mediaMode; this.recordingMode = recordingMode; this.defaultRecordingProperties = defaultRecordingProperties; this.customSessionId = customSessionId; this.mediaNode = mediaNode; this.forcedVideoCodec = forcedVideoCodec; this.forcedVideoCodecResolved = forcedVideoCodecResolved; this.allowTranscoding = allowTranscoding; } /** * Defines how the media streams will be sent and received by your clients: * routed through OpenVidu Media Node (<code>MediaMode.ROUTED</code>) or * attempting direct p2p connections (<code>MediaMode.RELAYED</code>, <i>not * available yet</i>) */ public MediaMode mediaMode() { return this.mediaMode; } /** * Defines whether the Session will be automatically recorded * ({@link RecordingMode#ALWAYS}) or not ({@link RecordingMode#MANUAL}) */ public RecordingMode recordingMode() { return this.recordingMode; } /** * Defines the default recording properties of this session. You can easily * override this value later when starting a * {@link io.openvidu.java.client.Recording} by providing new * {@link RecordingProperties} */ public RecordingProperties defaultRecordingProperties() { return this.defaultRecordingProperties; } /** * Fixes the value of the sessionId property of the Session. You can take * advantage of this property to facilitate the mapping between OpenVidu Server * 'session' entities and your own 'session' entities. If this parameter is * undefined or an empty string, OpenVidu Server will generate a random * sessionId for you. */ public String customSessionId() { return this.customSessionId; } /** * <a href="https://docs.openvidu.io/en/stable/openvidu-pro/" * style="display: inline-block; background-color: rgb(0, 136, 170); color: * white; font-weight: bold; padding: 0px 5px; margin-right: 5px; border-radius: * 3px; font-size: 13px; line-height:21px; font-family: Montserrat, * sans-serif">PRO</a> The Media Node where to host the session. The default * option if this property is not defined is the less loaded Media Node at the * moment the first user joins the session. */ public String mediaNode() { return this.mediaNode; } /** * Defines which video codec is being forced to be used in the browser/client. * This is the raw value that was configured. It might get resolved into a * different one for actual usage in the server. */ public VideoCodec forcedVideoCodec() { return this.forcedVideoCodec; } /** * Defines which video codec is being forced to be used in the browser/client. * This is the resolved value, for actual usage in the server. * * @hidden */ public VideoCodec forcedVideoCodecResolved() { return this.forcedVideoCodecResolved; } /** * Defines if transcoding is allowed or not when {@link #forcedVideoCodec} is * not a compatible codec with the browser/client. */ public Boolean isTranscodingAllowed() { return this.allowTranscoding; } public JsonObject toJson() { JsonObject json = new JsonObject(); json.addProperty("mediaMode", this.mediaMode.name()); json.addProperty("recordingMode", this.recordingMode.name()); json.add("defaultRecordingProperties", this.defaultRecordingProperties.toJson()); json.addProperty("customSessionId", this.customSessionId); if (this.mediaNode != null && !this.mediaNode.isEmpty()) { JsonObject mediaNodeJson = new JsonObject(); mediaNodeJson.addProperty("id", this.mediaNode); json.add("mediaNode", mediaNodeJson); } if (this.forcedVideoCodec != null) { json.addProperty("forcedVideoCodec", this.forcedVideoCodec.name()); } if (this.forcedVideoCodecResolved != null) { json.addProperty("forcedVideoCodecResolved", this.forcedVideoCodecResolved.name()); } if (this.allowTranscoding != null) { json.addProperty("allowTranscoding", this.allowTranscoding); } return json; } }
/** * */ package org.openflow.example; import java.io.IOException; import java.net.InetAddress; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.openflow.example.cli.Options; import org.openflow.example.cli.ParseException; import org.openflow.example.cli.SimpleCLI; import org.openflow.io.OFMessageAsyncStream; import org.openflow.protocol.OFEchoReply; import org.openflow.protocol.OFHello; import org.openflow.protocol.hello.OFHelloElement; import org.openflow.protocol.hello.OFHelloElementVersionBitmap; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFStatisticsRequest; import org.openflow.protocol.OFStatisticsReply; import org.openflow.protocol.OFFeaturesReply; import org.openflow.protocol.statistics.OFStatisticsType; import org.openflow.protocol.OFError; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFOXMFieldType; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFType; import org.openflow.protocol.instruction.OFInstruction; import org.openflow.protocol.instruction.OFInstructionApplyActions; import org.openflow.protocol.action.OFAction; import org.openflow.protocol.action.OFActionOutput; import org.openflow.protocol.factory.BasicFactory; import org.openflow.util.LRULinkedHashMap; import org.openflow.util.U16; /** * @author Rob Sherwood (rob.sherwood@stanford.edu), David Erickson (daviderickson@cs.stanford.edu) * @author Srini Seetharaman (srini.seetharaman@gmail.com) * */ public class SimpleController implements SelectListener { protected ExecutorService es; protected BasicFactory factory; protected SelectLoop listenSelectLoop; protected ServerSocketChannel listenSock; protected List<SelectLoop> switchSelectLoops; protected Map<SocketChannel,OFSwitch> switchSockets; protected Integer threadCount; protected int port; protected class OFSwitch { protected SocketChannel sock; protected OFMessageAsyncStream stream; protected Map<Integer, Integer> macTable = new LRULinkedHashMap<Integer, Integer>(64001, 64000); public OFSwitch(SocketChannel sock, OFMessageAsyncStream stream) { this.sock = sock; this.stream = stream; } public void handlePacketIn(OFPacketIn pi) { // Build the Match int inPort = pi.getInPort(); OFMatch match = OFMatch.load(pi.getPacketData(), inPort); byte[] dlDst = (byte[]) match.getMatchFieldValue(OFOXMFieldType.ETH_DST); Integer dlDstKey = Arrays.hashCode(dlDst); byte[] dlSrc = (byte[]) match.getMatchFieldValue(OFOXMFieldType.ETH_SRC); Integer dlSrcKey = Arrays.hashCode(dlSrc); int bufferId = pi.getBufferId(); Integer outPort = null; OFSwitch sw = switchSockets.get(sock); if (dlSrc != null && dlDst != null) { // if the src is not multicast, learn it if ((dlSrc[0] & 0x1) == 0) { if (!macTable.containsKey(dlSrcKey) || !macTable.get(dlSrcKey).equals(inPort)) { macTable.put(dlSrcKey, inPort); } } // if the destination is not multicast, look it up if ((dlDst[0] & 0x1) == 0) { outPort = macTable.get(dlDstKey); } } else { System.err.println("MAC address not reported in the match struct within the packet_in"); } // push a flow mod if we know where the packet should be going if (outPort != null) { OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); fm.setBufferId(bufferId); fm.setCommand(OFFlowMod.OFPFC_ADD); fm.setCookie(0); fm.setFlags((short) 0); fm.setHardTimeout((short) 0); fm.setIdleTimeout((short) 5); fm.setMatch(match); OFActionOutput action = new OFActionOutput(); action.setMaxLength((short) 0); action.setPort(outPort); List<OFAction> actions = new ArrayList<OFAction>(); actions.add(action); List<OFInstruction> instructions = new ArrayList<OFInstruction>(); OFInstructionApplyActions instruction = new OFInstructionApplyActions(actions); instructions.add(instruction); fm.setInstructions(instructions); try { stream.write(fm); System.err.println("Send FLOW_MOD to " + sw); System.err.println("--> Rule:" + fm); } catch (IOException e) { e.printStackTrace(); } } // Send a packet out if (outPort == null || pi.getBufferId() == 0xffffffff) { OFPacketOut po = new OFPacketOut(); po.setBufferId(bufferId); po.setInPort(pi.getInPort()); // set actions OFActionOutput action = new OFActionOutput(); action.setMaxLength((short) 0); action.setPort((short) ((outPort == null) ? OFPort.OFPP_FLOOD .getValue() : outPort)); List<OFAction> actions = new ArrayList<OFAction>(); actions.add(action); po.setActions(actions); po.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH); // set data if needed if (bufferId == 0xffffffff) { byte[] packetData = pi.getPacketData(); po.setLength(U16.t(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + packetData.length)); po.setPacketData(packetData); } else { po.setLength(U16.t(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength())); } try { stream.write(po); } catch (IOException e) { e.printStackTrace(); } } } public String toString() { InetAddress remote = sock.socket().getInetAddress(); return remote.getHostAddress() + ":" + sock.socket().getPort(); } public OFMessageAsyncStream getStream() { return stream; } } public SimpleController(int port) throws IOException{ listenSock = ServerSocketChannel.open(); listenSock.configureBlocking(false); listenSock.socket().bind(new java.net.InetSocketAddress(port)); listenSock.socket().setReuseAddress(true); this.port = port; switchSelectLoops = new ArrayList<SelectLoop>(); switchSockets = new ConcurrentHashMap<SocketChannel,OFSwitch>(); threadCount = 1; listenSelectLoop = new SelectLoop(this); // register this connection for accepting listenSelectLoop.register(listenSock, SelectionKey.OP_ACCEPT, listenSock); this.factory = BasicFactory.getInstance(); } @Override public void handleEvent(SelectionKey key, Object arg) throws IOException { if (arg instanceof ServerSocketChannel) handleListenEvent(key, (ServerSocketChannel)arg); else handleSwitchEvent(key, (SocketChannel) arg); } protected void handleListenEvent(SelectionKey key, ServerSocketChannel ssc) throws IOException { SocketChannel sock = listenSock.accept(); OFMessageAsyncStream stream = new OFMessageAsyncStream(sock, factory); switchSockets.put(sock, new OFSwitch(sock, stream)); System.err.println("Got new connection from " + switchSockets.get(sock)); OFHello hm = (OFHello) factory.getMessage(OFType.HELLO); List<OFHelloElement> helloElements = new ArrayList<OFHelloElement>(); OFHelloElementVersionBitmap hevb = new OFHelloElementVersionBitmap(); List<Integer> bitmaps = new ArrayList<Integer>(); bitmaps.add(0x10); hevb.setBitmaps(bitmaps); helloElements.add(hevb); hm.setHelloElements(helloElements); List<OFMessage> l = new ArrayList<OFMessage>(); l.add(hm); l.add(factory.getMessage(OFType.FEATURES_REQUEST)); stream.write(l); l = new ArrayList<OFMessage>(); OFStatisticsRequest omr = (OFStatisticsRequest) factory.getMessage(OFType.STATS_REQUEST); omr.setStatisticsType(OFStatisticsType.DESC); l.add(omr); omr = (OFStatisticsRequest) factory.getMessage(OFType.STATS_REQUEST); omr.setStatisticsType(OFStatisticsType.PORT_DESC); l.add(omr); // Disabling table request for now because returned result is really big when printed // omr = (OFStatisticsRequest) factory.getMessage(OFType.STATS_REQUEST); // omr.setStatisticsType(OFStatisticsType.TABLE_FEATURES); // l.add(omr); stream.write(l); //Clear all existing rules OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); fm.setCommand(OFFlowMod.OFPFC_DELETE); try { stream.write(fm); } catch (IOException e) { e.printStackTrace(); } //Install default rule required by OF1.3 fm.setCommand(OFFlowMod.OFPFC_ADD); fm.setPriority((short) 0); OFActionOutput action = new OFActionOutput().setPort(OFPort.OFPP_CONTROLLER); fm.setInstructions(Collections.singletonList( (OFInstruction)new OFInstructionApplyActions().setActions( Collections.singletonList((OFAction)action)))); try { stream.write(fm); } catch (IOException e) { e.printStackTrace(); } int ops = SelectionKey.OP_READ; if (stream.needsFlush()) ops |= SelectionKey.OP_WRITE; // hash this switch into a thread SelectLoop sl = switchSelectLoops.get(sock.hashCode() % switchSelectLoops.size()); sl.register(sock, ops, sock); // force select to return and re-enter using the new set of keys sl.wakeup(); } protected void handleSwitchEvent(SelectionKey key, SocketChannel sock) { OFSwitch sw = switchSockets.get(sock); OFMessageAsyncStream stream = sw.getStream(); try { if (key.isReadable()) { List<OFMessage> msgs = stream.read(); if (msgs == null) { key.cancel(); switchSockets.remove(sock); return; } for (OFMessage m : msgs) { switch (m.getType()) { case PACKET_IN: System.err.println("GOT PACKET_IN from " + sw); System.err.println("--> Data:" + ((OFPacketIn) m).toString()); sw.handlePacketIn((OFPacketIn) m); break; case FEATURES_REPLY: System.err.println("GOT FEATURE_REPLY from " + sw); System.err.println("--> Data:" + ((OFFeaturesReply) m).toString()); break; case STATS_REPLY: System.err.println("GOT STATS_REPLY from " + sw); System.err.println("--> Data:" + ((OFStatisticsReply) m).toString()); break; case HELLO: System.err.println("GOT HELLO from " + sw); break; case ERROR: System.err.println("GOT ERROR from " + sw); System.err.println("--> Data:" + ((OFError) m).toString()); break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) stream .getMessageFactory().getMessage( OFType.ECHO_REPLY); reply.setXid(m.getXid()); stream.write(reply); break; default: System.err.println("Unhandled OF message: " + m.getType() + " from " + sock.socket().getInetAddress()); } } } if (key.isWritable()) { stream.flush(); } /** * Only register for interest in R OR W, not both, causes stream * deadlock after some period of time */ if (stream.needsFlush()) key.interestOps(SelectionKey.OP_WRITE); else key.interestOps(SelectionKey.OP_READ); } catch (IOException e) { // if we have an exception, disconnect the switch key.cancel(); switchSockets.remove(sock); } } public void run() throws IOException{ System.err.println("Starting " + this.getClass().getCanonicalName() + " on port " + this.port + " with " + this.threadCount + " threads"); // Static number of threads equal to processor cores es = Executors.newFixedThreadPool(threadCount); // Launch one select loop per threadCount and start running for (int i = 0; i < threadCount; ++i) { final SelectLoop sl = new SelectLoop(this); switchSelectLoops.add(sl); es.execute(new Runnable() { @Override public void run() { try { sl.doLoop(); } catch (IOException e) { e.printStackTrace(); } }} ); } // Start the listen loop listenSelectLoop.doLoop(); } public static void main(String [] args) throws IOException { SimpleCLI cmd = parseArgs(args); int port = Integer.valueOf(cmd.getOptionValue("p")); SimpleController sc = new SimpleController(port); sc.threadCount = Integer.valueOf(cmd.getOptionValue("t")); sc.run(); } public static SimpleCLI parseArgs(String[] args) { Options options = new Options(); options.addOption("h", "help", "print help"); // unused? // options.addOption("n", true, "the number of packets to send"); options.addOption("p", "port", 6633, "the port to listen on"); options.addOption("t", "threads", 1, "the number of threads to run"); try { SimpleCLI cmd = SimpleCLI.parse(options, args); if (cmd.hasOption("h")) { printUsage(options); System.exit(0); } return cmd; } catch (ParseException e) { System.err.println(e); printUsage(options); } System.exit(-1); return null; } public static void printUsage(Options options) { SimpleCLI.printHelp("Usage: " + SimpleController.class.getCanonicalName() + " [options]", options); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.metron.solr.writer; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.metron.common.Constants; import org.apache.metron.common.configuration.IndexingConfigurations; import org.apache.metron.common.configuration.writer.IndexingWriterConfiguration; import org.apache.metron.common.writer.BulkMessage; import org.apache.metron.enrichment.integration.utils.SampleUtil; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.common.SolrInputDocument; import org.json.simple.JSONObject; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mockito; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; public class SolrWriterTest { static class CollectionRequestMatcher implements ArgumentMatcher<QueryRequest> { private String name; public CollectionRequestMatcher(String name) { this.name = name; } @Override public boolean matches(QueryRequest queryRequest) { return name.equals(queryRequest.getParams().get("action")); } @Override public String toString() { return name; } } static class SolrInputDocumentMatcher implements ArgumentMatcher<List<SolrInputDocument>> { List<Map<String, Object>> expectedDocs; public SolrInputDocumentMatcher(List<Map<String, Object>> expectedDocs) { this.expectedDocs = expectedDocs; } @Override public boolean matches(List<SolrInputDocument> docs) { int size = docs.size(); if(size != expectedDocs.size()) { return false; } for(int i = 0; i < size;++i) { SolrInputDocument doc = docs.get(i); Map<String, Object> expectedDoc = expectedDocs.get(i); for(Map.Entry<String, Object> expectedKv : expectedDoc.entrySet()) { if(!expectedKv.getValue().equals(doc.get(expectedKv.getKey()).getValue())) { return false; } } } return true; } @Override public String toString() { return expectedDocs.toString(); } } @Test public void testWriter() throws Exception { IndexingConfigurations configurations = SampleUtil.getSampleIndexingConfigs(); JSONObject message1 = new JSONObject(); message1.put(Constants.GUID, "guid-1"); message1.put(Constants.SENSOR_TYPE, "test"); message1.put("intField", 100); message1.put("doubleField", 100.0); JSONObject message2 = new JSONObject(); message2.put(Constants.GUID, "guid-2"); message2.put(Constants.SENSOR_TYPE, "test"); message2.put("intField", 200); message2.put("doubleField", 200.0); List<BulkMessage<JSONObject>> messages = new ArrayList<>(); messages.add(new BulkMessage<>("message1", message1)); messages.add(new BulkMessage<>("message2", message2)); String collection = "metron"; MetronSolrClient solr = Mockito.mock(MetronSolrClient.class); SolrWriter writer = new SolrWriter().withMetronSolrClient(solr); writer.init(null,new IndexingWriterConfiguration("solr", configurations)); verify(solr, times(1)).setDefaultCollection(collection); collection = "metron2"; Map<String, Object> globalConfig = configurations.getGlobalConfig(); globalConfig.put("solr.collection", collection); configurations.updateGlobalConfig(globalConfig); writer = new SolrWriter().withMetronSolrClient(solr); writer.init(null, new IndexingWriterConfiguration("solr", configurations)); verify(solr, times(1)).setDefaultCollection(collection); writer.write("test", new IndexingWriterConfiguration("solr", configurations), messages); verify(solr, times(1)).add(eq("yaf"), argThat(new SolrInputDocumentMatcher(ImmutableList.of(message1, message2)))); verify(solr, times(1)).commit("yaf" , (boolean)SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.defaultValue.get() , (boolean)SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.defaultValue.get() , (boolean)SolrWriter.SolrProperties.COMMIT_SOFT.defaultValue.get() ); } @Test public void configTest_zookeeperQuorumSpecified() { String expected = "test"; assertEquals(expected, SolrWriter.SolrProperties.ZOOKEEPER_QUORUM.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.ZOOKEEPER_QUORUM.name, expected) , String.class)); } @Test public void configTest_zookeeperQuorumUnpecified() { assertThrows( IllegalArgumentException.class, () -> SolrWriter.SolrProperties.ZOOKEEPER_QUORUM.coerceOrDefaultOrExcept( new HashMap<>(), String.class)); } @Test public void configTest_commitPerBatchSpecified() { Object expected = false; assertEquals(expected, SolrWriter.SolrProperties.COMMIT_PER_BATCH.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_PER_BATCH.name, false) , Boolean.class)); } @Test public void configTest_commitPerBatchUnpecified() { assertEquals(SolrWriter.SolrProperties.COMMIT_PER_BATCH.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_PER_BATCH.coerceOrDefaultOrExcept( new HashMap<>() , Boolean.class)); assertEquals(SolrWriter.SolrProperties.COMMIT_PER_BATCH.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_PER_BATCH.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_PER_BATCH.name, new DummyClass()) , Boolean.class)); } @Test public void configTest_commitSoftSpecified() { Object expected = true; assertEquals(expected, SolrWriter.SolrProperties.COMMIT_SOFT.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_SOFT.name, expected) , Boolean.class)); } @Test public void configTest_commitSoftUnpecified() { assertEquals(SolrWriter.SolrProperties.COMMIT_SOFT.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_SOFT.coerceOrDefaultOrExcept( new HashMap<>() , Boolean.class)); assertEquals(SolrWriter.SolrProperties.COMMIT_SOFT.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_SOFT.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_SOFT.name, new DummyClass()) , Boolean.class)); } @Test public void configTest_commitWaitFlushSpecified() { Object expected = false; assertEquals(expected, SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.name, expected) , Boolean.class)); } @Test public void configTest_commitWaitFlushUnspecified() { assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.coerceOrDefaultOrExcept( new HashMap<>() , Boolean.class)); assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.name, new DummyClass()) , Boolean.class)); } @Test public void configTest_commitWaitSearcherSpecified() { Object expected = false; assertEquals(expected, SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.name, expected) , Boolean.class)); } @Test public void configTest_commitWaitSearcherUnspecified() { assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.coerceOrDefaultOrExcept( new HashMap<>() , Boolean.class)); assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.defaultValue.get(), SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.name, new DummyClass()) , Boolean.class)); } @Test public void configTest_defaultCollectionSpecified() { Object expected = "mycollection"; assertEquals(expected, SolrWriter.SolrProperties.DEFAULT_COLLECTION.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.DEFAULT_COLLECTION.name, expected) , String.class)); } @Test public void configTest_defaultCollectionUnspecified() { assertEquals(SolrWriter.SolrProperties.DEFAULT_COLLECTION.defaultValue.get(), SolrWriter.SolrProperties.DEFAULT_COLLECTION.coerceOrDefaultOrExcept( new HashMap<>() , String.class)); } @Test public void configTest_httpConfigSpecified() { Object expected = new HashMap<String, Object>() {{ put("name", "metron"); }}; assertEquals(expected, SolrWriter.SolrProperties.HTTP_CONFIG.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.HTTP_CONFIG.name, expected) , Map.class)); } @Test public void configTest_httpConfigUnspecified() { assertEquals(SolrWriter.SolrProperties.HTTP_CONFIG.defaultValue.get(), SolrWriter.SolrProperties.HTTP_CONFIG.coerceOrDefaultOrExcept( new HashMap<>() , Map.class)); assertEquals(SolrWriter.SolrProperties.HTTP_CONFIG.defaultValue.get(), SolrWriter.SolrProperties.HTTP_CONFIG.coerceOrDefaultOrExcept( ImmutableMap.of( SolrWriter.SolrProperties.HTTP_CONFIG.name, new DummyClass()) , Map.class)); } public static class DummyClass {} }
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony.gsm; import android.os.AsyncResult; import android.os.Handler; import android.os.Message; import android.os.Registrant; import android.os.RegistrantList; import android.os.SystemProperties; import android.telephony.PhoneNumberUtils; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.util.EventLog; import android.telephony.Rlog; import com.android.internal.telephony.CallStateException; import com.android.internal.telephony.CallTracker; import com.android.internal.telephony.CommandsInterface; import com.android.internal.telephony.Connection; import com.android.internal.telephony.DriverCall; import com.android.internal.telephony.EventLogTags; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.TelephonyProperties; import com.android.internal.telephony.UUSInfo; import com.android.internal.telephony.gsm.CallFailCause; import com.android.internal.telephony.gsm.GSMPhone; import com.android.internal.telephony.gsm.GsmCall; import com.android.internal.telephony.gsm.GsmConnection; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.List; import java.util.ArrayList; /** * {@hide} */ public final class GsmCallTracker extends CallTracker { static final String LOG_TAG = "GsmCallTracker"; private static final boolean REPEAT_POLLING = false; private static final boolean DBG_POLL = false; //***** Constants static final int MAX_CONNECTIONS = 7; // only 7 connections allowed in GSM static final int MAX_CONNECTIONS_PER_CALL = 5; // only 5 connections allowed per call //***** Instance Variables GsmConnection mConnections[] = new GsmConnection[MAX_CONNECTIONS]; RegistrantList mVoiceCallEndedRegistrants = new RegistrantList(); RegistrantList mVoiceCallStartedRegistrants = new RegistrantList(); // connections dropped during last poll ArrayList<GsmConnection> mDroppedDuringPoll = new ArrayList<GsmConnection>(MAX_CONNECTIONS); GsmCall mRingingCall = new GsmCall(this); // A call that is ringing or (call) waiting GsmCall mForegroundCall = new GsmCall(this); GsmCall mBackgroundCall = new GsmCall(this); GsmConnection mPendingMO; boolean mHangupPendingMO; GSMPhone mPhone; boolean mDesiredMute = false; // false = mute off PhoneConstants.State mState = PhoneConstants.State.IDLE; //***** Events //***** Constructors GsmCallTracker (GSMPhone phone) { this.mPhone = phone; mCi = phone.mCi; mCi.registerForCallStateChanged(this, EVENT_CALL_STATE_CHANGE, null); mCi.registerForOn(this, EVENT_RADIO_AVAILABLE, null); mCi.registerForNotAvailable(this, EVENT_RADIO_NOT_AVAILABLE, null); } public void dispose() { //Unregister for all events mCi.unregisterForCallStateChanged(this); mCi.unregisterForOn(this); mCi.unregisterForNotAvailable(this); for(GsmConnection c : mConnections) { try { if(c != null) { hangup(c); // Since by now we are unregistered, we won't notify // PhoneApp that the call is gone. Do that here Rlog.d(LOG_TAG, "dispose: call connnection onDisconnect, cause LOST_SIGNAL"); c.onDisconnect(Connection.DisconnectCause.LOST_SIGNAL); } } catch (CallStateException ex) { Rlog.e(LOG_TAG, "dispose: unexpected error on hangup", ex); } } try { if(mPendingMO != null) { hangup(mPendingMO); Rlog.d(LOG_TAG, "dispose: call mPendingMO.onDsiconnect, cause LOST_SIGNAL"); mPendingMO.onDisconnect(Connection.DisconnectCause.LOST_SIGNAL); } } catch (CallStateException ex) { Rlog.e(LOG_TAG, "dispose: unexpected error on hangup", ex); } clearDisconnected(); } @Override protected void finalize() { Rlog.d(LOG_TAG, "GsmCallTracker finalized"); } //***** Instance Methods //***** Public Methods @Override public void registerForVoiceCallStarted(Handler h, int what, Object obj) { Registrant r = new Registrant(h, what, obj); mVoiceCallStartedRegistrants.add(r); } @Override public void unregisterForVoiceCallStarted(Handler h) { mVoiceCallStartedRegistrants.remove(h); } @Override public void registerForVoiceCallEnded(Handler h, int what, Object obj) { Registrant r = new Registrant(h, what, obj); mVoiceCallEndedRegistrants.add(r); } @Override public void unregisterForVoiceCallEnded(Handler h) { mVoiceCallEndedRegistrants.remove(h); } private void fakeHoldForegroundBeforeDial() { List<Connection> connCopy; // We need to make a copy here, since fakeHoldBeforeDial() // modifies the lists, and we don't want to reverse the order connCopy = (List<Connection>) mForegroundCall.mConnections.clone(); for (int i = 0, s = connCopy.size() ; i < s ; i++) { GsmConnection conn = (GsmConnection)connCopy.get(i); conn.fakeHoldBeforeDial(); } } /** * clirMode is one of the CLIR_ constants */ synchronized Connection dial (String dialString, int clirMode, UUSInfo uusInfo) throws CallStateException { // note that this triggers call state changed notif clearDisconnected(); if (!canDial()) { throw new CallStateException("cannot dial in current state"); } // The new call must be assigned to the foreground call. // That call must be idle, so place anything that's // there on hold if (mForegroundCall.getState() == GsmCall.State.ACTIVE) { // this will probably be done by the radio anyway // but the dial might fail before this happens // and we need to make sure the foreground call is clear // for the newly dialed connection switchWaitingOrHoldingAndActive(); // Fake local state so that // a) foregroundCall is empty for the newly dialed connection // b) hasNonHangupStateChanged remains false in the // next poll, so that we don't clear a failed dialing call fakeHoldForegroundBeforeDial(); } if (mForegroundCall.getState() != GsmCall.State.IDLE) { //we should have failed in !canDial() above before we get here throw new CallStateException("cannot dial in current state"); } mPendingMO = new GsmConnection(mPhone.getContext(), checkForTestEmergencyNumber(dialString), this, mForegroundCall); mHangupPendingMO = false; if (mPendingMO.mAddress == null || mPendingMO.mAddress.length() == 0 || mPendingMO.mAddress.indexOf(PhoneNumberUtils.WILD) >= 0 ) { // Phone number is invalid mPendingMO.mCause = Connection.DisconnectCause.INVALID_NUMBER; // handlePollCalls() will notice this call not present // and will mark it as dropped. pollCallsWhenSafe(); } else { // Always unmute when initiating a new call setMute(false); mCi.dial(mPendingMO.mAddress, clirMode, uusInfo, obtainCompleteMessage()); } updatePhoneState(); mPhone.notifyPreciseCallStateChanged(); return mPendingMO; } Connection dial(String dialString) throws CallStateException { return dial(dialString, CommandsInterface.CLIR_DEFAULT, null); } Connection dial(String dialString, UUSInfo uusInfo) throws CallStateException { return dial(dialString, CommandsInterface.CLIR_DEFAULT, uusInfo); } Connection dial(String dialString, int clirMode) throws CallStateException { return dial(dialString, clirMode, null); } void acceptCall () throws CallStateException { // FIXME if SWITCH fails, should retry with ANSWER // in case the active/holding call disappeared and this // is no longer call waiting if (mRingingCall.getState() == GsmCall.State.INCOMING) { Rlog.i("phone", "acceptCall: incoming..."); // Always unmute when answering a new call setMute(false); mCi.acceptCall(obtainCompleteMessage()); } else if (mRingingCall.getState() == GsmCall.State.WAITING) { setMute(false); switchWaitingOrHoldingAndActive(); } else { throw new CallStateException("phone not ringing"); } } void rejectCall () throws CallStateException { // AT+CHLD=0 means "release held or UDUB" // so if the phone isn't ringing, this could hang up held if (mRingingCall.getState().isRinging()) { mCi.rejectCall(obtainCompleteMessage()); } else { throw new CallStateException("phone not ringing"); } } void switchWaitingOrHoldingAndActive() throws CallStateException { // Should we bother with this check? if (mRingingCall.getState() == GsmCall.State.INCOMING) { throw new CallStateException("cannot be in the incoming state"); } else { mCi.switchWaitingOrHoldingAndActive( obtainCompleteMessage(EVENT_SWITCH_RESULT)); } } void conference() { mCi.conference(obtainCompleteMessage(EVENT_CONFERENCE_RESULT)); } void explicitCallTransfer() { mCi.explicitCallTransfer(obtainCompleteMessage(EVENT_ECT_RESULT)); } void clearDisconnected() { internalClearDisconnected(); updatePhoneState(); mPhone.notifyPreciseCallStateChanged(); } boolean canConference() { return mForegroundCall.getState() == GsmCall.State.ACTIVE && mBackgroundCall.getState() == GsmCall.State.HOLDING && !mBackgroundCall.isFull() && !mForegroundCall.isFull(); } boolean canDial() { boolean ret; int serviceState = mPhone.getServiceState().getState(); String disableCall = SystemProperties.get( TelephonyProperties.PROPERTY_DISABLE_CALL, "false"); ret = (serviceState != ServiceState.STATE_POWER_OFF) && mPendingMO == null && !mRingingCall.isRinging() && !disableCall.equals("true") && (!mForegroundCall.getState().isAlive() || !mBackgroundCall.getState().isAlive()); return ret; } boolean canTransfer() { return (mForegroundCall.getState() == GsmCall.State.ACTIVE || mForegroundCall.getState() == GsmCall.State.ALERTING || mForegroundCall.getState() == GsmCall.State.DIALING) && mBackgroundCall.getState() == GsmCall.State.HOLDING; } //***** Private Instance Methods private void internalClearDisconnected() { mRingingCall.clearDisconnected(); mForegroundCall.clearDisconnected(); mBackgroundCall.clearDisconnected(); } /** * Obtain a message to use for signalling "invoke getCurrentCalls() when * this operation and all other pending operations are complete */ private Message obtainCompleteMessage() { return obtainCompleteMessage(EVENT_OPERATION_COMPLETE); } /** * Obtain a message to use for signalling "invoke getCurrentCalls() when * this operation and all other pending operations are complete */ private Message obtainCompleteMessage(int what) { mPendingOperations++; mLastRelevantPoll = null; mNeedsPoll = true; if (DBG_POLL) log("obtainCompleteMessage: pendingOperations=" + mPendingOperations + ", needsPoll=" + mNeedsPoll); return obtainMessage(what); } private void operationComplete() { mPendingOperations--; if (DBG_POLL) log("operationComplete: pendingOperations=" + mPendingOperations + ", needsPoll=" + mNeedsPoll); if (mPendingOperations == 0 && mNeedsPoll) { mLastRelevantPoll = obtainMessage(EVENT_POLL_CALLS_RESULT); mCi.getCurrentCalls(mLastRelevantPoll); } else if (mPendingOperations < 0) { // this should never happen Rlog.e(LOG_TAG,"GsmCallTracker.pendingOperations < 0"); mPendingOperations = 0; } } private void updatePhoneState() { PhoneConstants.State oldState = mState; if (mRingingCall.isRinging()) { mState = PhoneConstants.State.RINGING; } else if (mPendingMO != null || !(mForegroundCall.isIdle() && mBackgroundCall.isIdle())) { mState = PhoneConstants.State.OFFHOOK; } else { mState = PhoneConstants.State.IDLE; } if (mState == PhoneConstants.State.IDLE && oldState != mState) { mVoiceCallEndedRegistrants.notifyRegistrants( new AsyncResult(null, null, null)); } else if (oldState == PhoneConstants.State.IDLE && oldState != mState) { mVoiceCallStartedRegistrants.notifyRegistrants ( new AsyncResult(null, null, null)); } if (mState != oldState) { mPhone.notifyPhoneStateChanged(); } } @Override protected synchronized void handlePollCalls(AsyncResult ar) { List polledCalls; if (ar.exception == null) { polledCalls = (List)ar.result; } else if (isCommandExceptionRadioNotAvailable(ar.exception)) { // just a dummy empty ArrayList to cause the loop // to hang up all the calls polledCalls = new ArrayList(); } else { // Radio probably wasn't ready--try again in a bit // But don't keep polling if the channel is closed pollCallsAfterDelay(); return; } Connection newRinging = null; //or waiting boolean hasNonHangupStateChanged = false; // Any change besides // a dropped connection boolean hasAnyCallDisconnected = false; boolean needsPollDelay = false; boolean unknownConnectionAppeared = false; for (int i = 0, curDC = 0, dcSize = polledCalls.size() ; i < mConnections.length; i++) { GsmConnection conn = mConnections[i]; DriverCall dc = null; // polledCall list is sparse if (curDC < dcSize) { dc = (DriverCall) polledCalls.get(curDC); if (dc.index == i+1) { curDC++; } else { dc = null; } } if (DBG_POLL) log("poll: conn[i=" + i + "]=" + conn+", dc=" + dc); if (conn == null && dc != null) { // Connection appeared in CLCC response that we don't know about if (mPendingMO != null && mPendingMO.compareTo(dc)) { if (DBG_POLL) log("poll: pendingMO=" + mPendingMO); // It's our pending mobile originating call mConnections[i] = mPendingMO; mPendingMO.mIndex = i; mPendingMO.update(dc); mPendingMO = null; // Someone has already asked to hangup this call if (mHangupPendingMO) { mHangupPendingMO = false; try { if (Phone.DEBUG_PHONE) log( "poll: hangupPendingMO, hangup conn " + i); hangup(mConnections[i]); } catch (CallStateException ex) { Rlog.e(LOG_TAG, "unexpected error on hangup"); } // Do not continue processing this poll // Wait for hangup and repoll return; } } else { mConnections[i] = new GsmConnection(mPhone.getContext(), dc, this, i); // it's a ringing call if (mConnections[i].getCall() == mRingingCall) { newRinging = mConnections[i]; } else { // Something strange happened: a call appeared // which is neither a ringing call or one we created. // Either we've crashed and re-attached to an existing // call, or something else (eg, SIM) initiated the call. Rlog.i(LOG_TAG,"Phantom call appeared " + dc); // If it's a connected call, set the connect time so that // it's non-zero. It may not be accurate, but at least // it won't appear as a Missed Call. if (dc.state != DriverCall.State.ALERTING && dc.state != DriverCall.State.DIALING) { mConnections[i].onConnectedInOrOut(); if (dc.state == DriverCall.State.HOLDING) { // We've transitioned into HOLDING mConnections[i].onStartedHolding(); } } unknownConnectionAppeared = true; } } hasNonHangupStateChanged = true; } else if (conn != null && dc == null) { // Connection missing in CLCC response that we were // tracking. mDroppedDuringPoll.add(conn); // Dropped connections are removed from the CallTracker // list but kept in the GsmCall list mConnections[i] = null; } else if (conn != null && dc != null && !conn.compareTo(dc)) { // Connection in CLCC response does not match what // we were tracking. Assume dropped call and new call mDroppedDuringPoll.add(conn); mConnections[i] = new GsmConnection (mPhone.getContext(), dc, this, i); if (mConnections[i].getCall() == mRingingCall) { newRinging = mConnections[i]; } // else something strange happened hasNonHangupStateChanged = true; } else if (conn != null && dc != null) { /* implicit conn.compareTo(dc) */ boolean changed; changed = conn.update(dc); hasNonHangupStateChanged = hasNonHangupStateChanged || changed; } if (REPEAT_POLLING) { if (dc != null) { // FIXME with RIL, we should not need this anymore if ((dc.state == DriverCall.State.DIALING /*&& cm.getOption(cm.OPTION_POLL_DIALING)*/) || (dc.state == DriverCall.State.ALERTING /*&& cm.getOption(cm.OPTION_POLL_ALERTING)*/) || (dc.state == DriverCall.State.INCOMING /*&& cm.getOption(cm.OPTION_POLL_INCOMING)*/) || (dc.state == DriverCall.State.WAITING /*&& cm.getOption(cm.OPTION_POLL_WAITING)*/) ) { // Sometimes there's no unsolicited notification // for state transitions needsPollDelay = true; } } } } // This is the first poll after an ATD. // We expect the pending call to appear in the list // If it does not, we land here if (mPendingMO != null) { Rlog.d(LOG_TAG,"Pending MO dropped before poll fg state:" + mForegroundCall.getState()); mDroppedDuringPoll.add(mPendingMO); mPendingMO = null; mHangupPendingMO = false; } if (newRinging != null) { mPhone.notifyNewRingingConnection(newRinging); } // clear the "local hangup" and "missed/rejected call" // cases from the "dropped during poll" list // These cases need no "last call fail" reason for (int i = mDroppedDuringPoll.size() - 1; i >= 0 ; i--) { GsmConnection conn = mDroppedDuringPoll.get(i); if (conn.isIncoming() && conn.getConnectTime() == 0) { // Missed or rejected call Connection.DisconnectCause cause; if (conn.mCause == Connection.DisconnectCause.LOCAL) { cause = Connection.DisconnectCause.INCOMING_REJECTED; } else { cause = Connection.DisconnectCause.INCOMING_MISSED; } if (Phone.DEBUG_PHONE) { log("missed/rejected call, conn.cause=" + conn.mCause); log("setting cause to " + cause); } mDroppedDuringPoll.remove(i); hasAnyCallDisconnected |= conn.onDisconnect(cause); } else if (conn.mCause == Connection.DisconnectCause.LOCAL || conn.mCause == Connection.DisconnectCause.INVALID_NUMBER) { mDroppedDuringPoll.remove(i); hasAnyCallDisconnected |= conn.onDisconnect(conn.mCause); } } // Any non-local disconnects: determine cause if (mDroppedDuringPoll.size() > 0) { mCi.getLastCallFailCause( obtainNoPollCompleteMessage(EVENT_GET_LAST_CALL_FAIL_CAUSE)); } if (needsPollDelay) { pollCallsAfterDelay(); } // Cases when we can no longer keep disconnected Connection's // with their previous calls // 1) the phone has started to ring // 2) A Call/Connection object has changed state... // we may have switched or held or answered (but not hung up) if (newRinging != null || hasNonHangupStateChanged || hasAnyCallDisconnected) { internalClearDisconnected(); } updatePhoneState(); if (unknownConnectionAppeared) { mPhone.notifyUnknownConnection(); } if (hasNonHangupStateChanged || newRinging != null || hasAnyCallDisconnected) { mPhone.notifyPreciseCallStateChanged(); } //dumpState(); } private void handleRadioNotAvailable() { // handlePollCalls will clear out its // call list when it gets the CommandException // error result from this pollCallsWhenSafe(); } private void dumpState() { List l; Rlog.i(LOG_TAG,"Phone State:" + mState); Rlog.i(LOG_TAG,"Ringing call: " + mRingingCall.toString()); l = mRingingCall.getConnections(); for (int i = 0, s = l.size(); i < s; i++) { Rlog.i(LOG_TAG,l.get(i).toString()); } Rlog.i(LOG_TAG,"Foreground call: " + mForegroundCall.toString()); l = mForegroundCall.getConnections(); for (int i = 0, s = l.size(); i < s; i++) { Rlog.i(LOG_TAG,l.get(i).toString()); } Rlog.i(LOG_TAG,"Background call: " + mBackgroundCall.toString()); l = mBackgroundCall.getConnections(); for (int i = 0, s = l.size(); i < s; i++) { Rlog.i(LOG_TAG,l.get(i).toString()); } } //***** Called from GsmConnection /*package*/ void hangup (GsmConnection conn) throws CallStateException { if (conn.mOwner != this) { throw new CallStateException ("GsmConnection " + conn + "does not belong to GsmCallTracker " + this); } if (conn == mPendingMO) { // We're hanging up an outgoing call that doesn't have it's // GSM index assigned yet if (Phone.DEBUG_PHONE) log("hangup: set hangupPendingMO to true"); mHangupPendingMO = true; } else { try { mCi.hangupConnection (conn.getGSMIndex(), obtainCompleteMessage()); } catch (CallStateException ex) { // Ignore "connection not found" // Call may have hung up already Rlog.w(LOG_TAG,"GsmCallTracker WARN: hangup() on absent connection " + conn); } } conn.onHangupLocal(); } /*package*/ void separate (GsmConnection conn) throws CallStateException { if (conn.mOwner != this) { throw new CallStateException ("GsmConnection " + conn + "does not belong to GsmCallTracker " + this); } try { mCi.separateConnection (conn.getGSMIndex(), obtainCompleteMessage(EVENT_SEPARATE_RESULT)); } catch (CallStateException ex) { // Ignore "connection not found" // Call may have hung up already Rlog.w(LOG_TAG,"GsmCallTracker WARN: separate() on absent connection " + conn); } } //***** Called from GSMPhone /*package*/ void setMute(boolean mute) { mDesiredMute = mute; mCi.setMute(mDesiredMute, null); } /*package*/ boolean getMute() { return mDesiredMute; } //***** Called from GsmCall /* package */ void hangup (GsmCall call) throws CallStateException { if (call.getConnections().size() == 0) { throw new CallStateException("no connections in call"); } if (call == mRingingCall) { if (Phone.DEBUG_PHONE) log("(ringing) hangup waiting or background"); mCi.hangupWaitingOrBackground(obtainCompleteMessage()); } else if (call == mForegroundCall) { if (call.isDialingOrAlerting()) { if (Phone.DEBUG_PHONE) { log("(foregnd) hangup dialing or alerting..."); } hangup((GsmConnection)(call.getConnections().get(0))); } else { hangupForegroundResumeBackground(); } } else if (call == mBackgroundCall) { if (mRingingCall.isRinging()) { if (Phone.DEBUG_PHONE) { log("hangup all conns in background call"); } hangupAllConnections(call); } else { hangupWaitingOrBackground(); } } else { throw new RuntimeException ("GsmCall " + call + "does not belong to GsmCallTracker " + this); } call.onHangupLocal(); mPhone.notifyPreciseCallStateChanged(); } /* package */ void hangupWaitingOrBackground() { if (Phone.DEBUG_PHONE) log("hangupWaitingOrBackground"); mCi.hangupWaitingOrBackground(obtainCompleteMessage()); } /* package */ void hangupForegroundResumeBackground() { if (Phone.DEBUG_PHONE) log("hangupForegroundResumeBackground"); mCi.hangupForegroundResumeBackground(obtainCompleteMessage()); } void hangupConnectionByIndex(GsmCall call, int index) throws CallStateException { int count = call.mConnections.size(); for (int i = 0; i < count; i++) { GsmConnection cn = (GsmConnection)call.mConnections.get(i); if (cn.getGSMIndex() == index) { mCi.hangupConnection(index, obtainCompleteMessage()); return; } } throw new CallStateException("no gsm index found"); } void hangupAllConnections(GsmCall call) { try { int count = call.mConnections.size(); for (int i = 0; i < count; i++) { GsmConnection cn = (GsmConnection)call.mConnections.get(i); mCi.hangupConnection(cn.getGSMIndex(), obtainCompleteMessage()); } } catch (CallStateException ex) { Rlog.e(LOG_TAG, "hangupConnectionByIndex caught " + ex); } } /* package */ GsmConnection getConnectionByIndex(GsmCall call, int index) throws CallStateException { int count = call.mConnections.size(); for (int i = 0; i < count; i++) { GsmConnection cn = (GsmConnection)call.mConnections.get(i); if (cn.getGSMIndex() == index) { return cn; } } return null; } private Phone.SuppService getFailedService(int what) { switch (what) { case EVENT_SWITCH_RESULT: return Phone.SuppService.SWITCH; case EVENT_CONFERENCE_RESULT: return Phone.SuppService.CONFERENCE; case EVENT_SEPARATE_RESULT: return Phone.SuppService.SEPARATE; case EVENT_ECT_RESULT: return Phone.SuppService.TRANSFER; } return Phone.SuppService.UNKNOWN; } //****** Overridden from Handler @Override public void handleMessage (Message msg) { AsyncResult ar; if (!mPhone.mIsTheCurrentActivePhone) { Rlog.e(LOG_TAG, "Received message " + msg + "[" + msg.what + "] while being destroyed. Ignoring."); return; } switch (msg.what) { case EVENT_POLL_CALLS_RESULT: ar = (AsyncResult)msg.obj; if (msg == mLastRelevantPoll) { if (DBG_POLL) log( "handle EVENT_POLL_CALL_RESULT: set needsPoll=F"); mNeedsPoll = false; mLastRelevantPoll = null; handlePollCalls((AsyncResult)msg.obj); } break; case EVENT_OPERATION_COMPLETE: ar = (AsyncResult)msg.obj; operationComplete(); break; case EVENT_SWITCH_RESULT: case EVENT_CONFERENCE_RESULT: case EVENT_SEPARATE_RESULT: case EVENT_ECT_RESULT: ar = (AsyncResult)msg.obj; if (ar.exception != null) { mPhone.notifySuppServiceFailed(getFailedService(msg.what)); } operationComplete(); break; case EVENT_GET_LAST_CALL_FAIL_CAUSE: int causeCode; ar = (AsyncResult)msg.obj; operationComplete(); if (ar.exception != null) { // An exception occurred...just treat the disconnect // cause as "normal" causeCode = CallFailCause.NORMAL_CLEARING; Rlog.i(LOG_TAG, "Exception during getLastCallFailCause, assuming normal disconnect"); } else { causeCode = ((int[])ar.result)[0]; } // Log the causeCode if its not normal if (causeCode == CallFailCause.NO_CIRCUIT_AVAIL || causeCode == CallFailCause.TEMPORARY_FAILURE || causeCode == CallFailCause.SWITCHING_CONGESTION || causeCode == CallFailCause.CHANNEL_NOT_AVAIL || causeCode == CallFailCause.QOS_NOT_AVAIL || causeCode == CallFailCause.BEARER_NOT_AVAIL || causeCode == CallFailCause.ERROR_UNSPECIFIED) { GsmCellLocation loc = ((GsmCellLocation)mPhone.getCellLocation()); EventLog.writeEvent(EventLogTags.CALL_DROP, causeCode, loc != null ? loc.getCid() : -1, TelephonyManager.getDefault().getNetworkType()); } for (int i = 0, s = mDroppedDuringPoll.size() ; i < s ; i++ ) { GsmConnection conn = mDroppedDuringPoll.get(i); conn.onRemoteDisconnect(causeCode); } updatePhoneState(); mPhone.notifyPreciseCallStateChanged(); mDroppedDuringPoll.clear(); break; case EVENT_REPOLL_AFTER_DELAY: case EVENT_CALL_STATE_CHANGE: pollCallsWhenSafe(); break; case EVENT_RADIO_AVAILABLE: handleRadioAvailable(); break; case EVENT_RADIO_NOT_AVAILABLE: handleRadioNotAvailable(); break; } } @Override protected void log(String msg) { Rlog.d(LOG_TAG, "[GsmCallTracker] " + msg); } @Override public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { pw.println("GsmCallTracker extends:"); super.dump(fd, pw, args); pw.println("mConnections: length=" + mConnections.length); for(int i=0; i < mConnections.length; i++) { pw.printf(" mConnections[%d]=%s\n", i, mConnections[i]); } pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants); pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants); pw.println(" mDroppedDuringPoll: size=" + mDroppedDuringPoll.size()); for(int i = 0; i < mDroppedDuringPoll.size(); i++) { pw.printf( " mDroppedDuringPoll[%d]=%s\n", i, mDroppedDuringPoll.get(i)); } pw.println(" mRingingCall=" + mRingingCall); pw.println(" mForegroundCall=" + mForegroundCall); pw.println(" mBackgroundCall=" + mBackgroundCall); pw.println(" mPendingMO=" + mPendingMO); pw.println(" mHangupPendingMO=" + mHangupPendingMO); pw.println(" mPhone=" + mPhone); pw.println(" mDesiredMute=" + mDesiredMute); pw.println(" mState=" + mState); } }
package nanocad; //package nanocad; //import nanocad.minimize.mm3.mm3MinimizeAlgorythm; import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.lang.*; import java.util.*; import java.awt.geom.*; import java.awt.image.*; public class Indiana1 { // private static textwin saveWin; public static String name,formula,a; public static char g,j,t,special; public static String search_str; public static LinkedList tosend = new LinkedList(); public static int chk; // private static newNanocad newnano; public static void main(String []argv) { if( argv.length < 2 ) { System.err.println( "Insufficient arguments" ); System.exit(-1); } System.err.println("In Java code"); search_str = argv[0]; // get the integer from the argument for( int i = 0; i < argv[1].length(); i++ ) if( Character.isDigit(argv[1].charAt(i)) ) chk = Character.digit(argv[1].charAt(i), 10 ); String query_string="",query_st=""; String atom1Name = null,atom1Num = null; String atom2Name = null,atom2Num = null; String atom3Name = null,atom3Num = null; // newnano.loadpdb("http://pine.ncsa.uiuc.edu/csd/temp/fileFromIndiana"); // System.err.println("chk = " + chk + " search_str = " + search_str); if(chk == 0){ // => we passed a name System.err.print("Hello world: "); query_string ="http://www.iumsc.indiana.edu/db/search.jsp?start=1&compoundName=" + argv[0]+ "&raw=pdb"; System.err.println("chk = " + chk + " query_string= " + query_string); } else if(chk == 1) //=> we passed a Formula { //Parse the formula string into alphabets and numbers // and then generate the query string reqd by Indiana String get = formula(search_str); atom1Name= tosend.get(0).toString(); atom3Name= tosend.get(2).toString(); atom1Num = tosend.get(1).toString(); atom3Num = tosend.get(3).toString(); /* for(int o = 0;o<tosend.size();++o) System.out.println("Hello see the output"+tosend.get(o)); */ int o=0,anothernumber=0; String initialquery = "", combined=""; String must = "http://www.iumsc.indiana.edu/db/search.jsp?start=1"; for(o=0;o<tosend.size();o++){ anothernumber++; initialquery = "&" + "atom"+ anothernumber+"Name"+"="+ tosend.get(o).toString(); o++; String something = "&atom" + anothernumber +"Relation==&atom"+ anothernumber+"Num=" + tosend.get(o).toString(); combined = combined + initialquery + something; } query_string = must + combined + "&raw=pdb"; /* query_string = "http://www.iumsc.indiana.edu/db/search.jsp?start=1&atom1Name=" + atom1Name + "&atom1Relation==atom1Num=" + atom1Num + "&&atom2Name=" + atom2Name + "&atom2Relation==atom2Num=" + atom2Num + "&&atom3Name=" + atom3Name + "&atom3Relation==atom3Num=" + atom3Num + "&raw=pdb"; */ System.err.println( "chk = " + chk + " query_string = " + query_string ); } try { System.err.println("Final value of query_string is "+ query_string); URL url_indiana = new URL(query_string); URLConnection conn_indiana = url_indiana.openConnection(); conn_indiana.connect(); BufferedReader inFile = new BufferedReader (new InputStreamReader(conn_indiana.getInputStream())); String line = null; String final_file=""; int counter = 0; while ((line = inFile.readLine()) !=null) { if(counter <5) counter++; else final_file += line; } /* DataOutputStream fout = new DataOutputStream(new FileOutputStream("fileFromIndiana1.pdb")); fout.writeBytes(query_string); fout.writeBytes(final_file); fout.close(); PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter("file1.pdb"))); fout.print(final_file); fout.close(); */ // newnano = new newNanocad(); // // newnano.loadpdb("http://pine.ncsa.uiuc.edu/csd/temp/fileFromIndiana"); //saveWin = new textwin("TRY THIS", "", false); //saveWin.setVisible(true); //newnano.drawFile(final_file); System.out.println(final_file); }catch(Exception e3) { System.err.println(e3); e3.printStackTrace(); System.err.println("This is the last few lines of the program"); } } public static String formula(String search_str){ int k=0; while(k<search_str.length()){ Character asj; special = search_str.charAt(0); if(Character.isDigit(special)){ System.exit(0); // is there a better aliter to exit here } g = search_str.charAt(k); if(Character.isUpperCase(g)){ asj=new Character(g); tosend.add(asj.toString()); k++; if(k>= search_str.length()){ tosend.add("1"); break ; } j = search_str.charAt(k); if(Character.isUpperCase(j)){ tosend.add("1"); asj = new Character(j); tosend.add(asj.toString()); k++; if(k>= search_str.length()){ tosend.add("1"); break ; } else if(Character.isDigit(t = search_str.charAt(k))){ asj = new Character(t); tosend.add(asj.toString()); k++; } else if(Character.isLowerCase(t = search_str.charAt(k))){ asj = new Character(t); String add = tosend.getLast().toString(); String after = add + asj.toString(); tosend.removeLast(); tosend.addLast(after); k++; if(k>= search_str.length()){ tosend.add("1"); break ; } else if(Character.isDigit(t = search_str.charAt(k))){ asj = new Character(t); tosend.add(asj.toString()); k++; } else tosend.add("1"); } } else if(Character.isDigit(j)){ asj = new Character(j); tosend.add(asj.toString()); // tosend.add("1"); k++; if(k>= search_str.length()){ break ; } } else{ asj = new Character(j); String test = tosend.getLast().toString(); String test1 = test + asj.toString(); tosend.removeLast(); tosend.addLast(test1); k++; if(k>= search_str.length()){ tosend.add("1"); break ; } else if(Character.isDigit(t = search_str.charAt(k))){ asj = new Character(t); tosend.add(asj.toString()); k++; } else tosend.add("1"); } } } String toreturn = null; for(int o = 0;o<tosend.size();++o){ toreturn = toreturn + "|" + tosend.get(o); } System.out.println(toreturn); return toreturn; } }
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.warp.services; import com.google.inject.Inject; import com.google.inject.Singleton; import io.github.nucleuspowered.nucleus.api.module.warp.NucleusWarpService; import io.github.nucleuspowered.nucleus.api.module.warp.data.Warp; import io.github.nucleuspowered.nucleus.api.module.warp.data.WarpCategory; import io.github.nucleuspowered.nucleus.modules.warp.WarpKeys; import io.github.nucleuspowered.nucleus.modules.warp.data.WarpCategoryData; import io.github.nucleuspowered.nucleus.modules.warp.data.WarpData; import io.github.nucleuspowered.nucleus.modules.warp.parameters.WarpCategoryParameter; import io.github.nucleuspowered.nucleus.modules.warp.parameters.WarpParameter; import io.github.nucleuspowered.nucleus.core.scaffold.service.ServiceBase; import io.github.nucleuspowered.nucleus.core.scaffold.service.annotations.APIService; import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection; import io.github.nucleuspowered.nucleus.core.services.impl.storage.dataobjects.modular.IGeneralDataObject; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.command.parameter.Parameter; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.math.vector.Vector3d; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; @Singleton @APIService(NucleusWarpService.class) public class WarpService implements NucleusWarpService, ServiceBase { public static final String WARP_KEY = "warp"; public static final String WARP_CATEGORY_KEY = "warp category"; @Nullable private Map<String, Warp> warpCache = null; @Nullable private Map<String, WarpCategory> warpCategoryCache = null; @Nullable private List<Warp> uncategorised = null; private final Map<String, List<Warp>> categoryCollectionMap = new HashMap<>(); private final INucleusServiceCollection serviceCollection; private final Parameter.Value<Warp> warpPermissionArgument; private final Parameter.Value<Warp> warpNoPermissionArgument; private final Parameter.Value<WarpCategory> warpCategoryParameter; @Inject public WarpService(final INucleusServiceCollection serviceCollection) { this.serviceCollection = serviceCollection; this.warpPermissionArgument = Parameter.builder(Warp.class) .addParser(new WarpParameter( serviceCollection.permissionService(), serviceCollection.messageProvider(), this, true)) .key("warp") .build(); this.warpNoPermissionArgument = Parameter.builder(Warp.class) .addParser(new WarpParameter( serviceCollection.permissionService(), serviceCollection.messageProvider(), this, false)) .key("warp") .build(); this.warpCategoryParameter = Parameter.builder(WarpCategory.class) .key("category") .addParser(new WarpCategoryParameter( serviceCollection, this)) .build(); } private Map<String, Warp> getWarpCache() { if (this.warpCache == null) { this.updateCache(); } return this.warpCache; } private Map<String, WarpCategory> getWarpCategoryCache() { if (this.warpCategoryCache == null) { this.updateCache(); } return this.warpCategoryCache; } private void updateCache() { this.categoryCollectionMap.clear(); this.warpCache = new HashMap<>(); this.warpCategoryCache = new HashMap<>(); this.uncategorised = null; final IGeneralDataObject dataObject = this.serviceCollection .storageManager() .getGeneralService() .getOrNewOnThread(); dataObject.get(WarpKeys.WARP_NODES) .orElseGet(Collections::emptyMap) .forEach((key, value) -> this.warpCache.put(key.toLowerCase(), value)); this.warpCategoryCache.putAll(dataObject.get(WarpKeys.WARP_CATEGORIES) .orElseGet(Collections::emptyMap)); } private void saveFromCache() { if (this.warpCache == null || this.warpCategoryCache == null) { return; // not loaded } final IGeneralDataObject dataObject = this.serviceCollection .storageManager() .getGeneralService() .getOrNewOnThread(); dataObject.set(WarpKeys.WARP_NODES, new HashMap<>(this.warpCache)); dataObject.set(WarpKeys.WARP_CATEGORIES, new HashMap<>(this.warpCategoryCache)); this.serviceCollection.storageManager().getGeneralService().save(dataObject); } public Parameter.Value<Warp> warpElement(final boolean requirePermission) { if (requirePermission) { return this.warpPermissionArgument; } else { return this.warpNoPermissionArgument; } } public Parameter.Value<WarpCategory> warpCategoryElement() { return this.warpCategoryParameter; } @Override public Optional<Warp> getWarp(final String warpName) { return Optional.ofNullable(this.getWarpCache().get(warpName.toLowerCase())); } @Override public boolean removeWarp(final String warpName) { if (this.getWarpCache().remove(warpName.toLowerCase()) != null) { this.saveFromCache(); return true; } return false; } @Override public boolean setWarp(final String warpName, final ServerLocation location, final Vector3d rotation) { final Map<String, Warp> cache = this.getWarpCache(); final String key = warpName.toLowerCase(); if (!cache.containsKey(key)) { cache.put(key, new WarpData( null, 0, null, location.worldKey(), location.position(), rotation, warpName )); this.saveFromCache(); return true; } return false; } @Override public List<Warp> getAllWarps() { return Collections.unmodifiableList(new ArrayList<>(this.getWarpCache().values())); } @Override public List<Warp> getUncategorisedWarps() { if (this.uncategorised == null) { this.uncategorised = this.getAllWarps() .stream() .filter(x -> !x.getCategory().isPresent()) .collect(Collectors.toList()); } return Collections.unmodifiableList(this.uncategorised); } @Override public List<Warp> getWarpsForCategory(final String category) { final List<Warp> warps = this.categoryCollectionMap.computeIfAbsent(category.toLowerCase(), c -> this.getAllWarps().stream().filter(x -> x.getCategory().map(cat -> cat.equalsIgnoreCase(c)).orElse(false)) .collect(Collectors.toList())); return Collections.unmodifiableList(warps); } public Map<WarpCategory, List<Warp>> getWarpsWithCategories() { return this.getWarpsWithCategories(t -> true); } @Override public Map<WarpCategory, List<Warp>> getWarpsWithCategories(final Predicate<Warp> warpDataPredicate) { // Populate cache final Map<WarpCategory, List<Warp>> map = new HashMap<>(); this.getWarpCategoryCache().keySet().forEach(x -> { final List<Warp> warps = this.getWarpsForCategory(x).stream().filter(warpDataPredicate).collect(Collectors.toList()); if (!warps.isEmpty()) { map.put(this.getWarpCategoryCache().get(x.toLowerCase()), warps); } }); return map; } @Override public boolean removeWarpCost(final String warpName) { final Optional<Warp> warp = this.getWarp(warpName); if (warp.isPresent()) { final Warp w = warp.get(); this.removeWarp(warpName); this.getWarpCache().put(w.getName().toLowerCase(), new WarpData( w.getCategory().orElse(null), 0, w.getDescription().orElse(null), w.getResourceKey(), w.getPosition(), w.getRotation(), w.getName() )); this.saveFromCache(); return true; } return false; } @Override public boolean setWarpCost(final String warpName, final double cost) { if (cost < 0) { return false; } final Optional<Warp> warp = this.getWarp(warpName); if (warp.isPresent()) { final Warp w = warp.get(); this.removeWarp(warpName); this.getWarpCache().put(w.getName().toLowerCase(), new WarpData( w.getCategory().orElse(null), cost, w.getDescription().orElse(null), w.getResourceKey(), w.getPosition(), w.getRotation(), w.getName() )); this.saveFromCache(); return true; } return false; } @Override public boolean setWarpCategory(final String warpName, @Nullable String category) { if (category != null) { final Optional<WarpCategory> c = this.getWarpCategory(category); if (!c.isPresent()) { final WarpCategory wc = new WarpCategoryData( category, null, null); this.getWarpCategoryCache().put(category.toLowerCase(), wc); } else { this.categoryCollectionMap.remove(category.toLowerCase()); } category = category.toLowerCase(); } else { this.uncategorised = null; } final Optional<Warp> warp = this.getWarp(warpName); if (warp.isPresent()) { final Warp w = warp.get(); this.removeWarp(warpName); this.getWarpCache().put(w.getName().toLowerCase(), new WarpData( category, w.getCost().orElse(0d), w.getDescription().orElse(null), w.getResourceKey(), w.getPosition(), w.getRotation(), w.getName() )); this.saveFromCache(); return true; } return false; } @Override public boolean setWarpDescription(final String warpName, @Nullable final Component description) { final Optional<Warp> warp = this.getWarp(warpName); if (warp.isPresent()) { final Warp w = warp.get(); this.removeWarp(warpName); this.getWarpCache().put(w.getName().toLowerCase(), new WarpData( w.getCategory().orElse(null), w.getCost().orElse(0d), description, w.getResourceKey(), w.getPosition(), w.getRotation(), w.getName() )); this.saveFromCache(); return true; } return false; } @Override public Set<String> getWarpNames() { return this.getWarpCache().keySet(); } @Override public Optional<WarpCategory> getWarpCategory(final String category) { return Optional.ofNullable(this.getWarpCategoryCache().get(category.toLowerCase())); } @Override public boolean setWarpCategoryDisplayName(final String category, @Nullable final Component displayName) { final Optional<WarpCategory> c = this.getWarpCategory(category); if (c.isPresent()) { final WarpCategory cat = c.get(); this.getWarpCategoryCache().remove(category.toLowerCase()); this.getWarpCategoryCache().put(category.toLowerCase(), new WarpCategoryData( cat.getId(), displayName, cat.getDescription().orElse(null) )); this.saveFromCache(); return true; } return false; } @Override public boolean setWarpCategoryDescription(final String category, @Nullable final Component description) { final Optional<WarpCategory> c = this.getWarpCategory(Objects.requireNonNull(category)); if (c.isPresent()) { final WarpCategory cat = c.get(); this.getWarpCategoryCache().remove(category.toLowerCase()); this.getWarpCategoryCache().put(category.toLowerCase(), new WarpCategoryData( cat.getId(), cat.getDisplayName(), description )); this.saveFromCache(); return true; } return false; } }
/** * * Copyright 2015 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.igniterealtime.smack.inttest; import static org.reflections.ReflectionUtils.getAllMethods; import static org.reflections.ReflectionUtils.withAnnotation; import static org.reflections.ReflectionUtils.withModifier; import static org.reflections.ReflectionUtils.withParametersCount; import static org.reflections.ReflectionUtils.withReturnType; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.igniterealtime.smack.inttest.IntTestUtil.UsernameAndPassword; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException.XMPPErrorException; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration.Builder; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.iqregister.AccountManager; import org.junit.AfterClass; import org.junit.BeforeClass; import org.reflections.Reflections; import org.reflections.scanners.MethodAnnotationsScanner; import org.reflections.scanners.MethodParameterScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import eu.geekplace.javapinning.JavaPinning; public class SmackIntegrationTestFramework { private static final Logger LOGGER = Logger.getLogger(SmackIntegrationTestFramework.class.getName()); private static final char CLASS_METHOD_SEP = '#'; protected final Configuration config; protected TestRunResult testRunResult; private SmackIntegrationTestEnvironment environment; public enum TestType { Normal, LowLevel, } public static void main(String[] args) throws IOException, KeyManagementException, NoSuchAlgorithmException, SmackException, XMPPException, InterruptedException { Configuration config = Configuration.newConfiguration(); SmackIntegrationTestFramework sinttest = new SmackIntegrationTestFramework(config); TestRunResult testRunResult = sinttest.run(); for (Entry<Class<? extends AbstractSmackIntTest>, String> entry : testRunResult.impossibleTestClasses.entrySet()) { LOGGER.info("Could not run " + entry.getKey().getName() + " because: " + entry.getValue()); } for (TestNotPossible testNotPossible : testRunResult.impossibleTestMethods) { LOGGER.info("Could not run " + testNotPossible.testMethod.getName() + " because: " + testNotPossible.testNotPossibleException.getMessage()); } LOGGER.info("SmackIntegrationTestFramework[" + testRunResult.testRunId + ']' + ": Finished [" + testRunResult.successfulTests.size() + '/' + testRunResult.numberOfTests + ']'); if (!testRunResult.failedIntegrationTests.isEmpty()) { for (FailedTest failedTest : testRunResult.failedIntegrationTests) { final Method method = failedTest.testMethod; final String className = method.getDeclaringClass().getName(); final String methodName = method.getName(); final Exception cause = failedTest.failureReason; LOGGER.severe(className + CLASS_METHOD_SEP + methodName + " failed: " + cause); } System.exit(2); } System.exit(0); } public SmackIntegrationTestFramework(Configuration configuration) { this.config = configuration; } public synchronized TestRunResult run() throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException, InterruptedException { testRunResult = new TestRunResult(); LOGGER.info("SmackIntegrationTestFramework [" + testRunResult.testRunId + ']' + ": Starting"); if (config.debug) { // JUL Debugger will not print any information until configured to print log messages of // level FINE // TODO configure JUL for log? SmackConfiguration.addDisabledSmackClass("org.jivesoftware.smack.debugger.JulDebugger"); SmackConfiguration.DEBUG = true; } if (config.replyTimeout > 0) { SmackConfiguration.setDefaultPacketReplyTimeout(config.replyTimeout); } if (config.securityMode != SecurityMode.required) { AccountManager.sensitiveOperationOverInsecureConnectionDefault(true); } // TODO print effective configuration String[] testPackages; if (config.testPackages == null) { testPackages = new String[] { "org.jivesoftware.smackx", "org.jivesoftware.smack" }; } else { testPackages = config.testPackages.toArray(new String[config.testPackages.size()]); } Reflections reflections = new Reflections((Object[]) testPackages, new SubTypesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new MethodParameterScanner()); Set<Class<? extends AbstractSmackIntegrationTest>> inttestClasses = reflections.getSubTypesOf(AbstractSmackIntegrationTest.class); Set<Class<? extends AbstractSmackLowLevelIntegrationTest>> lowLevelInttestClasses = reflections.getSubTypesOf(AbstractSmackLowLevelIntegrationTest.class); Set<Class<? extends AbstractSmackIntTest>> classes = new HashSet<>(inttestClasses.size() + lowLevelInttestClasses.size()); classes.addAll(inttestClasses); classes.addAll(lowLevelInttestClasses); if (classes.isEmpty()) { throw new IllegalStateException("No test classes found"); } LOGGER.info("SmackIntegrationTestFramework [" + testRunResult.testRunId + "]: Finished scanning for tests, preparing environment"); environment = prepareEnvironment(); try { runTests(classes); } finally { // Ensure that the accounts are deleted and disconnected before we continue disconnectAndMaybeDelete(environment.conOne); disconnectAndMaybeDelete(environment.conTwo); } return testRunResult; } @SuppressWarnings("unchecked") private void runTests(Set<Class<? extends AbstractSmackIntTest>> classes) throws NoResponseException, NotConnectedException, InterruptedException { for (Class<? extends AbstractSmackIntTest> testClass : classes) { final String testClassName = testClass.getName(); if (config.enabledTests != null && !config.enabledTests.contains(testClassName)) { LOGGER.info("Skipping test class " + testClassName + " because it is not enabled"); continue; } if (config.disabledTests != null && config.disabledTests.contains(testClassName)) { LOGGER.info("Skipping test class " + testClassName + " because it is disalbed"); continue; } TestType testType; if (AbstractSmackLowLevelIntegrationTest.class.isAssignableFrom(testClass)) { testType = TestType.LowLevel; } else if (AbstractSmackIntegrationTest.class.isAssignableFrom(testClass)) { testType = TestType.Normal; } else { throw new AssertionError(); } List<Method> smackIntegrationTestMethods = new LinkedList<>(); for (Method method : testClass.getMethods()) { if (!method.isAnnotationPresent(SmackIntegrationTest.class)) { continue; } Class<?> retClass = method.getReturnType(); if (!(retClass.equals(Void.TYPE))) { LOGGER.warning("SmackIntegrationTest annotation on method that does not return void"); continue; } final Class<?>[] parameterTypes = method.getParameterTypes(); switch (testType) { case Normal: if (method.getParameterTypes().length > 0) { LOGGER.warning("SmackIntegrationTest annotaton on method that takes arguments "); continue; } break; case LowLevel: for (Class<?> parameterType : parameterTypes) { if (!parameterType.isAssignableFrom(XMPPTCPConnection.class)) { LOGGER.warning("SmackIntegrationTest low-level test method declares parameter that is not of type XMPPTCPConnection"); } } break; } smackIntegrationTestMethods.add(method); } if (smackIntegrationTestMethods.isEmpty()) { LOGGER.warning("No integration test methods found"); continue; } Iterator<Method> it = smackIntegrationTestMethods.iterator(); while (it.hasNext()) { final Method method = it.next(); final String methodName = method.getName(); final String className = method.getDeclaringClass().getName(); if (config.enabledTests != null && !config.enabledTests.contains(methodName) && !config.enabledTests.contains(className)) { LOGGER.fine("Skipping test method " + methodName + " because it is not enabled"); it.remove(); continue; } if (config.disabledTests != null && config.disabledTests.contains(methodName)) { LOGGER.info("Skipping test method " + methodName + " because it is disabled"); it.remove(); continue; } } if (smackIntegrationTestMethods.isEmpty()) { LOGGER.info("All tests in " + testClassName + " are disabled"); continue; } testRunResult.numberOfTests.addAndGet(smackIntegrationTestMethods.size()); AbstractSmackIntTest test; switch (testType) { case Normal: { Constructor<? extends AbstractSmackIntegrationTest> cons; try { cons = ((Class<? extends AbstractSmackIntegrationTest>) testClass).getConstructor(SmackIntegrationTestEnvironment.class); } catch (NoSuchMethodException | SecurityException e) { LOGGER.log(Level.WARNING, "Smack Integration Test class could not get constructed (public Con)structor(SmackIntegrationTestEnvironment) missing?)", e); continue; } try { test = cons.newInstance(environment); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof TestNotPossibleException) { testRunResult.impossibleTestClasses.put(testClass, cause.getMessage()); } else { throwFatalException(cause); LOGGER.log(Level.WARNING, "Could not construct test class", e); } continue; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { LOGGER.log(Level.WARNING, "todo", e); continue; } } break; case LowLevel: { Constructor<? extends AbstractSmackLowLevelIntegrationTest> cons; try { cons = ((Class<? extends AbstractSmackLowLevelIntegrationTest>) testClass).getConstructor( Configuration.class, String.class); } catch (NoSuchMethodException | SecurityException e) { LOGGER.log(Level.WARNING, "Smack Integration Test class could not get constructed (public Con)structor(SmackIntegrationTestEnvironment) missing?)", e); continue; } try { test = cons.newInstance(config, testRunResult.testRunId); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof TestNotPossibleException) { testRunResult.impossibleTestClasses.put(testClass, cause.getMessage()); } else { throwFatalException(cause); LOGGER.log(Level.WARNING, "Could not construct test class", e); } continue; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { LOGGER.log(Level.WARNING, "todo", e); continue; } } break; default: throw new AssertionError(); } try { // Run the @BeforeClass methods (if any) Set<Method> beforeClassMethods = getAllMethods(testClass, withAnnotation(BeforeClass.class), withReturnType(Void.TYPE), withParametersCount(0), withModifier(Modifier.PUBLIC | Modifier.STATIC)); // See if there are any methods that have the @BeforeClassAnnotation but a wrong signature Set<Method> allBeforeClassMethods = getAllMethods(testClass, withAnnotation(BeforeClass.class)); allBeforeClassMethods.removeAll(beforeClassMethods); if (!allBeforeClassMethods.isEmpty()) { throw new IllegalArgumentException("@BeforeClass methods with wrong signature found"); } if (beforeClassMethods.size() == 1) { Method beforeClassMethod = beforeClassMethods.iterator().next(); try { beforeClassMethod.invoke(null); } catch (InvocationTargetException | IllegalAccessException e) { LOGGER.log(Level.SEVERE, "Exception executing @AfterClass method", e); } catch (IllegalArgumentException e) { throw new AssertionError(e); } } else if (beforeClassMethods.size() > 1) { throw new IllegalArgumentException("Only one @BeforeClass method allowed"); } for (Method testMethod : smackIntegrationTestMethods) { final String testPrefix = testClass.getSimpleName() + '.' + testMethod.getName() + ": "; // Invoke all test methods on the test instance LOGGER.info(testPrefix + "Start"); long testStart = System.currentTimeMillis(); try { switch (testType) { case Normal: testMethod.invoke(test); break; case LowLevel: invokeLowLevel(testMethod, test); break; } LOGGER.info(testPrefix + "Success"); long testEnd = System.currentTimeMillis(); testRunResult.successfulTests.add(new SuccessfulTest(testMethod, testStart, testEnd, null)); } catch (InvocationTargetException e) { long testEnd = System.currentTimeMillis(); Throwable cause = e.getCause(); if (cause instanceof TestNotPossibleException) { LOGGER.info(testPrefix + "Not possible"); testRunResult.impossibleTestMethods.add(new TestNotPossible(testMethod, testStart, testEnd, null, (TestNotPossibleException) cause)); continue; } Exception nonFatalException = throwFatalException(cause); // An integration test failed testRunResult.failedIntegrationTests.add(new FailedTest(testMethod, testStart, testEnd, null, nonFatalException)); LOGGER.log(Level.SEVERE, testPrefix + "Failed", e); } catch (IllegalArgumentException | IllegalAccessException e) { throw new AssertionError(e); } } } finally { // Run the @AfterClass method (if any) Set<Method> afterClassMethods = getAllMethods(testClass, withAnnotation(AfterClass.class), withReturnType(Void.TYPE), withParametersCount(0), withModifier(Modifier.PUBLIC | Modifier.STATIC)); // See if there are any methods that have the @AfterClassAnnotation but a wrong signature Set<Method> allAfterClassMethods = getAllMethods(testClass, withAnnotation(AfterClass.class)); allAfterClassMethods.removeAll(afterClassMethods); if (!allAfterClassMethods.isEmpty()) { throw new IllegalArgumentException("@AfterClass methods with wrong signature found"); } if (afterClassMethods.size() == 1) { Method afterClassMethod = afterClassMethods.iterator().next(); try { afterClassMethod.invoke(null); } catch (InvocationTargetException | IllegalAccessException e) { LOGGER.log(Level.SEVERE, "Exception executing @AfterClass method", e); } catch (IllegalArgumentException e) { throw new AssertionError(e); } } else if (afterClassMethods.size() > 1) { throw new IllegalArgumentException("Only one @AfterClass method allowed"); } } } } private void invokeLowLevel(Method testMethod, AbstractSmackIntTest test) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { // We have checked before that every parameter, if any, is of type XMPPTCPConnection final int numberOfConnections = testMethod.getParameterTypes().length; XMPPTCPConnection[] connections = null; try { if (numberOfConnections > 0 && !config.registerAccounts) { throw new TestNotPossibleException( "Must create accounts for this test, but it's not enabled"); } connections = new XMPPTCPConnection[numberOfConnections]; for (int i = 0; i < numberOfConnections; ++i) { connections[i] = getConnectedConnection(config); } } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } // Behave like this was an InvocationTargetException throw new InvocationTargetException(e); } try { testMethod.invoke(test, (Object[]) connections); } finally { for (int i = 0; i < numberOfConnections; ++i) { try { AccountManager.getInstance(connections[i]).deleteAccount(); LOGGER.info("Successfully deleted account for connection (" + connections[i].getConnectionCounter() + ')'); } catch (NoResponseException | XMPPErrorException | NotConnectedException | InterruptedException e) { LOGGER.log(Level.SEVERE, "Could not delete account", e); } connections[i].disconnect(); } } } protected void disconnectAndMaybeDelete(XMPPTCPConnection connection) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (config.registerAccounts) { AccountManager am = AccountManager.getInstance(connection); am.deleteAccount(); } connection.disconnect(); } protected SmackIntegrationTestEnvironment prepareEnvironment() throws SmackException, IOException, XMPPException, InterruptedException, KeyManagementException, NoSuchAlgorithmException { XMPPTCPConnection conOne = null; XMPPTCPConnection conTwo = null; try { conOne = getConnectedConnectionFor(AccountNum.One); conTwo = getConnectedConnectionFor(AccountNum.Two); } catch (Exception e) { if (conOne != null) { conOne.disconnect(); } if (conTwo != null) { conTwo.disconnect(); } throw e; } return new SmackIntegrationTestEnvironment(conOne, conTwo, testRunResult.testRunId, config); } enum AccountNum { One, Two, } private static final String USERNAME_PREFIX = "smack-inttest"; private XMPPTCPConnection getConnectedConnectionFor(AccountNum accountNum) throws SmackException, IOException, XMPPException, InterruptedException, KeyManagementException, NoSuchAlgorithmException { String middlefix; String accountUsername; String accountPassword; switch (accountNum) { case One: accountUsername = config.accountOneUsername; accountPassword = config.accountOnePassword; middlefix = "one"; break; case Two: accountUsername = config.accountTwoUsername; accountPassword = config.accountTwoPassword; middlefix = "two"; break; default: throw new IllegalStateException(); } if (StringUtils.isNullOrEmpty(accountUsername)) { accountUsername = USERNAME_PREFIX + '-' + middlefix + '-' +testRunResult.testRunId; } if (StringUtils.isNullOrEmpty(accountPassword)) { accountPassword = StringUtils.randomString(16); } // @formatter:off Builder builder = XMPPTCPConnectionConfiguration.builder() .setServiceName(config.service) .setUsernameAndPassword(accountUsername, accountPassword) .setResource(middlefix + '-' + testRunResult.testRunId) .setSecurityMode(config.securityMode); // @formatter:on if (StringUtils.isNotEmpty(config.serviceTlsPin)) { SSLContext sc = JavaPinning.forPin(config.serviceTlsPin); builder.setCustomSSLContext(sc); } XMPPTCPConnection connection = new XMPPTCPConnection(builder.build()); connection.connect(); if (config.registerAccounts) { IntTestUtil.registerAccount(connection, accountUsername, accountPassword); // TODO is this still required? // Some servers, e.g. Openfire, do not support a login right after the account was // created, so disconnect and re-connection the connection first. connection.disconnect(); connection.connect(); } connection.login(); return connection; } static XMPPTCPConnection getConnectedConnection(Configuration config) throws KeyManagementException, NoSuchAlgorithmException, InterruptedException, SmackException, IOException, XMPPException { XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder(); if (config.serviceTlsPin != null) { SSLContext sc = JavaPinning.forPin(config.serviceTlsPin); builder.setCustomSSLContext(sc); } builder.setSecurityMode(config.securityMode); builder.setServiceName(config.service); XMPPTCPConnection connection = new XMPPTCPConnection(builder.build()); connection.connect(); UsernameAndPassword uap = IntTestUtil.registerAccount(connection); connection.login(uap.username, uap.password); return connection; } private static Exception throwFatalException(Throwable e) throws Error, NotConnectedException, NoResponseException, InterruptedException { if (e instanceof NotConnectedException) { throw (NotConnectedException) e; } if (e instanceof NoResponseException) { throw (NoResponseException) e; } if (e instanceof InterruptedException) { throw (InterruptedException) e; } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof Error) { throw (Error) e; } return (Exception) e; } public static class TestRunResult { public final String testRunId = StringUtils.randomString(5); private final List<SuccessfulTest> successfulTests = Collections.synchronizedList(new LinkedList<SuccessfulTest>()); private final List<FailedTest> failedIntegrationTests = Collections.synchronizedList(new LinkedList<FailedTest>()); private final List<TestNotPossible> impossibleTestMethods = Collections.synchronizedList(new LinkedList<TestNotPossible>()); private final Map<Class<? extends AbstractSmackIntTest>, String> impossibleTestClasses = new HashMap<>(); private final AtomicInteger numberOfTests = new AtomicInteger(); private TestRunResult() { } public String getTestRunId() { return testRunId; } public int getNumberOfTests() { return numberOfTests.get(); } public List<SuccessfulTest> getSuccessfulTests() { return Collections.unmodifiableList(successfulTests); } public List<FailedTest> getFailedTests() { return Collections.unmodifiableList(failedIntegrationTests); } public List<TestNotPossible> getNotPossibleTests() { return Collections.unmodifiableList(impossibleTestMethods); } public Map<Class<? extends AbstractSmackIntTest>, String> getImpossibleTestClasses() { return Collections.unmodifiableMap(impossibleTestClasses); } } }
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2015 Florian Kohlmayer, Fabian Prasser * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.framework.check; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.ARXConfiguration.ARXConfigurationInternal; import org.deidentifier.arx.framework.check.StateMachine.Transition; import org.deidentifier.arx.framework.check.distribution.DistributionAggregateFunction; import org.deidentifier.arx.framework.check.distribution.IntArrayDictionary; import org.deidentifier.arx.framework.check.groupify.HashGroupify; import org.deidentifier.arx.framework.check.history.History; import org.deidentifier.arx.framework.data.Data; import org.deidentifier.arx.framework.data.DataManager; import org.deidentifier.arx.framework.data.Dictionary; import org.deidentifier.arx.framework.lattice.SolutionSpace; import org.deidentifier.arx.framework.lattice.Transformation; import org.deidentifier.arx.metric.InformationLoss; import org.deidentifier.arx.metric.InformationLossWithBound; import org.deidentifier.arx.metric.Metric; /** * This class orchestrates the process of checking a node for k-anonymity. * * @author Fabian Prasser * @author Florian Kohlmayer */ public class NodeChecker { /** * The result of a check. */ public static class Result { /** Overall anonymity. */ public final Boolean privacyModelFulfilled; /** k-Anonymity sub-criterion. */ public final Boolean minimalClassSizeFulfilled; /** Information loss. */ public final InformationLoss<?> informationLoss; /** Lower bound. */ public final InformationLoss<?> lowerBound; /** * Creates a new instance. * * @param privacyModelFulfilled * @param minimalClassSizeFulfilled * @param infoLoss * @param lowerBound */ Result(Boolean privacyModelFulfilled, Boolean minimalClassSizeFulfilled, InformationLoss<?> infoLoss, InformationLoss<?> lowerBound) { this.privacyModelFulfilled = privacyModelFulfilled; this.minimalClassSizeFulfilled = minimalClassSizeFulfilled; this.informationLoss = infoLoss; this.lowerBound = lowerBound; } } /** The config. */ private final ARXConfigurationInternal config; /** The data. */ private final Data dataGeneralized; /** The microaggregation functions. */ private final DistributionAggregateFunction[] microaggregationFunctions; /** The start index of the attributes with microaggregation in the data array */ private final int microaggregationStartIndex; /** The number of attributes with microaggregation in the data array */ private final int microaggregationNumAttributes; /** Map for the microaggregated data subset */ private final int[] microaggregationMap; /** Header of the microaggregated data subset */ private final String[] microaggregationHeader; /** The current hash groupify. */ private HashGroupify currentGroupify; /** The last hash groupify. */ private HashGroupify lastGroupify; /** The history. */ private final History history; /** The metric. */ private final Metric<?> metric; /** The state machine. */ private final StateMachine stateMachine; /** The data transformer. */ private final Transformer transformer; /** The solution space */ private final SolutionSpace solutionSpace; /** Is a minimal class size required */ private final boolean minimalClassSizeRequired; /** * Creates a new NodeChecker instance. * * @param manager The manager * @param metric The metric * @param config The configuration * @param historyMaxSize The history max size * @param snapshotSizeDataset A history threshold * @param snapshotSizeSnapshot A history threshold * @param solutionSpace */ public NodeChecker(final DataManager manager, final Metric<?> metric, final ARXConfigurationInternal config, final int historyMaxSize, final double snapshotSizeDataset, final double snapshotSizeSnapshot, final SolutionSpace solutionSpace) { // Initialize all operators this.metric = metric; this.config = config; this.dataGeneralized = manager.getDataGeneralized(); this.microaggregationFunctions = manager.getMicroaggregationFunctions(); this.microaggregationStartIndex = manager.getMicroaggregationStartIndex(); this.microaggregationNumAttributes = manager.getMicroaggregationNumAttributes(); this.microaggregationMap = manager.getMicroaggregationMap(); this.microaggregationHeader = manager.getMicroaggregationHeader(); this.solutionSpace = solutionSpace; this.minimalClassSizeRequired = config.getMinimalGroupSize() != Integer.MAX_VALUE; int initialSize = (int) (manager.getDataGeneralized().getDataLength() * 0.01d); IntArrayDictionary dictionarySensValue; IntArrayDictionary dictionarySensFreq; if ((config.getRequirements() & ARXConfiguration.REQUIREMENT_DISTRIBUTION) != 0) { dictionarySensValue = new IntArrayDictionary(initialSize); dictionarySensFreq = new IntArrayDictionary(initialSize); } else { // Just to allow byte code instrumentation dictionarySensValue = new IntArrayDictionary(0); dictionarySensFreq = new IntArrayDictionary(0); } this.history = new History(manager.getDataGeneralized().getArray().length, historyMaxSize, snapshotSizeDataset, snapshotSizeSnapshot, config, dictionarySensValue, dictionarySensFreq, solutionSpace); this.stateMachine = new StateMachine(history); this.currentGroupify = new HashGroupify(initialSize, config); this.lastGroupify = new HashGroupify(initialSize, config); this.transformer = new Transformer(manager.getDataGeneralized().getArray(), manager.getDataAnalyzed().getArray(), manager.getHierarchies(), config, dictionarySensValue, dictionarySensFreq); } /** * Applies the given transformation and returns the dataset * @param transformation * @return */ public TransformedData applyTransformation(final Transformation transformation) { // Apply transition and groupify currentGroupify = transformer.apply(0L, transformation.getGeneralization(), currentGroupify); currentGroupify.stateAnalyze(transformation, true); if (!currentGroupify.isPrivacyModelFulfilled() && !config.isSuppressionAlwaysEnabled()) { currentGroupify.stateResetSuppression(); } // Determine information loss InformationLoss<?> loss = transformation.getInformationLoss(); if (loss == null) { loss = metric.getInformationLoss(transformation, currentGroupify).getInformationLoss(); } // Prepare buffers Data microaggregatedOutput = new Data(new int[0][0], new String[0], new int[0], new Dictionary(0)); Data generalizedOutput = new Data(transformer.getBuffer(), dataGeneralized.getHeader(), dataGeneralized.getMap(), dataGeneralized.getDictionary()); // Perform microaggregation. This has to be done before suppression. if (microaggregationFunctions.length > 0) { microaggregatedOutput = currentGroupify.performMicroaggregation(transformer.getBuffer(), microaggregationStartIndex, microaggregationNumAttributes, microaggregationFunctions, microaggregationMap, microaggregationHeader); } // Perform suppression if (config.getAbsoluteMaxOutliers() != 0 || !currentGroupify.isPrivacyModelFulfilled()) { currentGroupify.performSuppression(transformer.getBuffer()); } // Return the buffer return new TransformedData(generalizedOutput, microaggregatedOutput, currentGroupify.getEquivalenceClassStatistics(), new Result(currentGroupify.isPrivacyModelFulfilled(), minimalClassSizeRequired ? currentGroupify.isMinimalClassSizeFulfilled() : null, loss, null)); } /** * Checks the given transformation, computes the utility if it fulfills the privacy model * @param node * @return */ public NodeChecker.Result check(final Transformation node) { return check(node, false); } /** * Checks the given transformation * @param node * @param forceMeasureInfoLoss * @return */ public NodeChecker.Result check(final Transformation node, final boolean forceMeasureInfoLoss) { // If the result is already know, simply return it if (node.getData() != null && node.getData() instanceof NodeChecker.Result) { return (NodeChecker.Result) node.getData(); } // Store snapshot from last check if (stateMachine.getLastNode() != null) { history.store(solutionSpace.getTransformation(stateMachine.getLastNode()), currentGroupify, stateMachine.getLastTransition().snapshot); } // Transition final Transition transition = stateMachine.transition(node.getGeneralization()); // Switch groupifies final HashGroupify temp = lastGroupify; lastGroupify = currentGroupify; currentGroupify = temp; // Apply transition switch (transition.type) { case UNOPTIMIZED: currentGroupify = transformer.apply(transition.projection, node.getGeneralization(), currentGroupify); break; case ROLLUP: currentGroupify = transformer.applyRollup(transition.projection, node.getGeneralization(), lastGroupify, currentGroupify); break; case SNAPSHOT: currentGroupify = transformer.applySnapshot(transition.projection, node.getGeneralization(), currentGroupify, transition.snapshot); break; } // We are done with transforming and adding currentGroupify.stateAnalyze(node, forceMeasureInfoLoss); if (forceMeasureInfoLoss && !currentGroupify.isPrivacyModelFulfilled() && !config.isSuppressionAlwaysEnabled()) { currentGroupify.stateResetSuppression(); } // Compute information loss and lower bound InformationLossWithBound<?> result = (currentGroupify.isPrivacyModelFulfilled() || forceMeasureInfoLoss) ? metric.getInformationLoss(node, currentGroupify) : null; InformationLoss<?> loss = result != null ? result.getInformationLoss() : null; InformationLoss<?> bound = result != null ? result.getLowerBound() : metric.getLowerBound(node, currentGroupify); // Return result; return new NodeChecker.Result(currentGroupify.isPrivacyModelFulfilled(), minimalClassSizeRequired ? currentGroupify.isMinimalClassSizeFulfilled() : null, loss, bound); } /** * Returns the configuration * @return */ public ARXConfigurationInternal getConfiguration() { return config; } /** * Returns the checkers history, if any. * * @return */ public History getHistory() { return history; } /** * Returns the utility measure * @return */ public Metric<?> getMetric() { return metric; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.connector.pulsar.source; import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.connector.source.Boundedness; import org.apache.flink.configuration.ConfigOption; import org.apache.flink.configuration.Configuration; import org.apache.flink.connector.pulsar.common.config.PulsarConfigBuilder; import org.apache.flink.connector.pulsar.common.config.PulsarOptions; import org.apache.flink.connector.pulsar.source.config.SourceConfiguration; import org.apache.flink.connector.pulsar.source.enumerator.cursor.StartCursor; import org.apache.flink.connector.pulsar.source.enumerator.cursor.StopCursor; import org.apache.flink.connector.pulsar.source.enumerator.subscriber.PulsarSubscriber; import org.apache.flink.connector.pulsar.source.enumerator.topic.TopicNameUtils; import org.apache.flink.connector.pulsar.source.enumerator.topic.TopicRange; import org.apache.flink.connector.pulsar.source.enumerator.topic.range.FullRangeGenerator; import org.apache.flink.connector.pulsar.source.enumerator.topic.range.RangeGenerator; import org.apache.flink.connector.pulsar.source.enumerator.topic.range.UniformRangeGenerator; import org.apache.flink.connector.pulsar.source.reader.deserializer.PulsarDeserializationSchema; import org.apache.pulsar.client.api.RegexSubscriptionMode; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.api.SubscriptionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import static java.lang.Boolean.FALSE; import static org.apache.flink.connector.pulsar.common.config.PulsarOptions.PULSAR_ADMIN_URL; import static org.apache.flink.connector.pulsar.common.config.PulsarOptions.PULSAR_ENABLE_TRANSACTION; import static org.apache.flink.connector.pulsar.common.config.PulsarOptions.PULSAR_SERVICE_URL; import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_CONSUMER_NAME; import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_ENABLE_AUTO_ACKNOWLEDGE_MESSAGE; import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_PARTITION_DISCOVERY_INTERVAL_MS; import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_READ_TRANSACTION_TIMEOUT; import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_SUBSCRIPTION_NAME; import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_SUBSCRIPTION_TYPE; import static org.apache.flink.connector.pulsar.source.config.PulsarSourceConfigUtils.SOURCE_CONFIG_VALIDATOR; import static org.apache.flink.util.InstantiationUtil.isSerializable; import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.flink.util.Preconditions.checkNotNull; import static org.apache.flink.util.Preconditions.checkState; /** * The builder class for {@link PulsarSource} to make it easier for the users to construct a {@link * PulsarSource}. * * <p>The following example shows the minimum setup to create a PulsarSource that reads the String * values from a Pulsar topic. * * <pre>{@code * PulsarSource<String> source = PulsarSource * .builder() * .setServiceUrl(PULSAR_BROKER_URL) * .setAdminUrl(PULSAR_BROKER_HTTP_URL) * .setSubscriptionName("flink-source-1") * .setTopics(Arrays.asList(TOPIC1, TOPIC2)) * .setDeserializationSchema(PulsarDeserializationSchema.flinkSchema(new SimpleStringSchema())) * .build(); * }</pre> * * <p>The service url, admin url, subscription name, topics to consume, and the record deserializer * are required fields that must be set. * * <p>To specify the starting position of PulsarSource, one can call {@link * #setStartCursor(StartCursor)}. * * <p>By default the PulsarSource runs in an {@link Boundedness#CONTINUOUS_UNBOUNDED} mode and never * stop until the Flink job is canceled or fails. To let the PulsarSource run in {@link * Boundedness#CONTINUOUS_UNBOUNDED} but stops at some given offsets, one can call {@link * #setUnboundedStopCursor(StopCursor)}. For example the following PulsarSource stops after it * consumes up to a event time when the Flink started. * * <pre>{@code * PulsarSource<String> source = PulsarSource * .builder() * .setServiceUrl(PULSAR_BROKER_URL) * .setAdminUrl(PULSAR_BROKER_HTTP_URL) * .setSubscriptionName("flink-source-1") * .setTopics(Arrays.asList(TOPIC1, TOPIC2)) * .setDeserializationSchema(PulsarDeserializationSchema.flinkSchema(new SimpleStringSchema())) * .setUnbounded(StopCursor.atEventTime(System.currentTimeMillis())) * .build(); * }</pre> * * @param <OUT> The output type of the source. */ @PublicEvolving public final class PulsarSourceBuilder<OUT> { private static final Logger LOG = LoggerFactory.getLogger(PulsarSourceBuilder.class); private final PulsarConfigBuilder configBuilder; private PulsarSubscriber subscriber; private RangeGenerator rangeGenerator; private StartCursor startCursor; private StopCursor stopCursor; private Boundedness boundedness; private PulsarDeserializationSchema<OUT> deserializationSchema; // private builder constructor. PulsarSourceBuilder() { this.configBuilder = new PulsarConfigBuilder(); this.startCursor = StartCursor.defaultStartCursor(); this.stopCursor = StopCursor.defaultStopCursor(); this.boundedness = Boundedness.CONTINUOUS_UNBOUNDED; } /** * Sets the admin endpoint for the PulsarAdmin of the PulsarSource. * * @param adminUrl the url for the PulsarAdmin. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setAdminUrl(String adminUrl) { return setConfig(PULSAR_ADMIN_URL, adminUrl); } /** * Sets the server's link for the PulsarConsumer of the PulsarSource. * * @param serviceUrl the server url of the Pulsar cluster. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setServiceUrl(String serviceUrl) { return setConfig(PULSAR_SERVICE_URL, serviceUrl); } /** * Sets the name for this pulsar subscription. * * @param subscriptionName the server url of the Pulsar cluster. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setSubscriptionName(String subscriptionName) { return setConfig(PULSAR_SUBSCRIPTION_NAME, subscriptionName); } /** * {@link SubscriptionType} is the consuming behavior for pulsar, we would generator different * split by the given subscription type. Please take some time to consider which subscription * type matches your application best. Default is {@link SubscriptionType#Shared}. * * @param subscriptionType The type of subscription. * @return this PulsarSourceBuilder. * @see <a href="https://pulsar.apache.org/docs/en/concepts-messaging/#subscriptions">Pulsar * Subscriptions</a> */ public PulsarSourceBuilder<OUT> setSubscriptionType(SubscriptionType subscriptionType) { return setConfig(PULSAR_SUBSCRIPTION_TYPE, subscriptionType); } /** * Set a pulsar topic list for flink source. Some topic may not exist currently, consuming this * non-existed topic wouldn't throw any exception. But the best solution is just consuming by * using a topic regex. You can set topics once either with {@link #setTopics} or {@link * #setTopicPattern} in this builder. * * @param topics The topic list you would like to consume message. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setTopics(String... topics) { return setTopics(Arrays.asList(topics)); } /** * Set a pulsar topic list for flink source. Some topic may not exist currently, consuming this * non-existed topic wouldn't throw any exception. But the best solution is just consuming by * using a topic regex. You can set topics once either with {@link #setTopics} or {@link * #setTopicPattern} in this builder. * * @param topics The topic list you would like to consume message. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setTopics(List<String> topics) { ensureSubscriberIsNull("topics"); List<String> distinctTopics = TopicNameUtils.distinctTopics(topics); this.subscriber = PulsarSubscriber.getTopicListSubscriber(distinctTopics); return this; } /** * Set a topic pattern to consume from the java regex str. You can set topics once either with * {@link #setTopics} or {@link #setTopicPattern} in this builder. * * @param topicsPattern the pattern of the topic name to consume from. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setTopicPattern(String topicsPattern) { return setTopicPattern(Pattern.compile(topicsPattern)); } /** * Set a topic pattern to consume from the java {@link Pattern}. You can set topics once either * with {@link #setTopics} or {@link #setTopicPattern} in this builder. * * @param topicsPattern the pattern of the topic name to consume from. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setTopicPattern(Pattern topicsPattern) { return setTopicPattern(topicsPattern, RegexSubscriptionMode.AllTopics); } /** * Set a topic pattern to consume from the java regex str. You can set topics once either with * {@link #setTopics} or {@link #setTopicPattern} in this builder. * * @param topicsPattern the pattern of the topic name to consume from. * @param regexSubscriptionMode The topic filter for regex subscription. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setTopicPattern( String topicsPattern, RegexSubscriptionMode regexSubscriptionMode) { return setTopicPattern(Pattern.compile(topicsPattern), regexSubscriptionMode); } /** * Set a topic pattern to consume from the java {@link Pattern}. You can set topics once either * with {@link #setTopics} or {@link #setTopicPattern} in this builder. * * @param topicsPattern the pattern of the topic name to consume from. * @param regexSubscriptionMode When subscribing to a topic using a regular expression, you can * pick a certain type of topics. * <ul> * <li>PersistentOnly: only subscribe to persistent topics. * <li>NonPersistentOnly: only subscribe to non-persistent topics. * <li>AllTopics: subscribe to both persistent and non-persistent topics. * </ul> * * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setTopicPattern( Pattern topicsPattern, RegexSubscriptionMode regexSubscriptionMode) { ensureSubscriberIsNull("topic pattern"); this.subscriber = PulsarSubscriber.getTopicPatternSubscriber(topicsPattern, regexSubscriptionMode); return this; } /** * The consumer name is informative and it can be used to identify a particular consumer * instance from the topic stats. */ public PulsarSourceBuilder<OUT> setConsumerName(String consumerName) { return setConfig(PULSAR_CONSUMER_NAME, consumerName); } /** * Set a topic range generator for Key_Shared subscription. * * @param rangeGenerator A generator which would generate a set of {@link TopicRange} for given * topic. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setRangeGenerator(RangeGenerator rangeGenerator) { if (configBuilder.contains(PULSAR_SUBSCRIPTION_TYPE)) { SubscriptionType subscriptionType = configBuilder.get(PULSAR_SUBSCRIPTION_TYPE); checkArgument( subscriptionType == SubscriptionType.Key_Shared, "Key_Shared subscription should be used for custom rangeGenerator instead of %s", subscriptionType); } else { LOG.warn("No subscription type provided, set it to Key_Shared."); setSubscriptionType(SubscriptionType.Key_Shared); } this.rangeGenerator = checkNotNull(rangeGenerator); return this; } /** * Specify from which offsets the PulsarSource should start consume from by providing an {@link * StartCursor}. * * @param startCursor set the starting offsets for the Source. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setStartCursor(StartCursor startCursor) { this.startCursor = checkNotNull(startCursor); return this; } /** * By default the PulsarSource is set to run in {@link Boundedness#CONTINUOUS_UNBOUNDED} manner * and thus never stops until the Flink job fails or is canceled. To let the PulsarSource run as * a streaming source but still stops at some point, one can set an {@link StopCursor} to * specify the stopping offsets for each partition. When all the partitions have reached their * stopping offsets, the PulsarSource will then exit. * * <p>This method is different from {@link #setBoundedStopCursor(StopCursor)} that after setting * the stopping offsets with this method, {@link PulsarSource#getBoundedness()} will still * return {@link Boundedness#CONTINUOUS_UNBOUNDED} even though it will stop at the stopping * offsets specified by the stopping offsets {@link StopCursor}. * * @param stopCursor The {@link StopCursor} to specify the stopping offset. * @return this PulsarSourceBuilder. * @see #setBoundedStopCursor(StopCursor) */ public PulsarSourceBuilder<OUT> setUnboundedStopCursor(StopCursor stopCursor) { this.boundedness = Boundedness.CONTINUOUS_UNBOUNDED; this.stopCursor = checkNotNull(stopCursor); return this; } /** * By default the PulsarSource is set to run in {@link Boundedness#CONTINUOUS_UNBOUNDED} manner * and thus never stops until the Flink job fails or is canceled. To let the PulsarSource run in * {@link Boundedness#BOUNDED} manner and stops at some point, one can set an {@link StopCursor} * to specify the stopping offsets for each partition. When all the partitions have reached * their stopping offsets, the PulsarSource will then exit. * * <p>This method is different from {@link #setUnboundedStopCursor(StopCursor)} that after * setting the stopping offsets with this method, {@link PulsarSource#getBoundedness()} will * return {@link Boundedness#BOUNDED} instead of {@link Boundedness#CONTINUOUS_UNBOUNDED}. * * @param stopCursor the {@link StopCursor} to specify the stopping offsets. * @return this PulsarSourceBuilder. * @see #setUnboundedStopCursor(StopCursor) */ public PulsarSourceBuilder<OUT> setBoundedStopCursor(StopCursor stopCursor) { this.boundedness = Boundedness.BOUNDED; this.stopCursor = checkNotNull(stopCursor); return this; } /** * DeserializationSchema is required for getting the {@link Schema} for deserialize message from * pulsar and getting the {@link TypeInformation} for message serialization in flink. * * <p>We have defined a set of implementations, using {@code * PulsarDeserializationSchema#pulsarSchema} or {@code PulsarDeserializationSchema#flinkSchema} * for creating the desired schema. */ public <T extends OUT> PulsarSourceBuilder<T> setDeserializationSchema( PulsarDeserializationSchema<T> deserializationSchema) { PulsarSourceBuilder<T> self = specialized(); self.deserializationSchema = deserializationSchema; return self; } /** * Set an arbitrary property for the PulsarSource and Pulsar Consumer. The valid keys can be * found in {@link PulsarSourceOptions} and {@link PulsarOptions}. * * <p>Make sure the option could be set only once or with same value. * * @param key the key of the property. * @param value the value of the property. * @return this PulsarSourceBuilder. */ public <T> PulsarSourceBuilder<OUT> setConfig(ConfigOption<T> key, T value) { configBuilder.set(key, value); return this; } /** * Set arbitrary properties for the PulsarSource and Pulsar Consumer. The valid keys can be * found in {@link PulsarSourceOptions} and {@link PulsarOptions}. * * @param config the config to set for the PulsarSource. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setConfig(Configuration config) { configBuilder.set(config); return this; } /** * Set arbitrary properties for the PulsarSource and Pulsar Consumer. The valid keys can be * found in {@link PulsarSourceOptions} and {@link PulsarOptions}. * * <p>This method is mainly used for future flink SQL binding. * * @param properties the config properties to set for the PulsarSource. * @return this PulsarSourceBuilder. */ public PulsarSourceBuilder<OUT> setProperties(Properties properties) { configBuilder.set(properties); return this; } /** * Build the {@link PulsarSource}. * * @return a PulsarSource with the settings made for this builder. */ @SuppressWarnings("java:S3776") public PulsarSource<OUT> build() { // Ensure the topic subscriber for pulsar. checkNotNull(subscriber, "No topic names or topic pattern are provided."); SubscriptionType subscriptionType = configBuilder.get(PULSAR_SUBSCRIPTION_TYPE); if (subscriptionType == SubscriptionType.Key_Shared) { if (rangeGenerator == null) { LOG.warn( "No range generator provided for key_shared subscription," + " we would use the UniformRangeGenerator as the default range generator."); this.rangeGenerator = new UniformRangeGenerator(); } } else { // Override the range generator. this.rangeGenerator = new FullRangeGenerator(); } if (boundedness == null) { LOG.warn("No boundedness was set, mark it as a endless stream."); this.boundedness = Boundedness.CONTINUOUS_UNBOUNDED; } if (boundedness == Boundedness.BOUNDED && configBuilder.get(PULSAR_PARTITION_DISCOVERY_INTERVAL_MS) >= 0) { LOG.warn( "{} property is overridden to -1 because the source is bounded.", PULSAR_PARTITION_DISCOVERY_INTERVAL_MS); configBuilder.override(PULSAR_PARTITION_DISCOVERY_INTERVAL_MS, -1L); } checkNotNull(deserializationSchema, "deserializationSchema should be set."); // Enable transaction if the cursor auto commit is disabled for Key_Shared & Shared. if (FALSE.equals(configBuilder.get(PULSAR_ENABLE_AUTO_ACKNOWLEDGE_MESSAGE)) && (subscriptionType == SubscriptionType.Key_Shared || subscriptionType == SubscriptionType.Shared)) { LOG.info( "Pulsar cursor auto commit is disabled, make sure checkpoint is enabled " + "and your pulsar cluster is support the transaction."); configBuilder.override(PULSAR_ENABLE_TRANSACTION, true); if (!configBuilder.contains(PULSAR_READ_TRANSACTION_TIMEOUT)) { LOG.warn( "The default pulsar transaction timeout is 3 hours, " + "make sure it was greater than your checkpoint interval."); } else { Long timeout = configBuilder.get(PULSAR_READ_TRANSACTION_TIMEOUT); LOG.warn( "The configured transaction timeout is {} mille seconds, " + "make sure it was greater than your checkpoint interval.", timeout); } } if (!configBuilder.contains(PULSAR_CONSUMER_NAME)) { LOG.warn( "We recommend set a readable consumer name through setConsumerName(String) in production mode."); } // Since these implementation could be a lambda, make sure they are serializable. checkState(isSerializable(startCursor), "StartCursor isn't serializable"); checkState(isSerializable(stopCursor), "StopCursor isn't serializable"); checkState(isSerializable(rangeGenerator), "RangeGenerator isn't serializable"); // Check builder configuration. SourceConfiguration sourceConfiguration = configBuilder.build(SOURCE_CONFIG_VALIDATOR, SourceConfiguration::new); return new PulsarSource<>( sourceConfiguration, subscriber, rangeGenerator, startCursor, stopCursor, boundedness, deserializationSchema); } // ------------- private helpers -------------- /** Helper method for java compiler recognize the generic type. */ @SuppressWarnings("unchecked") private <T extends OUT> PulsarSourceBuilder<T> specialized() { return (PulsarSourceBuilder<T>) this; } /** Topic name and topic pattern is conflict, make sure they are set only once. */ private void ensureSubscriberIsNull(String attemptingSubscribeMode) { if (subscriber != null) { throw new IllegalStateException( String.format( "Cannot use %s for consumption because a %s is already set for consumption.", attemptingSubscribeMode, subscriber.getClass().getSimpleName())); } } }
package com.log999.deprecated.logchunk.internal; import com.log999.displaychunk.DisplayableLogChunk; import com.log999.deprecated.chunkloader.LoadableLogChunk; import com.log999.util.LogFilePosition; import com.log999.util.MemoryCalculator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LogChunkImpl implements LoadableLogChunk, DisplayableLogChunk { private static Logger logger = LoggerFactory.getLogger(LogChunkImpl.class); private int bytesInChunk; private final int chunk; private final int maxBytesInChunk; private List<String> lines = new ArrayList<>(); private LogChunkImpl previous; private LogChunkImpl next; private long lineStart; private int longestLineLength; private short[] lineLengths; private int[] displayLineOffset; // The display index that the row will be displayed at (taking into account rows above) private long displayRowStartIndex; private int displayRowCount; public LogChunkImpl(int chunk, int maxBytesInChunk) { this.chunk = chunk; this.maxBytesInChunk = maxBytesInChunk; } @Override public boolean acceptLineIfRoom(String line) { int b = MemoryCalculator.bytesFor(line); int newSize = bytesInChunk + b; if (newSize > maxBytesInChunk) return false; bytesInChunk = newSize; lines.add(line); int len = line.length(); if (len > longestLineLength) { longestLineLength = len; } return true; } @Override public int getBytesInChunk() { return bytesInChunk; } @Override public long getLogLineStartIndex() { return lineStart; } @Override public List<String> getLines() { return lines; } @Override public void linkToNextChunk(LoadableLogChunk newChunk) { LogChunkImpl chunk = (LogChunkImpl)newChunk; next = chunk; chunk.previous = this; } @Override public void finishChunk() { lineLengths = new short[lines.size()]; for (int i=0; i<lines.size(); i++) { lineLengths[i] = (short)(lines.get(i).length()); } } public void setLogLineStartIndex(long idx) { lineStart = idx; } public LogFilePosition getDisplayRow(long desiredDisplayRowIndex) { if (displayLineOffset == null) { logger.warn("displayLineOffset is null"); return new LogFilePosition(desiredDisplayRowIndex,0); } short offset = (short)(desiredDisplayRowIndex - displayRowStartIndex); int i = Arrays.binarySearch(displayLineOffset, offset); if (i < 0) { int logFileIndex = -(i+2); if (logFileIndex < 0) logFileIndex = 0; long displayRowForStartOfLine = displayRowStartIndex + displayLineOffset[logFileIndex]; int lineOffset = (int)(desiredDisplayRowIndex - displayRowForStartOfLine); return new LogFilePosition(lineStart + logFileIndex, lineOffset); } else { return new LogFilePosition(lineStart + i, 0); } } @Deprecated public String getRealRowInOrNear(long idx) { return getRealRowInOrNear(idx,this); } private static String getRealRowInOrNear(long idx,LogChunkImpl chunk) { int maxChunkLinks = 3; while (chunk != null && maxChunkLinks-- > 0) { long chunkEnd = chunk.lineStart + chunk.getLines().size(); if (idx >= chunk.lineStart && idx < chunkEnd) { int offset = (int)(idx - chunk.lineStart); String line = chunk.lines.get(offset); return line; } chunk = chunk.next; logger.info("Looking in chunk {}",chunk); } return "..ENDOFFILE.."; } public String[] getRealRows(int rowsNeeded, long realLogLine) { String[] rows = new String[rowsNeeded]; fillRows(rows,realLogLine,this); return rows; } private static void fillRows(String[] rows,long realLineStart,LogChunkImpl chunk) { for (int i = 0; i < rows.length; i++) { long idx = realLineStart + i; if (chunk == null) { rows[i] = "..ENDOFFILE.."; } else { long chunkEnd = chunk.lineStart + chunk.getLines().size(); LOOP: while (idx >= chunkEnd) { logger.info("Looking for {} - end is {} Skip to {}", idx, chunkEnd, chunk.next); chunk = chunk.next; if (chunk == null) break LOOP; chunkEnd = chunk.lineStart + chunk.getLines().size(); } } if (chunk == null) { rows[i] = "..ENDOFFILE.."; } else { rows[i] = chunk.lines.get((int) (idx - chunk.lineStart)); } } } // ------------------------------------------------------------------------ // Holding rows // ------------------------------------------------------------------------ public String[] getHoldingRows(int rowsNeeded, long realLogLine) { String[] rows = new String[rowsNeeded]; fillHoldingRows(rows, realLogLine, this); return rows; } private static void fillHoldingRows(String[] rows,long reallineStart,LogChunkImpl chunk) { for (int i = 0; i < rows.length; i++) { long idx = reallineStart + i; if (chunk == null) { rows[i] = "."; } else { long chunkEnd = chunk.lineStart + chunk.getLines().size(); LOOP: while (idx >= chunkEnd) { logger.info("Holding Looking for {} - end is {} Skip to {}", idx, chunkEnd, chunk.next); chunk = chunk.next; if (chunk == null) break LOOP; chunkEnd = chunk.lineStart + chunk.getLines().size(); } } if (chunk == null) { rows[i] = "."; } else { int r = (int) (idx - chunk.lineStart); int length = chunk.lineLengths[r]; rows[i] = buildRandomLine(length); } } } // TODO Factor me into helper private static String SOURCE = "MMLDK SF DLK LKSDJF LSKDFJ KJSDF LKJS LKJSDF KLJS084 OWHK 23IOPJF DKLNSDKLFJ ISDJFIP SD F;KJSD LKFJS SDKKJF LSKDFJ LSKDJF KLSDJF LKSDJF KL JKLLKLSJDFKJL FSDLKJF KLSDJFLKJSDF LK"+ "SFKJH SKDJFH KSJDFHKJSDHF JSDHFJHDJHFJDHF DKFS KJDFH KJSDHFJHSDJHJ JDFH JD JDJ HFHJ FKJDLFJLSKDJF LKJSDFLKJSDFL JSDLKFJ LSDKJF"; private static String RANDOM = SOURCE + " " + SOURCE + " " + SOURCE + " " + SOURCE + " " + SOURCE; private static String buildRandomLine(int length) { int offset = length % 10; int end = Math.min(RANDOM.length(), length); return RANDOM.substring(offset,end); } @Override public boolean isLoaded() { return true; } @Override public void load() { // NOOP for now } @Override public void setDisplayRowStartIndex(long displayRowStartIndex) { this.displayRowStartIndex = displayRowStartIndex; } @Override public long getDisplayRowStartIndex() { return displayRowStartIndex; } @Override public void calculateLineWraps(int wrap) { displayLineOffset = new int[lines.size()]; int count = 0; for (int i=0; i<lineLengths.length; i++) { displayLineOffset[i] = count; int linesForRow = 1 + (lineLengths[i] / wrap); count += linesForRow; } displayRowCount = count; } @Override public int getDisplayRowCount() { return displayRowCount; } @Override public String toString() { return "LogChunkImpl{" + "bytesInChunk=" + bytesInChunk + ", chunk=" + chunk + ", maxBytesInChunk=" + maxBytesInChunk + ", lines=" + lines + ", lineStart=" + lineStart + ", longestLineLength=" + longestLineLength + ", lineLengths=" + Arrays.toString(lineLengths) + ", displayLineOffset=" + Arrays.toString(displayLineOffset) + ", displayRowStartIndex=" + displayRowStartIndex + ", displayRowCount=" + displayRowCount + '}'; } }
package com.ironz.binaryprefs.serialization.serializer.persistable.io; import com.ironz.binaryprefs.serialization.serializer.*; import com.ironz.binaryprefs.serialization.serializer.persistable.Persistable; import com.ironz.binaryprefs.serialization.serializer.persistable.PersistableRegistry; public final class PersistableObjectInput implements DataInput { private static final String BASE_INCORRECT_TYPE_MESSAGE = "cannot be deserialized in '%s' flag type"; private static final String BASE_NOT_MIRRORED_MESSAGE = "May be your read/write contract isn't mirror-implemented or " + "old disk version is not backward compatible with new class version?"; private static final String INCORRECT_BOOLEAN_MESSAGE = "boolean " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_BYTE_MESSAGE = "byte " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_BYTE_ARRAY_MESSAGE = "byte array " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_SHORT_MESSAGE = "short " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_CHAR_MESSAGE = "char " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_INT_MESSAGE = "int " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_LONG_MESSAGE = "long " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_FLOAT_MESSAGE = "float " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_DOUBLE_MESSAGE = "double " + BASE_INCORRECT_TYPE_MESSAGE; private static final String INCORRECT_STRING_MESSAGE = "String " + BASE_INCORRECT_TYPE_MESSAGE; private static final String OUT_OF_BOUNDS_MESSAGE = "Can't read out of bounds array (expected size: %s bytes > disk size: %s bytes) for %s! key" + BASE_NOT_MIRRORED_MESSAGE; private static final String EMPTY_BYTE_ARRAY_MESSAGE = "Cannot deserialize empty byte array for %s key! " + BASE_NOT_MIRRORED_MESSAGE; private final BooleanSerializer booleanSerializer; private final ByteSerializer byteSerializer; private final ByteArraySerializer byteArraySerializer; private final CharSerializer charSerializer; private final DoubleSerializer doubleSerializer; private final FloatSerializer floatSerializer; private final IntegerSerializer integerSerializer; private final LongSerializer longSerializer; private final ShortSerializer shortSerializer; private final StringSerializer stringSerializer; private final PersistableRegistry persistableRegistry; private int offset = 0; private byte[] bytes; private String key; public PersistableObjectInput(BooleanSerializer booleanSerializer, ByteSerializer byteSerializer, ByteArraySerializer byteArraySerializer, CharSerializer charSerializer, DoubleSerializer doubleSerializer, FloatSerializer floatSerializer, IntegerSerializer integerSerializer, LongSerializer longSerializer, ShortSerializer shortSerializer, StringSerializer stringSerializer, PersistableRegistry persistableRegistry) { this.booleanSerializer = booleanSerializer; this.byteSerializer = byteSerializer; this.byteArraySerializer = byteArraySerializer; this.charSerializer = charSerializer; this.doubleSerializer = doubleSerializer; this.floatSerializer = floatSerializer; this.integerSerializer = integerSerializer; this.longSerializer = longSerializer; this.shortSerializer = shortSerializer; this.stringSerializer = stringSerializer; this.persistableRegistry = persistableRegistry; } @Override public Persistable deserialize(String key, byte[] bytes) { this.offset = 0; this.key = key; this.bytes = bytes; checkBytes(); skipPersistableFlag(); //noinspection unused int versionStub = readInt(); // TODO: 7/11/17 implement v.2 serialization protocol migration return constructPersistable(); } private Persistable constructPersistable() { Class<? extends Persistable> clazz = persistableRegistry.get(key); Persistable instance = newInstance(clazz); instance.readExternal(this); return instance; } private void checkBytes() { if (bytes.length == 0) { throw new UnsupportedOperationException(String.format(EMPTY_BYTE_ARRAY_MESSAGE, key)); } } private void skipPersistableFlag() { offset++; } private Persistable newInstance(Class<? extends Persistable> clazz) { try { return clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public boolean readBoolean() { int length = booleanSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!booleanSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_BOOLEAN_MESSAGE, flag)); } boolean b = booleanSerializer.deserialize(bytes, offset); offset += length; return b; } @Override public byte readByte() { int length = byteSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!byteSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_BYTE_MESSAGE, flag)); } byte b = byteSerializer.deserialize(bytes, offset); offset += length; return b; } @Override public byte[] readByteArray() { int bytesArraySize = readInt(); if (bytesArraySize == -1) { return null; } int length = byteArraySerializer.bytesLength() + bytesArraySize; checkBounds(length); byte flag = bytes[offset]; if (!byteArraySerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_BYTE_ARRAY_MESSAGE, flag)); } byte[] a = byteArraySerializer.deserialize(bytes, offset, bytesArraySize); offset += length; return a; } @Override public short readShort() { int length = shortSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!shortSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_SHORT_MESSAGE, flag)); } short s = shortSerializer.deserialize(bytes, offset); offset += length; return s; } @Override public char readChar() { int length = charSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!charSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_CHAR_MESSAGE, flag)); } char c = charSerializer.deserialize(bytes, offset); offset += length; return c; } @Override public int readInt() { int length = integerSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!integerSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_INT_MESSAGE, flag)); } int i = integerSerializer.deserialize(bytes, offset); offset += length; return i; } @Override public long readLong() { int length = longSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!longSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_LONG_MESSAGE, flag)); } long l = longSerializer.deserialize(bytes, offset); offset += length; return l; } @Override public float readFloat() { int length = floatSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!floatSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_FLOAT_MESSAGE, flag)); } float f = floatSerializer.deserialize(bytes, offset); offset += length; return f; } @Override public double readDouble() { int length = doubleSerializer.bytesLength(); checkBounds(length); byte flag = bytes[offset]; if (!doubleSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_DOUBLE_MESSAGE, flag)); } double d = doubleSerializer.deserialize(bytes, offset); offset += length; return d; } @Override public String readString() { int bytesStringSize = readInt(); if (bytesStringSize == -1) { return null; } int length = stringSerializer.bytesLength() + bytesStringSize; checkBounds(length); byte flag = bytes[offset]; if (!stringSerializer.isMatches(flag)) { throw new ClassCastException(String.format(INCORRECT_STRING_MESSAGE, flag)); } String s = stringSerializer.deserialize(bytes, offset, bytesStringSize); offset += length; return s; } private void checkBounds(int requiredLength) { int requiredBound = offset + requiredLength; int length = bytes.length; if (requiredBound > length) { throw new ArrayIndexOutOfBoundsException(String.format(OUT_OF_BOUNDS_MESSAGE, key, requiredBound, length)); } } }
/* * Copyright WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer; import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.*; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.apache.synapse.message.processor.MessageProcessor; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.EnableDisableState; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MessageProcessorParameter; import org.wso2.developerstudio.eclipse.gmf.esb.MessageProcessorType; import org.wso2.developerstudio.eclipse.gmf.esb.ProcessorState; import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence.custom.DummyMessageProcessor; /** * Deserializes a message-processor configuration to a graphical message * processor object */ public class MessageProcessorDeserializer extends AbstractEsbNodeDeserializer<MessageProcessor, org.wso2.developerstudio.eclipse.gmf.esb.MessageProcessor> { // Fixing TOOLS-2026. private static final String scheduledMessageForwardingProcessorOld = "org.apache.synapse.message.processors.forward.ScheduledMessageForwardingProcessor"; private static final String messageSamplingProcessorOld = "org.apache.synapse.message.processors.sampler.SamplingProcessor"; private static final String scheduledMessageForwardingProcessor = "org.apache.synapse.message.processor.impl.forwarder.ScheduledMessageForwardingProcessor"; private static final String messageSamplingProcessor = "org.apache.synapse.message.processor.impl.sampler.SamplingProcessor"; @Override public org.wso2.developerstudio.eclipse.gmf.esb.MessageProcessor createNode( IGraphicalEditPart part, MessageProcessor processor) { org.wso2.developerstudio.eclipse.gmf.esb.MessageProcessor messageProcessor = (org.wso2.developerstudio.eclipse.gmf.esb.MessageProcessor) DeserializerUtils .createNode(part, EsbElementTypes.MessageProcessor_3701); setElementToEdit(messageProcessor); if (processor instanceof DummyMessageProcessor) { DummyMessageProcessor dummyMessageProcessor = (DummyMessageProcessor) processor; if (StringUtils.isNotBlank(dummyMessageProcessor.getClassName())) { if (dummyMessageProcessor.getClassName().equals( scheduledMessageForwardingProcessor)) { // Scheduled Message Forwarding Processor executeSetValueCommand(MESSAGE_PROCESSOR__PROCESSOR_TYPE, MessageProcessorType.SCHEDULED_MSG_FORWARDING); Map<String, Object> parameters = dummyMessageProcessor .getParameters(); // Endpoint name. if (StringUtils.isNotBlank(processor.getTargetEndpoint())) { RegistryKeyProperty endpointName = EsbFactory.eINSTANCE .createRegistryKeyProperty(); endpointName.setKeyValue(processor.getTargetEndpoint()); executeSetValueCommand( MESSAGE_PROCESSOR__ENDPOINT_NAME, endpointName); } // Parameters. if (parameters.containsKey("client.retry.interval")) { Object value = parameters.get("client.retry.interval"); if (value != null && StringUtils.isNumeric(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__RETRY_INTERVAL, new Long(value.toString())); } } if (parameters.containsKey("interval")) { Object value = parameters.get("interval"); if (value != null && StringUtils.isNumeric(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__FORWARDING_INTERVAL, new Long(value.toString())); } } if (parameters.containsKey("max.delivery.attempts")) { Object value = parameters.get("max.delivery.attempts"); if (value != null) { try { executeSetValueCommand( MESSAGE_PROCESSOR__MAX_DELIVERY_ATTEMPTS, new Integer(value.toString())); } catch (NumberFormatException e) { // set default value -1 executeSetValueCommand( MESSAGE_PROCESSOR__MAX_DELIVERY_ATTEMPTS, -1); } } } if (parameters.containsKey("axis2.repo")) { Object value = parameters.get("axis2.repo"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__AXIS2_CLIENT_REPOSITORY, value.toString()); } } if (parameters.containsKey("axis2.config")) { Object value = parameters.get("axis2.config"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__AXIS2_CONFIGURATION, value.toString()); } } if (parameters .containsKey("message.processor.reply.sequence")) { Object value = parameters .get("message.processor.reply.sequence"); if (StringUtils.isNotBlank(value.toString())) { RegistryKeyProperty replaySequence = EsbFactory.eINSTANCE .createRegistryKeyProperty(); replaySequence.setKeyValue(value.toString()); executeSetValueCommand( MESSAGE_PROCESSOR__REPLY_SEQUENCE_NAME, replaySequence); } } if (parameters .containsKey("message.processor.fault.sequence")) { Object value = parameters .get("message.processor.fault.sequence"); if (StringUtils.isNotBlank(value.toString())) { RegistryKeyProperty faultSequence = EsbFactory.eINSTANCE .createRegistryKeyProperty(); faultSequence.setKeyValue(value.toString()); executeSetValueCommand( MESSAGE_PROCESSOR__FAULT_SEQUENCE_NAME, faultSequence); } } if (parameters .containsKey("message.processor.deactivate.sequence")) { Object value = parameters .get("message.processor.deactivate.sequence"); if (StringUtils.isNotBlank(value.toString())) { RegistryKeyProperty deactivateSequence = EsbFactory.eINSTANCE .createRegistryKeyProperty(); deactivateSequence.setKeyValue(value.toString()); executeSetValueCommand( MESSAGE_PROCESSOR__DEACTIVATE_SEQUENCE_NAME, deactivateSequence); } } if (parameters.containsKey("quartz.conf")) { Object value = parameters.get("quartz.conf"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__QUARTZ_CONFIG_FILE_PATH, value.toString()); } } if (parameters.containsKey("cronExpression")) { Object value = parameters.get("cronExpression"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__CRON_EXPRESSION, value.toString()); } } if (parameters.containsKey("is.active")) { Object value = parameters.get("is.active"); if (StringUtils.isNotBlank(value.toString())) { if ("true".equals(value)) { executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_STATE, ProcessorState.ACTIVATE); } else { executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_STATE, ProcessorState.DEACTIVATE); } } } if (parameters.containsKey("non.retry.status.codes")) { Object value = parameters.get("non.retry.status.codes"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__NON_RETRY_HTTP_STATUS_CODES, value.toString()); } } if (parameters.containsKey("max.delivery.drop")) { Object value = parameters.get("max.delivery.drop"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__DROP_MESSAGE_AFTER_MAXIMUM_DELIVERY_ATTEMPTS, value.toString()); if ("Enabled".equals(value)) { executeSetValueCommand( MESSAGE_PROCESSOR__DROP_MESSAGE_AFTER_MAXIMUM_DELIVERY_ATTEMPTS, EnableDisableState.ENABLED); } else { executeSetValueCommand( MESSAGE_PROCESSOR__DROP_MESSAGE_AFTER_MAXIMUM_DELIVERY_ATTEMPTS, EnableDisableState.DISABLED); } } } if (parameters.containsKey("member.count")) { Object value = parameters.get("member.count"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__TASK_COUNT, value.toString()); } } } else if (dummyMessageProcessor .getClassName() .equals("org.apache.synapse.message.processor.impl.failover.FailoverScheduledMessageForwardingProcessor")) { // Scheduled Fail over Message Forwarding Processor executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_TYPE, MessageProcessorType.SCHEDULED_FAILOVER_MSG_FORWARDING); Map<String, Object> parameters = dummyMessageProcessor .getParameters(); // Parameters. if (parameters.containsKey("client.retry.interval")) { Object value = parameters.get("client.retry.interval"); if (value != null && StringUtils.isNumeric(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__RETRY_INTERVAL, new Long(value.toString())); } } if (parameters.containsKey("interval")) { Object value = parameters.get("interval"); if (value != null && StringUtils.isNumeric(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__FORWARDING_INTERVAL, new Long(value.toString())); } } if (parameters.containsKey("max.delivery.attempts")) { Object value = parameters.get("max.delivery.attempts"); if (value != null) { try { executeSetValueCommand( MESSAGE_PROCESSOR__MAX_DELIVERY_ATTEMPTS, new Integer(value.toString())); } catch (NumberFormatException e) { // set default value -1 executeSetValueCommand( MESSAGE_PROCESSOR__MAX_DELIVERY_ATTEMPTS, -1); } } } if (parameters .containsKey("message.processor.fault.sequence")) { Object value = parameters .get("message.processor.fault.sequence"); if (StringUtils.isNotBlank(value.toString())) { RegistryKeyProperty faultSequence = EsbFactory.eINSTANCE .createRegistryKeyProperty(); faultSequence.setKeyValue(value.toString()); executeSetValueCommand( MESSAGE_PROCESSOR__FAULT_SEQUENCE_NAME, faultSequence); } } if (parameters .containsKey("message.processor.deactivate.sequence")) { Object value = parameters .get("message.processor.deactivate.sequence"); if (StringUtils.isNotBlank(value.toString())) { RegistryKeyProperty deactivateSequence = EsbFactory.eINSTANCE .createRegistryKeyProperty(); deactivateSequence.setKeyValue(value.toString()); executeSetValueCommand( MESSAGE_PROCESSOR__DEACTIVATE_SEQUENCE_NAME, deactivateSequence); } } if (parameters.containsKey("quartz.conf")) { Object value = parameters.get("quartz.conf"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__QUARTZ_CONFIG_FILE_PATH, value.toString()); } } if (parameters.containsKey("cronExpression")) { Object value = parameters.get("cronExpression"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__CRON_EXPRESSION, value.toString()); } } if (parameters.containsKey("is.active")) { Object value = parameters.get("is.active"); if (StringUtils.isNotBlank(value.toString())) { if ("true".equals(value)) { executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_STATE, ProcessorState.ACTIVATE); } else { executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_STATE, ProcessorState.DEACTIVATE); } } } if (parameters.containsKey("max.delivery.drop")) { Object value = parameters.get("max.delivery.drop"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__DROP_MESSAGE_AFTER_MAXIMUM_DELIVERY_ATTEMPTS, value.toString()); if ("Enabled".equals(value)) { executeSetValueCommand( MESSAGE_PROCESSOR__DROP_MESSAGE_AFTER_MAXIMUM_DELIVERY_ATTEMPTS, EnableDisableState.ENABLED); } else { executeSetValueCommand( MESSAGE_PROCESSOR__DROP_MESSAGE_AFTER_MAXIMUM_DELIVERY_ATTEMPTS, EnableDisableState.DISABLED); } } } if (parameters.containsKey("member.count")) { Object value = parameters.get("member.count"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__TASK_COUNT, value.toString()); } } if (parameters.containsKey("message.target.store.name")) { Object value = parameters .get("message.target.store.name"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__TARGET_MESSAGE_STORE, value.toString()); } } } else if (dummyMessageProcessor.getClassName().equals( messageSamplingProcessor) || dummyMessageProcessor.getClassName().equals( messageSamplingProcessorOld)) { // Message Sampling Processor executeSetValueCommand(MESSAGE_PROCESSOR__PROCESSOR_TYPE, MessageProcessorType.MSG_SAMPLING); Map<String, Object> parameters = dummyMessageProcessor .getParameters(); if (parameters.containsKey("sequence")) { Object value = parameters.get("sequence"); if (StringUtils.isNotBlank(value.toString())) { RegistryKeyProperty sequence = EsbFactory.eINSTANCE .createRegistryKeyProperty(); sequence.setKeyValue(value.toString()); executeSetValueCommand(MESSAGE_PROCESSOR__SEQUENCE, sequence); } } if (parameters.containsKey("interval")) { Object value = parameters.get("interval"); if (value != null && StringUtils.isNumeric(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__SAMPLING_INTERVAL, new Long(value.toString())); } } if (parameters.containsKey("concurrency")) { Object value = parameters.get("concurrency"); if (value != null && StringUtils.isNumeric(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__SAMPLING_CONCURRENCY, new Integer(value.toString())); } } if (parameters.containsKey("quartz.conf")) { Object value = parameters.get("quartz.conf"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__QUARTZ_CONFIG_FILE_PATH, value.toString()); } } if (parameters.containsKey("cronExpression")) { Object value = parameters.get("cronExpression"); if (StringUtils.isNotBlank(value.toString())) { executeSetValueCommand( MESSAGE_PROCESSOR__CRON_EXPRESSION, value.toString()); } } if (parameters.containsKey("is.active")) { Object value = parameters.get("is.active"); if (StringUtils.isNotBlank(value.toString())) { if ("true".equals(value)) { executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_STATE, ProcessorState.ACTIVATE); } else { executeSetValueCommand( MESSAGE_PROCESSOR__PROCESSOR_STATE, ProcessorState.DEACTIVATE); } } } } else { // Custom Message Processor executeSetValueCommand(MESSAGE_PROCESSOR__PROCESSOR_TYPE, MessageProcessorType.CUSTOM); executeSetValueCommand( MESSAGE_PROCESSOR__MESSAGE_PROCESSOR_PROVIDER, dummyMessageProcessor.getClassName()); for (Entry<String, Object> parameter : dummyMessageProcessor .getParameters().entrySet()) { MessageProcessorParameter processorParameter = EsbFactory.eINSTANCE .createMessageProcessorParameter(); processorParameter.setParameterName(parameter.getKey()); processorParameter.setParameterValue(parameter .getValue().toString()); executeAddValueCommand( messageProcessor.getParameters(), processorParameter); } } } } executeSetValueCommand(MESSAGE_PROCESSOR__PROCESSOR_NAME, processor.getName()); executeSetValueCommand(MESSAGE_PROCESSOR__MESSAGE_STORE, processor.getMessageStoreName()); executeSetValueCommand(MESSAGE_PROCESSOR__SOURCE_MESSAGE_STORE, processor.getMessageStoreName()); return messageProcessor; } }
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.event.formatter.core.internal.type.xml; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.databridge.commons.Attribute; import org.wso2.carbon.databridge.commons.StreamDefinition; import org.wso2.carbon.event.formatter.core.config.EventFormatterConfiguration; import org.wso2.carbon.event.formatter.core.config.EventFormatterConstants; import org.wso2.carbon.event.formatter.core.exception.EventFormatterConfigurationException; import org.wso2.carbon.event.formatter.core.exception.EventFormatterProcessingException; import org.wso2.carbon.event.formatter.core.exception.EventFormatterStreamValidationException; import org.wso2.carbon.event.formatter.core.internal.OutputMapper; import org.wso2.carbon.event.formatter.core.internal.ds.EventFormatterServiceValueHolder; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class XMLOutputOutputMapper implements OutputMapper { private static final Log log = LogFactory.getLog(XMLOutputOutputMapper.class); EventFormatterConfiguration eventFormatterConfiguration = null; Map<String, Integer> propertyPositionMap = null; private String outputXMLText = ""; public XMLOutputOutputMapper(EventFormatterConfiguration eventFormatterConfiguration, Map<String, Integer> propertyPositionMap, int tenantId, StreamDefinition streamDefinition) throws EventFormatterConfigurationException { this.eventFormatterConfiguration = eventFormatterConfiguration; this.propertyPositionMap = propertyPositionMap; if (eventFormatterConfiguration.getOutputMapping().isCustomMappingEnabled()) { validateStreamDefinitionWithOutputProperties(tenantId); } else { generateTemplateXMLEvent(streamDefinition); } } private List<String> getOutputMappingPropertyList(String mappingText) { List<String> mappingTextList = new ArrayList<String>(); String text = mappingText; mappingTextList.clear(); while (text.contains(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) && text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX) > 0) { mappingTextList.add(text.substring(text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) + 2, text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX))); text = text.substring(text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX) + 2); } return mappingTextList; } private void validateStreamDefinitionWithOutputProperties(int tenantId) throws EventFormatterConfigurationException { XMLOutputMapping textOutputMapping = ((XMLOutputMapping) eventFormatterConfiguration.getOutputMapping()); String actualMappingText = textOutputMapping.getMappingXMLText(); if (textOutputMapping.isRegistryResource()) { actualMappingText = EventFormatterServiceValueHolder.getCarbonEventFormatterService().getRegistryResourceContent(textOutputMapping.getMappingXMLText(), tenantId); } this.outputXMLText = actualMappingText; List<String> mappingProperties = getOutputMappingPropertyList(actualMappingText); Iterator<String> mappingTextListIterator = mappingProperties.iterator(); for (; mappingTextListIterator.hasNext(); ) { String property = mappingTextListIterator.next(); if (!propertyPositionMap.containsKey(property)) { throw new EventFormatterStreamValidationException("Property " + property + " is not in the input stream definition.", eventFormatterConfiguration.getFromStreamName() + ":" + eventFormatterConfiguration.getFromStreamVersion()); } } } private String getPropertyValue(Object obj, String mappingProperty) { Object[] inputObjArray = (Object[]) obj; if (inputObjArray.length != 0) { int position = propertyPositionMap.get(mappingProperty); Object data = inputObjArray[position]; if (data != null) { return data.toString(); } } return ""; } private OMElement buildOuputOMElement(Object event, OMElement omElement) throws EventFormatterConfigurationException { Iterator<OMElement> iterator = omElement.getChildElements(); if (iterator.hasNext()) { for (; iterator.hasNext(); ) { OMElement childElement = iterator.next(); Iterator<OMAttribute> iteratorAttr = childElement.getAllAttributes(); while (iteratorAttr.hasNext()) { OMAttribute omAttribute = iteratorAttr.next(); String text = omAttribute.getAttributeValue(); if (text != null) { if (text.contains(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) && text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX) > 0) { String propertyToReplace = text.substring(text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) + 2, text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX)); String value = getPropertyValue(event, propertyToReplace); omAttribute.setAttributeValue(value); } } } String text = childElement.getText(); if (text != null) { if (text.contains(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) && text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX) > 0) { String propertyToReplace = text.substring(text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) + 2, text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX)); String value = getPropertyValue(event, propertyToReplace); childElement.setText(value); } } buildOuputOMElement(event, childElement); } } else { String text = omElement.getText(); if (text != null) { if (text.contains(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) && text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX) > 0) { String propertyToReplace = text.substring(text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX) + 2, text.indexOf(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX)); String value = getPropertyValue(event, propertyToReplace); omElement.setText(value); } } } return omElement; } @Override public Object convertToMappedInputEvent(Object[] eventData) throws EventFormatterConfigurationException { if (eventData.length > 0) { try { return buildOuputOMElement(eventData, AXIOMUtil.stringToOM(outputXMLText)); } catch (XMLStreamException e) { throw new EventFormatterConfigurationException("XML mapping is not in XML format :" + outputXMLText, e); } } else { throw new EventFormatterProcessingException("Input Object array is empty!"); } } @Override public Object convertToTypedInputEvent(Object[] eventData) throws EventFormatterConfigurationException { return convertToMappedInputEvent(eventData); } private void generateTemplateXMLEvent(StreamDefinition streamDefinition) { OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement templateEventElement = factory.createOMElement(new QName( EventFormatterConstants.EVENT_PARENT_TAG)); templateEventElement.declareDefaultNamespace(EventFormatterConstants.EVENT_DEFAULT_NAMESPACE); List<Attribute> metaDatAttributes = streamDefinition.getMetaData(); if (metaDatAttributes != null && metaDatAttributes.size() > 0) { templateEventElement.addChild(createPropertyElement(factory, EventFormatterConstants.PROPERTY_META_PREFIX, metaDatAttributes, EventFormatterConstants.EVENT_META_TAG)); } List<Attribute> correlationAttributes = streamDefinition.getCorrelationData(); if (correlationAttributes != null && correlationAttributes.size() > 0) { templateEventElement.addChild(createPropertyElement(factory, EventFormatterConstants.PROPERTY_CORRELATION_PREFIX, correlationAttributes, EventFormatterConstants.EVENT_CORRELATION_TAG)); } List<Attribute> payloadAttributes = streamDefinition.getPayloadData(); if (payloadAttributes != null && payloadAttributes.size() > 0) { templateEventElement.addChild(createPropertyElement(factory, "", payloadAttributes, EventFormatterConstants.EVENT_PAYLOAD_TAG)); } outputXMLText = templateEventElement.toString(); } private static OMElement createPropertyElement(OMFactory factory, String dataPrefix, List<Attribute> attributeList, String propertyTag) { OMElement parentPropertyElement = factory.createOMElement(new QName( propertyTag)); parentPropertyElement.declareDefaultNamespace(EventFormatterConstants.EVENT_DEFAULT_NAMESPACE); for (Attribute attribute : attributeList) { OMElement propertyElement = factory.createOMElement(new QName( attribute.getName())); propertyElement.declareDefaultNamespace(EventFormatterConstants.EVENT_DEFAULT_NAMESPACE); propertyElement.setText(EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_PREFIX + dataPrefix + attribute.getName() + EventFormatterConstants.TEMPLATE_EVENT_ATTRIBUTE_POSTFIX); parentPropertyElement.addChild(propertyElement); } return parentPropertyElement; } }
package org.ovirt.engine.core.common.businessentities; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Size; import org.ovirt.engine.core.common.validation.annotation.ValidName; import org.ovirt.engine.core.common.validation.group.CreateEntity; import org.ovirt.engine.core.common.validation.group.UpdateEntity; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.INotifyPropertyChanged; /** * Quota business entity which reflects the <code>Quota</code> limitations for storage pool. <BR/> * The limitation are separated to two different types * <ul> * <li>General Limitation - Indicates the general limitation of the quota cross all the storage pool</li> * <li>Specific Limitation - Indicates specific limitation of the quota for specific storage or vds group</li> * </ul> * <BR/> * Quota entity encapsulate the specific limitations of the storage pool with lists, general limitations are configured * in the field members.<BR/> * <BR/> * Take in notice there can not be general limitation and specific limitation on the same resource type. */ public class Quota extends IVdcQueryable implements INotifyPropertyChanged, BusinessEntity<Guid> { /** * Automatic generated serial version ID. */ private static final long serialVersionUID = 6637198348072059199L; /** * The quota id. */ private Guid id = new Guid(); /** * The storage pool id the quota is enforced on. */ private Guid storagePoolId; /** * The storage pool name the quota is enforced on, for GUI use. */ private String storagePoolName; /** * The quota name. */ @Size(min = 1, max = BusinessEntitiesDefinitions.QUOTA_NAME_SIZE) @ValidName(message = "VALIDATION.QUOTA.NAME.INVALID", groups = { CreateEntity.class, UpdateEntity.class }) private String quotaName; /** * The quota description. */ @Size(min = 1, max = BusinessEntitiesDefinitions.QUOTA_DESCRIPTION_SIZE) private String description; /** * The threshold of vds group in percentages. */ @Min(0) @Max(100) private int thresholdVdsGroupPercentage; /** * The threshold of storage in percentages. */ @Min(0) @Max(100) private int thresholdStoragePercentage; /** * The grace of vds group in percentages. */ @Min(0) @Max(100) private int graceVdsGroupPercentage; /** * The grace of storage in percentages. */ @Min(0) @Max(100) private int graceStoragePercentage; /** * The global quota vds group limit. */ private QuotaVdsGroup globalQuotaVdsGroup; /** * The global quota storage limit. */ private QuotaStorage globalQuotaStorage; /** * The quota enforcement type. */ private QuotaEnforcementTypeEnum quotaEnforcementType; /** * List of all the specific VdsGroups limitations. */ private List<QuotaVdsGroup> quotaVdsGroupList; /** * List of all the specific storage limitations. */ private List<QuotaStorage> quotaStorageList; /** * Default constructor of Quota, which initialize empty lists for specific limitations, and no user assigned. */ public Quota() { setQuotaStorages(new ArrayList<QuotaStorage>()); setQuotaVdsGroups(new ArrayList<QuotaVdsGroup>()); } /** * @return the quota id. */ public Guid getId() { return id; } /** * @param id * the quota Id to set. */ public void setId(Guid id) { this.id = id; } /** * @return the thresholdVdsGroupPercentage */ public int getThresholdVdsGroupPercentage() { return thresholdVdsGroupPercentage; } /** * @param thresholdVdsGroupPercentage * the thresholdVdsGroupPercentage to set */ public void setThresholdVdsGroupPercentage(int thresholdVdsGroupPercentage) { this.thresholdVdsGroupPercentage = thresholdVdsGroupPercentage; } /** * @return the thresholdStoragePercentage */ public int getThresholdStoragePercentage() { return thresholdStoragePercentage; } /** * @param thresholdStoragePercentage * the thresholdStoragePercentage to set */ public void setThresholdStoragePercentage(int thresholdStoragePercentage) { this.thresholdStoragePercentage = thresholdStoragePercentage; } /** * @return the graceVdsGroupPercentage */ public int getGraceVdsGroupPercentage() { return graceVdsGroupPercentage; } /** * @param graceVdsGroupPercentage * the graceVdsGroupPercentage to set */ public void setGraceVdsGroupPercentage(int graceVdsGroupPercentage) { this.graceVdsGroupPercentage = graceVdsGroupPercentage; } /** * @return the graceStoragePercentage */ public int getGraceStoragePercentage() { return graceStoragePercentage; } /** * @param graceStoragePercentage * the graceStoragePercentage to set */ public void setGraceStoragePercentage(int graceStoragePercentage) { this.graceStoragePercentage = graceStoragePercentage; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the quotaName */ public String getQuotaName() { return quotaName; } /** * @param quotaName * the quotaName to set */ public void setQuotaName(String quotaName) { this.quotaName = quotaName; } /** * @return the storagePoolId */ public Guid getStoragePoolId() { return storagePoolId; } /** * @param storagePoolId * the storagePoolId to set */ public void setStoragePoolId(Guid storagePoolId) { this.storagePoolId = storagePoolId; } /** * @return the storagePoolName */ public String getStoragePoolName() { return storagePoolName; } /** * @param storagePoolName * the storagePoolName to set */ public void setStoragePoolName(String storagePoolName) { this.storagePoolName = storagePoolName; } /** * @return the quotaStorageList */ public List<QuotaStorage> getQuotaStorages() { return quotaStorageList; } /** * @param quotaStorages * the quotaStorages to set */ public void setQuotaStorages(List<QuotaStorage> quotaStorages) { this.quotaStorageList = quotaStorages; } /** * @return the quotaVdsGroups */ public List<QuotaVdsGroup> getQuotaVdsGroups() { return quotaVdsGroupList; } /** * @param quotaVdsGroups * the quotaVdsGroups to set */ public void setQuotaVdsGroups(List<QuotaVdsGroup> quotaVdsGroups) { this.quotaVdsGroupList = quotaVdsGroups; } /** * @return the quotaEnforcementType */ public QuotaEnforcementTypeEnum getQuotaEnforcementType() { return this.quotaEnforcementType; } /** * @param quotaEnforcementType * the quotaEnforcementType to set */ public void setQuotaEnforcementType(QuotaEnforcementTypeEnum quotaEnforcementType) { this.quotaEnforcementType = quotaEnforcementType; } @Override public Object getQueryableId() { return getId(); } /** * @return If this there is a global storage limitation in the quota, returns true. */ public boolean isGlobalStorageQuota() { return globalQuotaStorage != null; } /** * @return If this there is a global vds group limitation in the quota, returns true. */ public boolean isGlobalVdsGroupQuota() { return globalQuotaVdsGroup != null; } /** * @return If the storage quota is empty, returns true. */ public boolean isEmptyStorageQuota() { return globalQuotaStorage == null && (getQuotaStorages() == null || getQuotaStorages().isEmpty()); } /** * @return If the vdsGroup quota is empty, returns true. */ public boolean isEmptyVdsGroupQuota() { return globalQuotaVdsGroup == null && (getQuotaVdsGroups() == null || getQuotaVdsGroups().isEmpty()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((globalQuotaStorage == null) ? 0 : globalQuotaStorage.hashCode()); result = prime * result + ((globalQuotaVdsGroup == null) ? 0 : globalQuotaVdsGroup.hashCode()); result = prime * result + graceStoragePercentage; result = prime * result + graceVdsGroupPercentage; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((quotaName == null) ? 0 : quotaName.hashCode()); result = prime * result + ((quotaStorageList == null) ? 0 : quotaStorageList.hashCode()); result = prime * result + ((quotaVdsGroupList == null) ? 0 : quotaVdsGroupList.hashCode()); result = prime * result + ((storagePoolId == null) ? 0 : storagePoolId.hashCode()); result = prime * result + thresholdStoragePercentage; result = prime * result + thresholdVdsGroupPercentage; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Quota other = (Quota) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (globalQuotaStorage == null) { if (other.globalQuotaStorage != null) return false; } else if (!globalQuotaStorage.equals(other.globalQuotaStorage)) return false; if (globalQuotaVdsGroup == null) { if (other.globalQuotaVdsGroup != null) return false; } else if (!globalQuotaVdsGroup.equals(other.globalQuotaVdsGroup)) return false; if (graceStoragePercentage != other.graceStoragePercentage) return false; if (graceVdsGroupPercentage != other.graceVdsGroupPercentage) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (quotaName == null) { if (other.quotaName != null) return false; } else if (!quotaName.equals(other.quotaName)) return false; if (quotaStorageList == null) { if (other.quotaStorageList != null) return false; } else if (!quotaStorageList.equals(other.quotaStorageList)) return false; if (quotaVdsGroupList == null) { if (other.quotaVdsGroupList != null) return false; } else if (!quotaVdsGroupList.equals(other.quotaVdsGroupList)) return false; if (storagePoolId == null) { if (other.storagePoolId != null) return false; } else if (!storagePoolId.equals(other.storagePoolId)) return false; if (thresholdStoragePercentage != other.thresholdStoragePercentage) return false; if (thresholdVdsGroupPercentage != other.thresholdVdsGroupPercentage) return false; return true; } public QuotaVdsGroup getGlobalQuotaVdsGroup() { return globalQuotaVdsGroup; } public void setGlobalQuotaVdsGroup(QuotaVdsGroup globalQuotaVdsGroup) { this.globalQuotaVdsGroup = globalQuotaVdsGroup; } public QuotaStorage getGlobalQuotaStorage() { return globalQuotaStorage; } public void setGlobalQuotaStorage(QuotaStorage globalQuotaStorage) { this.globalQuotaStorage = globalQuotaStorage; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.trinidadbuild.plugin.faces.parse; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; public class AbstractTagBean extends ObjectBean { private List<String> _accessibilityGuidelines = new ArrayList<String>(); private String _description; private String _longDescription; private QName _tagName; private String _tagClass; protected Map<String, PropertyBean> _properties; private int _tagClassModifiers; private Map<String, ExampleBean> _examples; private int _exampleIdx = 0; private Map<String, ScreenshotBean> _screenshots; private int _screenshotIdx = 0; public AbstractTagBean() { this(false); } public AbstractTagBean(boolean isComponentBean) { // Component Bean does its own thing // with properties. The other bean // types, i.e. Converters and Validators // use the same properties. if (!isComponentBean) { _properties = new LinkedHashMap<String, PropertyBean>(); } _examples = new LinkedHashMap<String, ExampleBean>(); _screenshots = new LinkedHashMap<String, ScreenshotBean>(); } /** * Sets the description of this property. * * @param description the property description */ public void setDescription( String description) { _description = description; } /** * Returns the description of this property. * * @return the property description */ public String getDescription() { return _description; } /** * Sets the long description of this property. * * @param longDescription the long property description */ public void setLongDescription( String longDescription) { _longDescription = longDescription; } /** * Returns the long description of this property. * * @return the long property description */ public String getLongDescription() { return _longDescription; } /** * Sets the JSP tag handler class for this component. * * @param tagClass the JSP tag handler class */ public void setTagClass( String tagClass) { _tagClass = tagClass; } /** * Returns the JSP tag handler class for this component. * * @return the JSP tag handler class */ public String getTagClass() { return _tagClass; } /** * Sets the JSP tag name for this component. * * @param tagName the JSP tag name */ public void setTagName( QName tagName) { _tagName = tagName; } /** * Returns the JSP tag name for this component. * * @return the JSP tag name */ public QName getTagName() { return _tagName; } /** * Adds a property to this component. * * @param property the property to add */ public void addProperty( PropertyBean property) { _properties.put(property.getPropertyName(), property); } /** * Returns the property for this property name. * * @param propertyName the property name to find */ public PropertyBean findProperty( String propertyName) { return _properties.get(propertyName); } /** * Returns true if this component has any properties. * * @return true if this component has any properties, * false otherwise */ public boolean hasProperties() { return !_properties.isEmpty(); } /** * Returns an iterator for all properties on this component only. * * @return the property iterator */ public Iterator<PropertyBean> properties() { return _properties.values().iterator(); } /** * Adds a Example to this component. * * @param example the example to add */ public void addExample( ExampleBean example) { String key = _generateExampleKey(); example.setKey(key); _examples.put(key, example); } /** * Returns true if this component has any examples. * * @return true if this component has any examples, * false otherwise */ public boolean hasExamples() { return !_examples.isEmpty(); } /** * Returns the example for this example key. * * @param key the hashmap example key */ public ExampleBean findExample( String key) { return _examples.get(key); } /** * Returns an iterator for all examples on this component only. * * @return the example iterator */ public Iterator<ExampleBean> examples() { return _examples.values().iterator(); } /** * Adds a Screenshot to this component. * * @param screenshot the screenshot to add */ public void addScreenshot( ScreenshotBean screenshot) { String key = _generateScreenshotKey(); screenshot.setKey(key); _screenshots.put(key, screenshot); } /** * Returns true if this component has any screenshots. * * @return true if this component has any screenshots, * false otherwise */ public boolean hasScreenshots() { return !_screenshots.isEmpty(); } /** * Returns the screenshot for this screenshot key. * * @param key the hashmap screenshot key */ public ScreenshotBean findScreenshot( String key) { return _screenshots.get(key); } /** * Returns an iterator for all screenshots on this component only. * * @return the screenshot iterator */ public Iterator<ScreenshotBean> screenshots() { return _screenshots.values().iterator(); } /** * Adds an Accessibility (e.g. section 508 compliance) Guideline to this component. The * accessibility guidelines are used during tag doc generation to give the application * developer hints on how to configure the component to be accessibility-compliant. * * @param accessibilityGuideline the accessibility guideline to add */ public void addAccessibilityGuideline( String accessibilityGuideline) { _accessibilityGuidelines.add(accessibilityGuideline); } /** * Returns true if this component has any accessibility guidelines. * * @return true if this component has any accessibility guidelines, * false otherwise */ public boolean hasAccessibilityGuidelines() { return !_accessibilityGuidelines.isEmpty(); } /** * Returns an iterator for all accessibility guidelines on this component only. * * @return the accessibility guidelines iterator */ public Iterator<String> accessibilityGuidelines() { return _accessibilityGuidelines.iterator(); } public void parseTagClassModifier( String modifier) { addTagClassModifier(_parseModifier(modifier)); } protected int _parseModifier( String text) { if ("public".equals(text)) return Modifier.PUBLIC; else if ("protected".equals(text)) return Modifier.PROTECTED; else if ("private".equals(text)) return Modifier.PRIVATE; else if ("abstract".equals(text)) return Modifier.ABSTRACT; else if ("final".equals(text)) return Modifier.FINAL; throw new IllegalArgumentException("Unrecognized modifier: " + text); } /** * Adds a Java Language class modifier to the tag class. * * @param modifier the modifier to be added */ public void addTagClassModifier( int modifier) { _tagClassModifiers |= modifier; } /** * Returns the Java Language class modifiers for the tag class. * By default, these modifiers include Modifier.PUBLIC. * * @return the Java Language class modifiers for the tag class */ public int getTagClassModifiers() { int modifiers = _tagClassModifiers; if (!Modifier.isPrivate(modifiers) && !Modifier.isProtected(modifiers) && !Modifier.isPublic(modifiers)) { modifiers |= Modifier.PUBLIC; } return modifiers; } /** * Number of properties for this component * @return num of properties */ public int propertiesSize() { return _properties.size(); } /* Get a generated key to use in storing * this example bean in its hashmap. */ private String _generateExampleKey() { String key = "Example" + Integer.toString(_exampleIdx); _exampleIdx++; return key; } /* Get a generated key to use in storing * this screen shot bean in its hashmap. */ private String _generateScreenshotKey() { String key = "Screenshot" + Integer.toString(_screenshotIdx); _screenshotIdx++; return key; } }
package org.marketcetera.photon.ui; import java.text.Collator; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Widget; import org.marketcetera.core.MMapEntry; import org.marketcetera.photon.Messages; import ca.odell.glazedlists.EventList; import ca.odell.glazedlists.gui.AdvancedTableFormat; import ca.odell.glazedlists.gui.WritableTableFormat; public abstract class MapEditor extends FieldEditor implements Messages /*implements IElementChangeListener<MMapEntry<String, String>> */ { /** * The list widget; <code>null</code> if none * (before creation or after disposal). */ private Table table; private IndexedTableViewer tableViewer; /** * The button box containing the Add, Remove, Up, and Down buttons; * <code>null</code> if none (before creation or after disposal). */ private Composite buttonBox; /** * The Add button. */ private Button addButton; /** * The Remove button. */ private Button removeButton; /** * The Up button. */ private Button upButton; /** * The Down button. */ private Button downButton; /** * The selection listener. */ private SelectionListener selectionListener; EventList<Map.Entry<String, String>> entries; /** * Creates a new list field editor */ protected MapEditor() { } /** * Creates a list field editor. * * @param name the name of the preference this field editor works on * @param labelText the label text of the field editor * @param parent the parent of the field edMapFieldEditortrol */ protected MapEditor(String name, String labelText, Composite parent) { init(name, labelText); createControl(parent); } protected boolean isDuplicateKeyAllowed() { return true; } /** * Notifies that the Add button has been pressed. */ private void addPressed() { setPresentsDefaultValue(false); Entry<String, String> input = getNewInputObject(); if (input != null) { if (isDuplicateKeyAllowed() || !hasEntryKey(input.getKey())) { int index = table.getSelectionIndex(); if (index >= 0) { entries.add(index + 1, input); } else { entries.add(0, input); } selectionChanged(); } } } /* * (non-Javadoc) Method declared on FieldEditor. */ protected void adjustForNumColumns(int numColumns) { Control control = getLabelControl(); ((GridData) control.getLayoutData()).horizontalSpan = numColumns; ((GridData) table.getLayoutData()).horizontalSpan = numColumns - 1; } /** * Creates the Add, Remove, Up, and Down button in the given button box. * * @param box the box for the buttons */ private void createButtons(Composite box) { addButton = createPushButton(box, "Add");//$NON-NLS-1$ removeButton = createPushButton(box, "Remove");//$NON-NLS-1$ if(includeUpDownButtons()) { upButton = createPushButton(box, "Up");//$NON-NLS-1$ downButton = createPushButton(box, "Down");//$NON-NLS-1$ } } /** * Combines the given list of items into a single string. * This method is the converse of <code>parseString</code>. * <p> * Subclasses must implement this method. * </p> * * @param entries the list of items * @return the combined string * @see #parseString */ protected abstract String createMap(EventList<Map.Entry<String, String>> entries); /** * Indicates if the up and down buttons should be included or omitted from the dialog. * * @return a <code>boolean</code> value */ protected boolean includeUpDownButtons() { return true; } /** * Helper method to create a push button. * * @param parent the parent control * @param key the resource name used to supply the button's label text * @return Button */ private Button createPushButton(Composite parent, String key) { Button button = new Button(parent, SWT.PUSH); button.setText(JFaceResources.getString(key)); button.setFont(parent.getFont()); GridData data = new GridData(GridData.FILL_HORIZONTAL); int widthHint = convertHorizontalDLUsToPixels(button, IDialogConstants.BUTTON_WIDTH); data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); button.setLayoutData(data); button.addSelectionListener(getSelectionListener()); return button; } /** * Creates a selection listener. */ public void createSelectionListener() { selectionListener = new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { Widget widget = event.widget; if (widget == addButton) { addPressed(); } else if (widget == removeButton) { removePressed(); } else if (widget == upButton) { upPressed(); } else if (widget == downButton) { downPressed(); } else if (widget == table) { selectionChanged(); } } }; } /* (non-Javadoc) * Method declared on FieldEditor. */ protected void doFillIntoGrid(Composite parent, int numColumns) { Control control = getLabelControl(parent); GridData gd = new GridData(); gd.horizontalSpan = numColumns; control.setLayoutData(gd); table = getTableControl(parent); gd = new GridData(GridData.FILL_HORIZONTAL); gd.verticalAlignment = GridData.FILL; gd.horizontalSpan = numColumns - 1; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; table.setLayoutData(gd); createTableViewer(); buttonBox = getButtonBoxControl(parent); gd = new GridData(); gd.verticalAlignment = GridData.BEGINNING; buttonBox.setLayoutData(gd); } /* (non-Javadoc) * Method declared on FieldEditor. */ protected void doLoad() { if (table != null) { String s = getPreferenceStore().getString(getPreferenceName()); entries = parseString(s); tableViewer.setInput(entries); } } /* (non-Javadoc) * Method declared on FieldEditor. */ protected void doLoadDefault() { if (table != null) { table.removeAll(); String s = getPreferenceStore().getDefaultString( getPreferenceName()); entries = parseString(s); tableViewer.setInput(entries); } } private boolean hasEntryKey(String entryKey) { if( entryKey == null || entries == null ) { return false; } for( Map.Entry<String, String> entry : entries ) { if( entry != null ) { String key = entry.getKey(); if( entryKey.equals(key)) { return true; } } } return false; } /* (non-Javadoc) * Method declared on FieldEditor. */ @SuppressWarnings("unchecked") //$NON-NLS-1$ protected void doStore() { EventList<Map.Entry<String, String>> items = (EventList<Map.Entry<String, String>>) tableViewer.getInput(); String s = createMap(items); if (s != null) { getPreferenceStore().setValue(getPreferenceName(), s); } } /** * Notifies that the Down button has been pressed. */ private void downPressed() { swap(false); } /** * Returns this field editor's button box containing the Add, Remove, * Up, and Down button. * * @param parent the parent control * @return the button box */ public Composite getButtonBoxControl(Composite parent) { if (buttonBox == null) { buttonBox = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.marginWidth = 0; buttonBox.setLayout(layout); createButtons(buttonBox); buttonBox.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { addButton = null; removeButton = null; upButton = null; downButton = null; buttonBox = null; } }); } else { checkParent(buttonBox, parent); } selectionChanged(); return buttonBox; } /** * Returns this field editor's list control. * * @param parent the parent control * @return the list control */ public Table getTableControl(Composite parent) { if (table == null) { table = new Table(parent, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION ); table.setHeaderVisible(false); table.setFont(parent.getFont()); table.addSelectionListener(getSelectionListener()); table.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { table = null; } }); table.setHeaderVisible(true); // 2nd column with task Description TableColumn column; column = new TableColumn(table, SWT.LEFT); column.setText(KEY_LABEL.getText()); column.setWidth(100); column = new TableColumn(table, SWT.LEFT); column.setText(VALUE_LABEL.getText()); column.setWidth(100); } else { checkParent(table, parent); } return table; } /** * Create the TableViewer */ private void createTableViewer() { tableViewer = new IndexedTableViewer(table); tableViewer.setUseHashlookup(true); String[] columnNames = new String[] { KEY_LABEL.getText(), VALUE_LABEL.getText() }; tableViewer.setColumnProperties(columnNames); // Create the cell editors CellEditor[] editors = new CellEditor[columnNames.length]; editors[0] = null; editors[1] = new TextCellEditor(table); // Assign the cell editors to the viewer //tableViewer.setCellEditors(editors); // Set the cell modifier for the viewer //tableViewer.setCellModifier(new BeanCellModifier<MMapEntry<String,String>>(this)); tableViewer.setContentProvider(new EventListContentProvider<Map.Entry<String,String>>()); tableViewer.setLabelProvider(new MapEntryLabelProvider()); } // public void elementChanged(MMapEntry<String, String> element) { // tableViewer.update(element, null); // } protected ITableLabelProvider getTableLabelProvider(){ return new ITableLabelProvider(){ public Image getColumnImage(Object element, int columnIndex) { return null; } @SuppressWarnings("unchecked") //$NON-NLS-1$ public String getColumnText(Object element, int columnIndex) { return (element instanceof Map.Entry) ? columnIndex == 1 ? ((Map.Entry<String,String>)element).getKey() : ((Map.Entry<String,String>)element).getValue() : null; } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } }; } /** * Creates and returns a new item for the list. * <p> * Subclasses must implement this method. * </p> * * @return a new item */ protected abstract Entry<String, String> getNewInputObject(); /* (non-Javadoc) * Method declared on FieldEditor. */ public int getNumberOfControls() { return 2; } /** * Returns this field editor's selection listener. * The listener is created if nessessary. * * @return the selection listener */ private SelectionListener getSelectionListener() { if (selectionListener == null) { createSelectionListener(); } return selectionListener; } /** * Returns this field editor's shell. * <p> * This method is internal to the framework; subclassers should not call * this method. * </p> * * @return the shell */ protected Shell getShell() { if (addButton == null) { return null; } return addButton.getShell(); } /** * Splits the given string into a list of strings. * This method is the converse of <code>createList</code>. * <p> * Subclasses must implement this method. * </p> * * @param stringList the string * @return an array of <code>String</code> */ protected abstract EventList<Map.Entry<String, String>> parseString(String stringList); /** * Notifies that the Remove button has been pressed. */ protected int removePressed() { setPresentsDefaultValue(false); int index = table.getSelectionIndex(); if (index >= 0) { //table.remove(index); entries.remove(index); selectionChanged(); } return index; } /** * Notifies that the list selection has changed. */ private void selectionChanged() { int index = table.getSelectionIndex(); int size = table.getItemCount(); removeButton.setEnabled(index >= 0); if(includeUpDownButtons()) { upButton.setEnabled(size > 1 && index > 0); downButton.setEnabled(size > 1 && index >= 0 && index < size - 1); } } /* (non-Javadoc) * Method declared on FieldEditor. */ public void setFocus() { if (table != null) { table.setFocus(); } } /** * Moves the currently selected item up or down. * * @param up <code>true</code> if the item should move up, * and <code>false</code> if it should move down */ @SuppressWarnings("unchecked") //selections are untyped //$NON-NLS-1$ private void swap(boolean up) { setPresentsDefaultValue(false); int index = table.getSelectionIndex(); int target = up ? index - 1 : index + 1; if (index >= 0) { TableItem[] selection = table.getSelection(); Entry<String, String> toReplace = (Entry<String, String>) selection[0].getData(); entries.remove(index); entries.add(target, toReplace); table.setSelection(target); } selectionChanged(); } /** * Notifies that the Up button has been pressed. */ private void upPressed() { swap(true); } /* * @see FieldEditor.setEnabled(boolean,Composite). */ public void setEnabled(boolean enabled, Composite parent) { super.setEnabled(enabled, parent); getTableControl(parent).setEnabled(enabled); addButton.setEnabled(enabled); removeButton.setEnabled(enabled); if(includeUpDownButtons()) { upButton.setEnabled(enabled); downButton.setEnabled(enabled); } } protected class MapTableFormat implements WritableTableFormat<Object>, AdvancedTableFormat<Object>{ public static final int KEY_COLUMN = 0; public static final int VALUE_COLUMN = 1; public boolean isEditable(Object arg0, int arg1) { return true; } @SuppressWarnings("unchecked") //$NON-NLS-1$ public Object setColumnValue(Object baseObject, Object editedValue, int column) { switch (column) { case KEY_COLUMN: return new MMapEntry<String, String>((String) editedValue, ((Map.Entry<String, String>) baseObject).getValue()); case VALUE_COLUMN: ((MMapEntry<String, String>) baseObject) .setValue(((String) editedValue)); return baseObject; default: return null; } } public int getColumnCount() { return 2; } public String getColumnName(int column) { switch(column){ case KEY_COLUMN: return KEY_LABEL.getText(); case VALUE_COLUMN: return VALUE_LABEL.getText(); default: return null; } } @SuppressWarnings("unchecked") //$NON-NLS-1$ public Object getColumnValue(Object obj, int column) { switch(column){ case KEY_COLUMN: return ((Map.Entry<String, String>)obj).getKey(); case VALUE_COLUMN: return ((Map.Entry<String, String>)obj).getValue(); default: return null; } } public Class<?> getColumnClass(int arg0) { return String.class; } public Comparator<?> getColumnComparator(int arg0) { return Collator.getInstance(); } } }
package com.hockeyhurd.hcorelib.mod.client.gui; import com.hockeyhurd.hcorelib.api.math.expressions.Expression; import com.hockeyhurd.hcorelib.api.math.expressions.GlobalConstants; import com.hockeyhurd.hcorelib.api.math.expressions.Interpreter; import com.hockeyhurd.hcorelib.api.math.expressions.InterpreterResult; import com.hockeyhurd.hcorelib.mod.ClientProxy; import com.hockeyhurd.hcorelib.mod.HCoreLibMain; import com.hockeyhurd.hcorelib.mod.common.ModRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; import java.util.HashMap; import java.util.Map; /** * Gui interface for ItemCalculator. * * @author hockeyhurd * @version 11/10/16 */ @SideOnly(Side.CLIENT) public final class GuiCalculator extends GuiScreen { private static final ResourceLocation texture = new ResourceLocation(HCoreLibMain.assetDir, "textures/gui/GuiCalculator.png"); private int xSize, ySize; private int guiLeft, guiTop; private String drawString; private char[] drawBuffer; private int charIndex; private GuiButton[] numPad; private GuiButton deleteButton, clearButton; private Map<String, GuiButton> buttonMap; private MemoryBuffer memoryBuffer; private InterpreterResult lastResult; public GuiCalculator() { this.xSize = 248; this.ySize = 166; this.drawBuffer = new char[0x20]; this.charIndex = 0; this.drawString = ""; buttonMap = new HashMap<String, GuiButton>(); memoryBuffer = new MemoryBuffer(); } @Override public void initGui() { super.initGui(); final ItemStack calcStack = mc.player.getHeldItem(EnumHand.MAIN_HAND); if (calcStack != null && calcStack.getCount() > 0 && calcStack.getItem() == ModRegistry.ModItems.itemCalculator.getItem().getItem()) { NBTTagCompound comp = calcStack.getTagCompound(); if (comp != null) { drawString = comp.getString("CalculatorInput"); charIndex = comp.getInteger("CalculatorInputCharCount"); memoryBuffer.store(comp.getDouble("CalculatorMemoryBuffer")); if (lastResult == null) lastResult = new InterpreterResult(); lastResult.updateResult(comp.getString("CalculatorLastResultString"), comp.getDouble("CalculatorLastResult")); // comp.setDouble("CalculatorMemoryBuffer", memoryBuffer.read()); // comp.setDouble("CalculatorLastResult", lastResult.getResult()); // comp.setString("CalculatorLastResultString", lastResult.getExpressionString()); for (int i = 0; i < charIndex; i++) drawBuffer[i] = drawString.charAt(i); } } this.guiLeft = (this.width - this.xSize) >> 1; this.guiTop = (this.height - this.ySize) >> 1; // if (numPad == null) numPad = new GuiButton[9]; if (numPad == null) numPad = new GuiButton[12]; // final int bw = xSize / 10; // final int bh = ySize / 10; final int bw = 0x14; final int bh = 0x14; for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { GuiButton button = new GuiButton(x + y * 3, guiLeft + ((x + 1) * (bw + 4)) + (bw >> 1), height - guiTop - ((4 - y) * (bh + 4)) - (bh >> 2), bw, bh, Integer.toString(1 + x + y * 3)); numPad[x + y * 3] = button; buttonList.add(button); } } numPad[9] = new GuiButton(9, numPad[6].x, numPad[6].y + bh + 4, bw, bh, "("); numPad[10] = new GuiButton(10, numPad[7].x, numPad[7].y + bh + 4, bw, bh, Integer.toString(0)); numPad[11] = new GuiButton(11, numPad[8].x, numPad[8].y + bh + 4, bw, bh, ")"); buttonList.add(numPad[9]); buttonList.add(numPad[10]); buttonList.add(numPad[11]); clearButton = new GuiButton(buttonList.size(), numPad[0].x - bw - 4, numPad[4].y, bw, bh, "C"); buttonList.add(clearButton); deleteButton = new GuiButton(buttonList.size(), clearButton.x, numPad[1].y, bw, bh, "<-"); buttonList.add(deleteButton); GuiButton bufferButton; // equalsButtons = new GuiButton(buttonList.size(), numPad[11].xPosition + bw + 4, numPad[11].yPosition, bw, bh, "="); // buttonList.add(equalsButtons); buttonMap.put("=", new GuiButton(buttonList.size(), clearButton.x, numPad[7].y, bw, bh, "=")); buttonMap.put(".", new GuiButton(buttonList.size(), clearButton.x, numPad[11].y, bw, bh, ".")); buttonMap.put("+", new GuiButton(buttonList.size(), numPad[11].x + bw + 4, numPad[11].y, bw, bh, "+")); buttonMap.put("-", new GuiButton(buttonList.size(), numPad[8].x + bw + 4, numPad[8].y, bw, bh, "-")); buttonMap.put("*", new GuiButton(buttonList.size(), numPad[5].x + bw + 4, numPad[5].y, bw, bh, "*")); buttonMap.put("/", new GuiButton(buttonList.size(), numPad[2].x + bw + 4, numPad[2].y, bw, bh, "/")); buttonMap.put("M+", bufferButton = new GuiButton(buttonList.size(), numPad[11].x + (bw + 4 << 1), numPad[11].y, bw, bh, "M+")); buttonMap.put("M-", new GuiButton(buttonList.size(), numPad[8].x + (bw + 4 << 1), numPad[8].y, bw, bh, "M-")); buttonMap.put("M*", new GuiButton(buttonList.size(), numPad[5].x + (bw + 4 << 1), numPad[5].y, bw, bh, "M*")); buttonMap.put("M/", new GuiButton(buttonList.size(), numPad[2].x + (bw + 4 << 1), numPad[2].y, bw, bh, "M/")); buttonMap.put("MC", new GuiButton(buttonList.size(), numPad[0].x, numPad[0].y - bh - 4, bw, bh, "MC")); buttonMap.put("MR", new GuiButton(buttonList.size(), numPad[1].x, numPad[1].y - bh - 4, bw, bh, "MR")); buttonMap.put("MS", new GuiButton(buttonList.size(), numPad[2].x, numPad[2].y - bh - 4, bw, bh, "MS")); buttonMap.put("^", new GuiButton(buttonList.size(), numPad[2].x + bw + 4, numPad[2].y - bh - 4, bw, bh, "^")); buttonMap.put("" + GlobalConstants.SQ_ROOT_CHAR, new GuiButton(buttonList.size(), numPad[2].x + (bw + 4 << 1), numPad[2].y - bh - 4, bw, bh, "" + GlobalConstants.SQ_ROOT_CHAR)); buttonMap.put("e", bufferButton = new GuiButton(buttonList.size(), bufferButton.x + bw + 4, numPad[11].y, bw, bh, "e")); buttonMap.put("" + GlobalConstants.PI_CHAR, new GuiButton(buttonList.size(), bufferButton.x, numPad[8].y, bw, bh, "" + GlobalConstants.PI_CHAR)); for (GuiButton button : buttonMap.values()) { button.id = buttonList.size(); buttonList.add(button); } } @Override public void onGuiClosed() { super.onGuiClosed(); final ItemStack calcStack = mc.player.getHeldItem(EnumHand.MAIN_HAND); if (calcStack != null && calcStack.getCount() > 0 && calcStack.getItem() == ModRegistry.ModItems.itemCalculator.getItem().getItem()) { NBTTagCompound comp = calcStack.getTagCompound(); if (comp == null) calcStack.setTagCompound((comp = new NBTTagCompound())); comp.setString("CalculatorInput", drawString); comp.setInteger("CalculatorInputCharCount", charIndex); comp.setDouble("CalculatorMemoryBuffer", memoryBuffer.read()); if (lastResult != null) { comp.setDouble("CalculatorLastResult", lastResult.getResult()); comp.setString("CalculatorLastResultString", lastResult.getExpressionString()); } else { comp.setDouble("CalculatorLastResult", 0.0d); comp.setString("CalculatorLastResultString", "0.0"); } } } public void drawGuiContainerForegroundLayer(int x, int y) { // fontRendererObj.drawString(drawString, xSize - (width >> 1) - 8, guiTop, 0xffffffff); fontRenderer.drawString(drawString, (xSize >> 3) - (fontRenderer.getStringWidth("00") >> 1), (ySize >> 3), 0xffffffff); } public void drawGuiContainerBackgroundLayer(float f, int x, int y) { GL11.glColor4f(1f, 1f, 1f, 1f); Minecraft.getMinecraft().getTextureManager().bindTexture(texture); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); /*final int size = fontRendererObj.getCharWidth('0'); drawRect(guiLeft + xSize - (width >> 1) - (size >> 1) - 8, (guiTop << 1) - (size >> 1), size * 53 - 8, ((guiTop << 1) + (size << 1)) - (size >> 1), 0xff000000);*/ } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); int i = this.guiLeft; int j = this.guiTop; this.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); GlStateManager.disableRescaleNormal(); GlStateManager.disableLighting(); GlStateManager.disableDepth(); super.drawScreen(mouseX, mouseY, partialTicks); GlStateManager.pushMatrix(); GlStateManager.translate((float) i, (float) j, 0.0F); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.enableRescaleNormal(); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0F, 240.0F); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.drawGuiContainerForegroundLayer(mouseX, mouseY); GlStateManager.popMatrix(); GlStateManager.enableLighting(); GlStateManager.enableDepth(); } @Override public void actionPerformed(GuiButton button) { // Is num key: if (button.id < numPad.length || (!button.displayString.equals("=") && !button.displayString.startsWith("M") && !button.displayString.startsWith("\u221A") && buttonMap.containsKey(button.displayString))) { if (charIndex < drawBuffer.length) { // drawBuffer[charIndex++] = (char) ('0' + button.id + 1); drawBuffer[charIndex++] = button.displayString.charAt(0); drawString = new String(drawBuffer); } } else if (button.id == clearButton.id) { for (int i = 0; i < charIndex; i++) drawBuffer[i] = 0; charIndex = 0; drawString = ""; } else if (button.id == deleteButton.id) { if (charIndex > 0) { drawBuffer[--charIndex] = 0; drawString = new String(drawBuffer); } } // else if (button.id == equalsButtons.id) { else if (button.id == buttonMap.get("=").id) { // if (drawString.contains("=")) return; Interpreter interpreter = new Interpreter(); lastResult = interpreter.processExpressionString(new Expression(drawString.substring(0, charIndex)), ClientProxy.getPlayer().getUniqueID().hashCode()); if (!lastResult.isEmpty()) { // drawString = lastResult.getExpressionString(); drawString = Double.toString(lastResult.getResult()); charIndex = drawString.length(); syncStringBuffer(); } } else if (button.displayString.startsWith("\u221A")) { drawBuffer[charIndex++] = '^'; drawBuffer[charIndex++] = '('; drawBuffer[charIndex++] = '1'; drawBuffer[charIndex++] = '/'; drawBuffer[charIndex++] = '2'; drawBuffer[charIndex++] = ')'; drawString = new String(drawBuffer); } else if (button.displayString.startsWith("M")) { final char secondChar = button.displayString.charAt(1); final double lastValue = lastResult != null ? lastResult.getResult() : 0.0d; switch (secondChar) { case '+': memoryBuffer.add(lastValue); break; case '-': memoryBuffer.subtract(lastValue); break; case '*': memoryBuffer.multiply(lastValue); break; case '/': if (lastValue != 0.0d) memoryBuffer.divide(lastValue); break; case 'C': memoryBuffer.clear(); break; case 'R': drawString = Double.toString(memoryBuffer.read()); charIndex = drawString.length(); syncStringBuffer(); break; case 'S': memoryBuffer.store(lastValue); break; default: } } } /** * Synchronizes the drawBuffer with the drawString. */ private void syncStringBuffer() { if (drawString == null || drawString.isEmpty()) return; int i; for (i = 0; i < drawString.length(); i++) drawBuffer[i] = drawString.charAt(i); for ( ; i < drawBuffer.length; i++) drawBuffer[i] = '\0'; } /** * Static class for storing values and emulating the * memory buffer function of calculators. * * @author hockeyhurd * @version 12/19/16 */ private static class MemoryBuffer { private double value; MemoryBuffer() { this(0.0d); } MemoryBuffer(double value) { if (value != Double.NaN) this.value = value; } void add(double value) { if (value != Double.NaN) this.value += value; } void subtract(double value) { if (value != Double.NaN) this.value -= value; } void multiply(double value) { if (value != Double.NaN) this.value *= value; } void divide(double value) { if (value != Double.NaN) this.value /= value; } void store(double value) { if (value != Double.NaN) this.value = value; } double read() { return value; } void clear() { value = 0.0d; } } }
package com.evolveum.midpoint.web.page.login; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.Validate; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.string.StringValue; import org.springframework.security.core.AuthenticationException; import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.model.api.context.NonceAuthenticationContext; import com.evolveum.midpoint.prism.delta.ContainerDelta; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.security.api.ConnectionEnvironment; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.Producer; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.application.PageDescriptor; import com.evolveum.midpoint.web.application.Url; import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.NonceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; //CONFIRMATION_LINK = "http://localhost:8080/midpoint/confirm/registration/"; @PageDescriptor(urls = {@Url(mountUrl = SchemaConstants.REGISTRATION_CONFIRAMTION_PREFIX)}, permitAll = true) public class PageRegistrationConfirmation extends PageRegistrationBase { private static final Trace LOGGER = TraceManager.getTrace(PageRegistrationConfirmation.class); private static final String DOT_CLASS = PageRegistrationConfirmation.class.getName() + "."; private static final String ID_LABEL_SUCCESS = "successLabel"; private static final String ID_LABEL_ERROR = "errorLabel"; private static final String ID_LINK_LOGIN = "linkToLogin"; private static final String ID_SUCCESS_PANEL = "successPanel"; private static final String ID_ERROR_PANEL = "errorPanel"; private static final String OPERATION_ASSIGN_DEFAULT_ROLES = DOT_CLASS + ".assignDefaultRoles"; private static final String OPERATION_FINISH_REGISTRATION = DOT_CLASS + "finishRegistration"; private static final long serialVersionUID = 1L; public PageRegistrationConfirmation() { super(); init(null); } public PageRegistrationConfirmation(PageParameters params) { super(); init(params); } private void init(final PageParameters pageParameters) { PageParameters params = pageParameters; if (params == null) { params = getPageParameters(); } OperationResult result = new OperationResult(OPERATION_FINISH_REGISTRATION); if (params == null) { LOGGER.error("Confirmation link is not valid. No credentials provided in it"); String msg = createStringResource("PageSelfRegistration.invalid.registration.link").getString(); getSession().error(createStringResource(msg)); result.recordFatalError(msg); initLayout(result); return; } StringValue userNameValue = params.get(SchemaConstants.USER_ID); Validate.notEmpty(userNameValue.toString()); StringValue tokenValue = params.get(SchemaConstants.TOKEN); Validate.notEmpty(tokenValue.toString()); UserType userType = checkUserCredentials(userNameValue.toString(), tokenValue.toString(), result); if (userType == null) { initLayout(result); return; } result = assignDefaultRoles(userType.getOid()); if (result.getStatus() == OperationResultStatus.FATAL_ERROR) { LOGGER.error("Failed to assign default roles, {}", result.getMessage()); initLayout(result); return; } final NonceType nonceClone = userType.getCredentials().getNonce().clone(); result = removeNonce(userType.getOid(), nonceClone); result = assignAdditionalRoleIfPresent(userType.getOid(), nonceClone, result); initLayout(result); } // private UsernamePasswordAuthenticationToken authenticateUser(String username, String nonce, OperationResult result){ // ConnectionEnvironment connEnv = new ConnectionEnvironment(); // connEnv.setChannel(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI); // try { // return getAuthenticationEvaluator().authenticate(connEnv, new NonceAuthenticationContext( username, // nonce, getSelfRegistrationConfiguration().getNoncePolicy())); // } catch (AuthenticationException ex) { // getSession() // .error(getString(ex.getMessage())); // result.recordFatalError("Failed to validate user"); // LoggingUtils.logException(LOGGER, ex.getMessage(), ex); // return null; // } catch (Exception ex) { // getSession() // .error(createStringResource("PageRegistrationConfirmation.authnetication.failed").getString()); // LoggingUtils.logException(LOGGER, "Failed to confirm registration", ex); // return null; // } // } private UserType checkUserCredentials(String username, String nonce, OperationResult result) { ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI); try { return getAuthenticationEvaluator().checkCredentials(connEnv, new NonceAuthenticationContext( username, nonce, getSelfRegistrationConfiguration().getNoncePolicy())); } catch (AuthenticationException ex) { getSession() .error(getString(ex.getMessage())); result.recordFatalError("Failed to validate user"); LoggingUtils.logException(LOGGER, ex.getMessage(), ex); return null; } catch (Exception ex) { getSession() .error(createStringResource("PageRegistrationConfirmation.authnetication.failed").getString()); LoggingUtils.logException(LOGGER, "Failed to confirm registration", ex); return null; } } private OperationResult assignDefaultRoles(final String userOid){ List<ContainerDelta<AssignmentType>> assignments = new ArrayList<>(); for (ObjectReferenceType defaultRole : getSelfRegistrationConfiguration().getDefaultRoles()) { AssignmentType assignment = new AssignmentType(); assignment.setTargetRef(defaultRole); try { getPrismContext().adopt(assignment); assignments.add(ContainerDelta.createModificationAdd(UserType.F_ASSIGNMENT, UserType.class, getPrismContext(), assignment)); } catch (SchemaException e) { //nothing to do } } final ObjectDelta<UserType> delta = ObjectDelta.createModifyDelta(userOid, assignments, UserType.class, getPrismContext()); return runPrivileged(new Producer<OperationResult>() { @Override public OperationResult run() { OperationResult result = new OperationResult(OPERATION_ASSIGN_DEFAULT_ROLES); Task task = createAnonymousTask(OPERATION_ASSIGN_DEFAULT_ROLES); WebModelServiceUtils.save(delta, result, task, PageRegistrationConfirmation.this); result.computeStatusIfUnknown(); return result; } }); } private OperationResult removeNonce(final String userOid, final NonceType nonce){ return runPrivileged(() -> { OperationResult result = new OperationResult("assignDefaultRoles"); Task task = createAnonymousTask("assignDefaultRoles"); ObjectDelta<UserType> userAssignmentsDelta; try { userAssignmentsDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, userOid, new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_NONCE), getPrismContext(), nonce); userAssignmentsDelta.addModificationReplaceProperty(UserType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_ACTIVE); } catch (SchemaException e) { result.recordFatalError("Could not create delta"); LOGGER.error("Could not prepare delta for removing nonce and lyfecycle state {}", e.getMessage()); return result; } WebModelServiceUtils.save(userAssignmentsDelta, result, task, PageRegistrationConfirmation.this); result.computeStatusIfUnknown(); return result; }); } private OperationResult assignAdditionalRoleIfPresent(String userOid, NonceType nonceType, OperationResult result){ // SecurityContextHolder.getContext().setAuthentication(token); return runPrivileged(() -> { List<ItemDelta> userDeltas = new ArrayList<>(); if (nonceType.getName() != null) { Task task = createAnonymousTask(OPERATION_FINISH_REGISTRATION); ObjectDelta<UserType> assignRoleDelta = null; try { AssignmentType assignment = new AssignmentType(); assignment.setTargetRef( ObjectTypeUtil.createObjectRef(nonceType.getName(), ObjectTypes.ABSTRACT_ROLE)); getPrismContext().adopt(assignment); userDeltas.add((ItemDelta) ContainerDelta.createModificationAdd(UserType.F_ASSIGNMENT, UserType.class, getPrismContext(), assignment)); assignRoleDelta = ObjectDelta.createModifyDelta(userOid, userDeltas, UserType.class, getPrismContext()); assignRoleDelta.setPrismContext(getPrismContext()); } catch (SchemaException e) { result.recordFatalError("Could not create delta"); return result; } WebModelServiceUtils.save(assignRoleDelta, result, task, PageRegistrationConfirmation.this); result.computeStatusIfUnknown(); } return result; }); // SecurityContextHolder.getContext().setAuthentication(null); } private void initLayout(final OperationResult result) { WebMarkupContainer successPanel = new WebMarkupContainer(ID_SUCCESS_PANEL); add(successPanel); successPanel.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return result.getStatus() != OperationResultStatus.FATAL_ERROR; } @Override public boolean isEnabled() { return result.getStatus() != OperationResultStatus.FATAL_ERROR; } }); Label successMessage = new Label(ID_LABEL_SUCCESS, createStringResource("PageRegistrationConfirmation.confirmation.successful")); successPanel.add(successMessage); AjaxLink<String> continueToLogin = new AjaxLink<String>(ID_LINK_LOGIN) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { setResponsePage(PageLogin.class); } }; successPanel.add(continueToLogin); WebMarkupContainer errorPanel = new WebMarkupContainer(ID_ERROR_PANEL); add(errorPanel); errorPanel.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isEnabled() { return result.getStatus() == OperationResultStatus.FATAL_ERROR; } @Override public boolean isVisible() { return result.getStatus() == OperationResultStatus.FATAL_ERROR; } }); Label errorMessage = new Label(ID_LABEL_ERROR, createStringResource("PageRegistrationConfirmation.confirmation.error")); errorPanel.add(errorMessage); } @Override protected void createBreadcrumb() { // don't create breadcrumb for registration confirmation page } }
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ package org.olap4j.transform; import java.util.ArrayList; import java.util.List; /** * Generic Tree Node. * Adapted from JPivot (class com.tonbeller.jpivot.util.TreeNode) * * <p>REVIEW: Should this class be in the public olap4j API? (jhyde, 2008/8/14) * * @author etdub * @since Aug 7, 2008 */ class TreeNode<T> { private TreeNode<T> parent = null; private final List<TreeNode<T>> children; private T reference; /** * Constructor. * * @param data the reference to hold in the node */ public TreeNode(T data) { this.reference = data; this.children = new ArrayList<TreeNode<T>>(); } /** * Removes this node from the tree */ public void remove() { if (parent != null) { parent.removeChild(this); } } /** * Removes child node from the tree, if it exists * @param child node to remove */ public void removeChild(TreeNode<T> child) { if (children.contains(child)) { children.remove(child); } } /** * Adds a child node to the tree * @param child node to be added */ public void addChildNode(TreeNode<T> child) { child.parent = this; if (!children.contains(child)) { children.add(child); } } /** * Performs a deep copy (clone) of this node * The contained reference is not cloned but passed to the * new node. * @return the cloned TreeNode */ public TreeNode<T> deepCopy() { TreeNode<T> newNode = new TreeNode<T>(reference); for (TreeNode<T> child : children) { newNode.addChildNode(child.deepCopy()); } return newNode; } /** * Performs a deep copy (clone) of this node, pruning * all nodes below level specified by depth * @param depth number of child levels to be copied * @return the cloned TreeNode */ public TreeNode<T> deepCopyPrune(int depth) { if (depth < 0) { throw new IllegalArgumentException("Depth is negative"); } TreeNode<T> newNode = new TreeNode<T>(reference); if (depth == 0) { return newNode; } for (TreeNode<T> child : children) { newNode.addChildNode(child.deepCopyPrune(depth - 1)); } return newNode; } /** * Returns the level of this node, i.e. distance from * the root node * @return level distance from root node */ public int getLevel() { int level = 0; TreeNode<T> p = parent; while (p != null) { ++level; p = p.parent; } return level; } /** * Gets a list of children nodes. * * <p>The list is mutable but shouldn't be modified by callers * (use the add and remove methods instead). * @return the list of children */ public List<TreeNode<T>> getChildren() { return children; } /** * Gets the parent node. * @return parent node */ public TreeNode<T> getParent() { return parent; } /** * Get the contained reference object * @return the reference object */ public T getReference() { return reference; } /** * Set the contained reference object * @param ref the new reference object */ public void setReference(T ref) { this.reference = ref; } /** * Walk through subtree of this node * @param callbackHandler callback function called on iteration * @return code used for navigation in the tree (@see TreeNodeCallback) */ public int walkTree(TreeNodeCallback<T> callbackHandler) { int code = callbackHandler.handleTreeNode(this); if (code != TreeNodeCallback.CONTINUE) { return code; } for (TreeNode<T> child : children) { code = child.walkTree(callbackHandler); if (code >= TreeNodeCallback.CONTINUE_PARENT) { return code; } } return code; } /** * Walk through children subtrees of this node * @param callbackHandler callback function called on iteration * @return code used for navigation in the tree (@see TreeNodeCallback) */ public int walkChildren(TreeNodeCallback<T> callbackHandler) { int code = 0; for (TreeNode<T> child : children) { code = callbackHandler.handleTreeNode(child); if (code >= TreeNodeCallback.CONTINUE_PARENT) { return code; } if (code == TreeNodeCallback.CONTINUE) { code = child.walkChildren(callbackHandler); if (code > TreeNodeCallback.CONTINUE_PARENT) { return code; } } } return code; } } // End TreeNode.java
/** * SetCollectionExp.java * --------------------------------- * Copyright (c) 2016 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.rsrg.absyn.expressions.mathexpr; import edu.clemson.cs.rsrg.absyn.expressions.Exp; import edu.clemson.cs.rsrg.parsing.data.Location; import java.util.*; /** * <p>This is the class for all the mathematical set (as a collection) * expression objects that the compiler builds using the ANTLR4 AST nodes.</p> * * @version 2.0 */ public class SetCollectionExp extends MathExp { // =========================================================== // Member Fields // =========================================================== /** <p>The list of member expressions in this set collection.</p> */ private final Set<MathExp> myMembers; // =========================================================== // Constructors // =========================================================== /** * <p>This constructs a mathematical set collection expression.</p> * * @param l A {@link Location} representation object. * @param vars A set of {@link MathExp}s where each one is a member * in this set. */ public SetCollectionExp(Location l, Set<MathExp> vars) { super(l); myMembers = vars; } // =========================================================== // Public Methods // =========================================================== /** * {@inheritDoc} */ @Override public final String asString(int indentSize, int innerIndentInc) { StringBuffer sb = new StringBuffer(); printSpace(indentSize, sb); sb.append("{"); if (myMembers != null) { if (myMembers.isEmpty()) { sb.append(""); } else { Iterator<MathExp> i = myMembers.iterator(); while (i.hasNext()) { MathExp m = i.next(); sb.append(m.asString(indentSize, innerIndentInc)); if (i.hasNext()) { sb.append(", "); } } } } sb.append("}"); return sb.toString(); } /** * {@inheritDoc} */ @Override public final boolean containsExp(Exp exp) { boolean found = false; Iterator<MathExp> i = myMembers.iterator(); while (i.hasNext() && !found) { MathExp m = i.next(); if (m != null) { found = m.containsExp(exp); } } return found; } /** * {@inheritDoc} */ @Override public final boolean containsVar(String varName, boolean IsOldExp) { boolean found = false; Iterator<MathExp> i = myMembers.iterator(); while (i.hasNext() && !found) { MathExp m = i.next(); if (m != null) { found = m.containsVar(varName, IsOldExp); } } return found; } /** * {@inheritDoc} */ @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; SetCollectionExp that = (SetCollectionExp) o; return myMembers.equals(that.myMembers); } /** * {@inheritDoc} */ @Override public final boolean equivalent(Exp e) { boolean result = (e instanceof SetCollectionExp); if (result) { SetCollectionExp eAsSetCollectionExp = (SetCollectionExp) e; if (myMembers != null && eAsSetCollectionExp.myMembers != null) { Iterator<MathExp> thisMemberExps = myMembers.iterator(); Iterator<MathExp> eMemberExps = eAsSetCollectionExp.myMembers.iterator(); while (result && thisMemberExps.hasNext() && eMemberExps.hasNext()) { result &= thisMemberExps.next() .equivalent(eMemberExps.next()); } //Both had better have run out at the same time result &= (!thisMemberExps.hasNext()) && (!eMemberExps.hasNext()); } } return result; } /** * {@inheritDoc} */ @Override public final List<Exp> getSubExpressions() { List<Exp> subExpList = new ArrayList<>(); for (MathExp m : myMembers) { subExpList.add(m); } return subExpList; } /** * <p>This method returns all the * variable expressions in this set.</p> * * @return A set containing all the {@link MathExp}s. */ public final Set<MathExp> getVars() { return myMembers; } /** * {@inheritDoc} */ @Override public final int hashCode() { int result = super.hashCode(); result = 31 * result + myMembers.hashCode(); return result; } /** * <p>This method applies VC Generator's remember rule. * For all inherited programming expression classes, this method * should throw an exception.</p> * * @return The resulting {@link SetCollectionExp} from applying the remember rule. */ @Override public final SetCollectionExp remember() { Set<MathExp> newVarExps = new HashSet<>(); for (MathExp m : myMembers) { newVarExps.add((MathExp) m.remember()); } return new SetCollectionExp(cloneLocation(), newVarExps); } /** * <p>This method applies the VC Generator's simplification step.</p> * * @return The resulting {@link MathExp} from applying the simplification step. */ @Override public final MathExp simplify() { return this.clone(); } // =========================================================== // Protected Methods // =========================================================== /** * {@inheritDoc} */ @Override protected final Exp copy() { return new SetCollectionExp(cloneLocation(), copyExps()); } /** * {@inheritDoc} */ @Override protected final Exp substituteChildren(Map<Exp, Exp> substitutions) { Set<MathExp> newMembers = new HashSet<>(); for (MathExp m : myMembers) { newMembers.add((MathExp) substitute(m, substitutions)); } return new SetCollectionExp(cloneLocation(), newMembers); } // =========================================================== // Private Methods // =========================================================== /** * <p>This is a helper method that makes a copy of the * list containing all the variable expressions.</p> * * @return A list containing {@link MathExp}s. */ private Set<MathExp> copyExps() { Set<MathExp> copyMathExps = new HashSet<>(); for (MathExp v : myMembers) { copyMathExps.add(v.clone()); } return copyMathExps; } }
package id.dreamfighter.android.utils; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import id.dreamfighter.android.log.Logger; public class JsonUtils { public static <T> T parse(JSONObject jsonObject, Class<T> classDefinition){ Object o; try { o = jsonToClassMapping(jsonObject,classDefinition); return classDefinition.cast(o) ; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } public static <T> List<T> parse(JSONArray jsonArray, Class<T> classDefinition) { List<T> list = new ArrayList<T>(); if(jsonArray!=null){ for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject; try { jsonObject = jsonArray.getJSONObject(i); list.add(parse(jsonObject,classDefinition)); } catch (JSONException e) { e.printStackTrace(); } } } return list; } public static Object jsonToClassMapping(JSONObject jsonObject, Class<?> classDefinition) throws ClassNotFoundException, InstantiationException, IllegalAccessException, JSONException{ //Class<?> classDefinition = Class.forName(className.getName()); if(jsonObject==null){ return null; } Object object = classDefinition.newInstance(); if(object !=null){ //ContentValues values = new ContentValues(); List<Field> fields = new ArrayList<Field>(); fields = new LinkedList<Field>(Arrays.asList(classDefinition.getDeclaredFields())); if(classDefinition.getSuperclass()!=null){ fields.addAll(Arrays.asList(classDefinition.getSuperclass().getDeclaredFields())); } for(Field field:fields){ field.setAccessible(true); String columName = field.getName(); if(jsonObject.isNull(columName)){ continue; } if(field.getType().getName().equalsIgnoreCase("java.lang.String")){ String value = jsonObject.get(columName).toString(); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => String"); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); field.set(object, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Integer")){ int value = jsonObject.getInt(columName); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => String"); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); field.set(object, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Double")){ double value = jsonObject.getDouble(columName); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => String"); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); field.set(object, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Long")){ Long value = jsonObject.getLong(columName); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => String"); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); field.set(object, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Boolean")){ boolean value = jsonObject.getBoolean(columName); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => String"); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); field.set(object, value); }else if(field.getType().getName().equalsIgnoreCase("java.util.List")){ ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); Class<?> listTypeClass = (Class<?>) stringListType.getActualTypeArguments()[0]; List value = parse(jsonObject.getJSONArray(columName), listTypeClass); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => String"); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); field.set(object, value); }else if(field.getType().getDeclaredFields().length>0){ //Logger.log("JsonUtils", object.getClass().getSimpleName() + " columName = "+columName+" => " + field.getType()); Object value = jsonToClassMapping(jsonObject.getJSONObject(columName),field.getType()); field.set(object, value); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); } field.setAccessible(false); } } return object; } public static String objectToJson(Object object) throws IllegalAccessException{ //Class<?> classDefinition = Class.forName(className.getName()); StringBuilder json = new StringBuilder(); json.append("{"); if(object !=null){ int i = 0; //ContentValues values = new ContentValues(); for(Field field:object.getClass().getDeclaredFields()){ field.setAccessible(true); String columName = field.getName(); if(i!=0){ json.append(","); } if(field.getType().getName().equalsIgnoreCase("java.lang.String")){ Object value = field.get(object); Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); //json.append("\""+columName+"\":\""+value+"\""); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Integer")){ Integer value = (Integer)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); json.append("\""+columName+"\":\""+value+"\""); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Double")){ double value = (Double)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); json.append("\""+columName+"\":\""+value+"\""); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Long")){ Long value = (Long)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); json.append("\""+columName+"\":\""+value+"\""); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Boolean")){ boolean value = (Boolean)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); json.append("\""+columName+"\":\""+value+"\""); }else if(field.getType().getDeclaredFields().length>0){ String value = objectToJson(field.get(object)); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); json.append("\""+columName+"\":"+value); } i++; } } json.append("}"); return json.toString(); } public static JSONObject updateJsonObject(JSONObject jsonObject,Object object) throws IllegalAccessException, JSONException{ //Class<?> classDefinition = Class.forName(className.getName()); if(object !=null){ //ContentValues values = new ContentValues(); for(Field field:object.getClass().getDeclaredFields()){ field.setAccessible(true); String columName = field.getName(); if(field.getType().getName().equalsIgnoreCase("java.lang.String")){ Object value = field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); jsonObject.put(columName, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Integer")){ int value = (Integer)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); jsonObject.put(columName, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Double")){ double value = (Double)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); jsonObject.put(columName, value); }else if(field.getType().getName().equalsIgnoreCase("java.lang.Boolean")){ boolean value = (Boolean)field.get(object); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); jsonObject.put(columName, value); }else if(field.getType().getDeclaredFields().length>0){ JSONObject value = updateJsonObject(jsonObject.getJSONObject(columName),field.get(object)); //Logger.log("JsonUtils", object.getClass().getSimpleName() + " => ["+columName+","+value+"]"); jsonObject.put(columName, value); } } } return jsonObject; } }
/* * Copyright (C) 2014 Adam Huang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package poisondog.net.http; import java.io.File; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.util.HashMap; import java.util.Map; import java.util.Set; import poisondog.io.StepListener; import poisondog.log.Logger; import poisondog.log.LogLevel; import poisondog.log.NoLogger; import poisondog.net.Entity; import poisondog.net.FileEntity; import poisondog.net.MultipartEntity; import poisondog.net.NameValueEntity; import poisondog.net.TextEntity; import poisondog.net.URLUtils; /** * @author Adam Huang <poisondog@gmail.com> */ public class HttpParameter { private String mCharset; private String mUrl; private String mUsername; private String mPassword; private String mRequestMethod; private int mTimeout; private Map<String, String> mHeaderMap; private Map<String, String> mTextMap; private Map<String, File> mFileMap; private StepListener mListener; private Logger mLogger; public HttpParameter() { mCharset = "utf8"; mTextMap = new HashMap<String, String>(); mHeaderMap = new HashMap<String, String>(); mFileMap = new HashMap<String, File>(); mUrl = ""; mRequestMethod = "GET"; mLogger = new NoLogger(); } public void addHeader(String key, String value) { mHeaderMap.put(key, value); } public String getHeader(String key) { return mHeaderMap.get(key); } public Set<String> headerKeys() { return mHeaderMap.keySet(); } public void addText(String key, String value) { mTextMap.put(key, value); } public String getText(String key) { return mTextMap.get(key); } public Set<String> textKeys() { return mTextMap.keySet(); } public String httpQuery() { return URLUtils.httpQuery(mTextMap); } public void addFile(String key, File value) { mFileMap.put(key, value); } public File getFile(String key) { return mFileMap.get(key); } public Set<String> fileKeys() { return mFileMap.keySet(); } public void setUrl(String url) { mUrl = url; } public String getUrl() { return mUrl; } public void setTimeout(int timeout) { mTimeout = timeout; } public int getTimeout() { return mTimeout; } public void setUsername(String username) { mUsername = username; } public String getUsername() { return mUsername; } public void setPassword(String password) { mPassword = password; } public String getPassword() { return mPassword; } @Override public boolean equals(Object obj) { if(!(obj instanceof HttpParameter)) return false; HttpParameter another = (HttpParameter) obj; if(!mUrl.equals(another.getUrl())) return false; for (String key : textKeys()) { String value = another.getText(key); if(value == null) return false; if(!value.equals(getText(key))) return false; } return true; } public void setStepListener(StepListener listener) { mListener = listener; } public StepListener getStepListener() { return mListener; } public void setRequestMethod(String method) { mRequestMethod = method; } public String getRequestMethod() { return mRequestMethod; } public void neverUseFile() { if(!fileKeys().isEmpty()) { throw new IllegalArgumentException("this parameter has file, but this method never send files"); } } public void withAuthentication() { if(mUsername != null && !mUsername.isEmpty()) { Authenticator.setDefault (new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mUsername, mPassword.toCharArray()); } }); mLogger.log(LogLevel.VERBOSE, "with authentication"); } } public void setCharset(String charset) { mCharset = charset; } public String getCharset() { return mCharset; } public void setLogger(Logger logger) { mLogger = logger; } public Logger getLogger() { return mLogger; } private NameValueEntity createTextEntity() { NameValueEntity textEntity = new NameValueEntity(mCharset); for (String key : textKeys()) { textEntity.addTextBody(key, getText(key)); } return textEntity; } public Entity createMultiEntity() { Entity entity = null; NameValueEntity textEntity = createTextEntity(); Set<String> filekeys = fileKeys(); if(!filekeys.isEmpty()) { MultipartEntity multiEntity = new MultipartEntity(); for (String key : textKeys()) { multiEntity.addEntity(new TextEntity(key, getText(key), mCharset)); } for (String key : filekeys) { multiEntity.addEntity(new FileEntity(key, getFile(key))); } entity = multiEntity; } else { entity = textEntity; } return entity; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.ml.structures; import org.apache.ignite.ml.math.exceptions.CardinalityException; import org.apache.ignite.ml.math.exceptions.NoDataException; import org.apache.ignite.ml.math.exceptions.knn.NoLabelVectorException; import org.apache.ignite.ml.math.primitives.vector.Vector; import org.apache.ignite.ml.math.primitives.vector.impl.DenseVector; /** * The set of labeled vectors used in local partition calculations. */ public class LabeledVectorSet<L, Row extends LabeledVector> extends Dataset<Row> implements AutoCloseable { /** * Default constructor (required by Externalizable). */ public LabeledVectorSet() { super(); } /** * Creates new Labeled Dataset and initialized with empty data structure. * * @param rowSize Amount of instances. Should be > 0. * @param colSize Amount of attributes. Should be > 0. * @param isDistributed Use distributed data structures to keep data. */ public LabeledVectorSet(int rowSize, int colSize, boolean isDistributed){ this(rowSize, colSize, null, isDistributed); } /** * Creates new local Labeled Dataset and initialized with empty data structure. * * @param rowSize Amount of instances. Should be > 0. * @param colSize Amount of attributes. Should be > 0. */ public LabeledVectorSet(int rowSize, int colSize){ this(rowSize, colSize, null, false); } /** * Creates new Labeled Dataset and initialized with empty data structure. * * @param rowSize Amount of instances. Should be > 0. * @param colSize Amount of attributes. Should be > 0 * @param featureNames Column names. * @param isDistributed Use distributed data structures to keep data. */ public LabeledVectorSet(int rowSize, int colSize, String[] featureNames, boolean isDistributed){ super(rowSize, colSize, featureNames, isDistributed); initializeDataWithLabeledVectors(); } /** * Creates new Labeled Dataset by given data. * * @param data Should be initialized with one vector at least. */ public LabeledVectorSet(Row[] data) { super(data); } /** */ private void initializeDataWithLabeledVectors() { data = (Row[])new LabeledVector[rowSize]; for (int i = 0; i < rowSize; i++) data[i] = (Row)new LabeledVector(emptyVector(colSize, isDistributed), null); } /** * Creates new Labeled Dataset by given data. * * @param data Should be initialized with one vector at least. * @param colSize Amount of observed attributes in each vector. */ public LabeledVectorSet(Row[] data, int colSize) { super(data, colSize); } /** * Creates new local Labeled Dataset by matrix and vector of labels. * * @param mtx Given matrix with rows as observations. * @param lbs Labels of observations. */ public LabeledVectorSet(double[][] mtx, double[] lbs) { this(mtx, lbs, null, false); } /** * Creates new Labeled Dataset by matrix and vector of labels. * * @param mtx Given matrix with rows as observations. * @param lbs Labels of observations. * @param featureNames Column names. * @param isDistributed Use distributed data structures to keep data. */ public LabeledVectorSet(double[][] mtx, double[] lbs, String[] featureNames, boolean isDistributed) { super(); assert mtx != null; assert lbs != null; if(mtx.length != lbs.length) throw new CardinalityException(lbs.length, mtx.length); if(mtx[0] == null) throw new NoDataException("Pass filled array, the first vector is empty"); this.rowSize = lbs.length; this.colSize = mtx[0].length; if(featureNames == null) generateFeatureNames(); else { assert colSize == featureNames.length; convertStringNamesToFeatureMetadata(featureNames); } data = (Row[])new LabeledVector[rowSize]; for (int i = 0; i < rowSize; i++){ data[i] = (Row)new LabeledVector(emptyVector(colSize, isDistributed), lbs[i]); for (int j = 0; j < colSize; j++) { try { data[i].features().set(j, mtx[i][j]); } catch (ArrayIndexOutOfBoundsException e) { throw new NoDataException("No data in given matrix by coordinates (" + i + "," + j + ")"); } } } } /** * Returns label if label is attached or null if label is missed. * * @param idx Index of observation. * @return Label. */ public double label(int idx) { LabeledVector labeledVector = data[idx]; if(labeledVector!=null) return (double)labeledVector.label(); else return Double.NaN; } /** * Returns new copy of labels of all labeled vectors NOTE: This method is useful for copying labels from test * dataset. * * @return Copy of labels. */ public double[] labels() { assert data != null; assert data.length > 0; double[] labels = new double[data.length]; for (int i = 0; i < data.length; i++) labels[i] = (double)data[i].label(); return labels; } /** * Fill the label with given value. * * @param idx Index of observation. * @param lb The given label. */ public void setLabel(int idx, double lb) { LabeledVector<Vector, Double> labeledVector = data[idx]; if(labeledVector != null) labeledVector.setLabel(lb); else throw new NoLabelVectorException(idx); } /** */ public static Vector emptyVector(int size, boolean isDistributed) { return new DenseVector(size); } /** Makes copy with new Label objects and old features and Metadata objects. */ public LabeledVectorSet copy(){ LabeledVectorSet res = new LabeledVectorSet(this.data, this.colSize); res.isDistributed = this.isDistributed; res.meta = this.meta; for (int i = 0; i < rowSize; i++) res.setLabel(i, this.label(i)); return res; } /** Closes LabeledDataset. */ @Override public void close() throws Exception { } }
/* * Copyright 2014-2015 Jeff Hain * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jafaran; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class RandomsPerf { //-------------------------------------------------------------------------- // CONFIGURATION //-------------------------------------------------------------------------- private static final int NBR_OF_PROC = Runtime.getRuntime().availableProcessors(); private static final int CEILED_NBR_OF_PROC = ceilingPowerOfTwo(NBR_OF_PROC); private static final int MIN_PARALLELISM = 1; private static final int MAX_PARALLELISM = 2*CEILED_NBR_OF_PROC; private static final int NBR_OF_RUNS = 2; private static final int NBR_OF_CALLS = 10 * 1000 * 1000; /** * Because Random.nextGaussian(), called concurrently, can be very slow * with Java5. */ private static final int LOOP_DIVISOR_FOR_CONC_GAUSSIAN = 100; private static final boolean BENCH_INT_PRIMITIVES = true; private static final boolean BENCH_INT_PRIMITIVES_RANGES = true; private static final boolean BENCH_FLOATING_POINTS = true; private static final boolean BENCH_GAUSSIANS = true; /** * To avoid log-and-time-spam with nextGaussian() and the like, * while we already have performances of the backing nextInt() * and nextLong(). */ private static final boolean IGNORE_SECONDARY_METHODS_ABOVE_2_THREADS = true; //-------------------------------------------------------------------------- // PRIVATE CLASSES //-------------------------------------------------------------------------- /** * Implementations must be stateless (can be used concurrently). */ private static interface MyInterfaceUser { public String methodSignature(); public void use(Random random, int nbrOfCalls); } private static class MyUser_nextBoolean implements MyInterfaceUser { //@Override public String methodSignature() { return "nextBoolean()"; } //@Override public void use(Random random, int nbrOfCalls) { int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += (random.nextBoolean() ? 1 : 0); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextBit implements MyInterfaceUser { //@Override public String methodSignature() { return "nextBit()"; } //@Override public void use(Random random, int nbrOfCalls) { final AbstractRNG rng = (AbstractRNG)random; int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += rng.nextBit(); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextByte implements MyInterfaceUser { //@Override public String methodSignature() { return "nextByte()"; } //@Override public void use(Random random, int nbrOfCalls) { final AbstractRNG impl = (AbstractRNG)random; int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += impl.nextByte(); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextShort implements MyInterfaceUser { //@Override public String methodSignature() { return "nextShort()"; } //@Override public void use(Random random, int nbrOfCalls) { final AbstractRNG rng = (AbstractRNG)random; int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += rng.nextShort(); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextInt implements MyInterfaceUser { //@Override public String methodSignature() { return "nextInt()"; } //@Override public void use(Random random, int nbrOfCalls) { int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += random.nextInt(); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextLong implements MyInterfaceUser { //@Override public String methodSignature() { return "nextLong()"; } //@Override public void use(Random random, int nbrOfCalls) { int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += (int)random.nextLong(); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextInt_int implements MyInterfaceUser { private final int maxExcl; public MyUser_nextInt_int(int maxExcl) { this.maxExcl = maxExcl; } //@Override public String methodSignature() { return "nextInt("+this.maxExcl+")"; } //@Override public void use(Random random, int nbrOfCalls) { int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += random.nextInt(this.maxExcl); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextLong_long implements MyInterfaceUser { private final long maxExcl; public MyUser_nextLong_long(long maxExcl) { this.maxExcl = maxExcl; } //@Override public String methodSignature() { return "nextLong("+this.maxExcl+")"; } //@Override public void use(Random random, int nbrOfCalls) { final AbstractRNG rng = (AbstractRNG)random; int dummy = Integer.MIN_VALUE; for (int i=0;i<nbrOfCalls;i++) { dummy += (int)rng.nextLong(this.maxExcl); } if (dummy == 0) { System.out.println("rare"); } } } private static class MyUser_nextFloat implements MyInterfaceUser { //@Override public String methodSignature() { return "nextFloat()"; } //@Override public void use(Random random, int nbrOfCalls) { float dummy = 0.0f; for (int i=0;i<nbrOfCalls;i++) { dummy += random.nextFloat(); } if (dummy == 0.0f) { System.out.println("rare"); } } } private static class MyUser_nextDouble implements MyInterfaceUser { //@Override public String methodSignature() { return "nextDouble()"; } //@Override public void use(Random random, int nbrOfCalls) { double dummy = 0.0; for (int i=0;i<nbrOfCalls;i++) { dummy += random.nextDouble(); } if (dummy == 0.0) { System.out.println("rare"); } } } private static class MyUser_nextDoubleFast implements MyInterfaceUser { //@Override public String methodSignature() { return "nextDoubleFast()"; } //@Override public void use(Random random, int nbrOfCalls) { final AbstractRNG rng = (AbstractRNG)random; double dummy = 0.0; for (int i=0;i<nbrOfCalls;i++) { dummy += rng.nextDoubleFast(); } if (dummy == 0.0) { System.out.println("rare"); } } } private static class MyUser_nextGaussian implements MyInterfaceUser { //@Override public String methodSignature() { return "nextGaussian()"; } //@Override public void use(Random random, int nbrOfCalls) { double dummy = 0.0; for (int i=0;i<nbrOfCalls;i++) { dummy += random.nextGaussian(); } if (dummy == 0.0) { System.out.println("rare"); } } } private static class MyUser_nextGaussianFast implements MyInterfaceUser { //@Override public String methodSignature() { return "nextGaussianFast()"; } //@Override public void use(Random random, int nbrOfCalls) { final AbstractRNG rng = (AbstractRNG)random; double dummy = 0.0; for (int i=0;i<nbrOfCalls;i++) { dummy += rng.nextGaussianFast(); } if (dummy == 0.0) { System.out.println("rare"); } } } //-------------------------------------------------------------------------- // MEMBERS //-------------------------------------------------------------------------- private static final Random SEQ_PILL = new Random(); //-------------------------------------------------------------------------- // PUBLIC METHODS //-------------------------------------------------------------------------- public static void main(String[] args) { System.out.println(TestUtils.getJVMInfo()); newRun(args); } public static void newRun(String[] args) { new RandomsPerf().run(args); } public RandomsPerf() { } //-------------------------------------------------------------------------- // PRIVATE METHODS //-------------------------------------------------------------------------- /** * @param a A value in [0,2^30]. * @return The lowest power of two >= a. */ private static int ceilingPowerOfTwo(int a) { return (a >= 2) ? Integer.highestOneBit((a-1)<<1) : 1; } /* * */ private static boolean handlePill(Random pillOrNot) { if (pillOrNot == SEQ_PILL) { System.out.println("seq:"); return true; } else { return false; } } private void run(String[] args) { // XXX System.out.println("--- "+RandomsPerf.class.getSimpleName()+"... ---"); System.out.println("number of calls = "+NBR_OF_CALLS); for (boolean concurrent : new boolean[]{false,true}) { final int minNbrOfThreads = Math.max(concurrent ? 2 : 1, MIN_PARALLELISM); final int maxNbrOfThreads = Math.min(concurrent ? MAX_PARALLELISM : 1, MAX_PARALLELISM); final boolean sequentialAllowed = (!concurrent); for (int nbrOfThreads=minNbrOfThreads;nbrOfThreads<=maxNbrOfThreads;nbrOfThreads*=2) { if (BENCH_INT_PRIMITIVES) { System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextBoolean()); } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextBit()); } } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextByte()); } } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextShort()); } } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextInt()); } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextLong()); } } /* * */ if (IGNORE_SECONDARY_METHODS_ABOVE_2_THREADS && (nbrOfThreads > 2)) { continue; } /* * */ if (BENCH_INT_PRIMITIVES_RANGES) { // Tiny. System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextInt_int(7)); } // Power of two. System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextInt_int(1<<30)); } // Tiny. System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextLong_long(7L)); } } // Tiny not in int range. System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextLong_long(Integer.MAX_VALUE+8L)); } } } /* * */ if (BENCH_FLOATING_POINTS) { System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextFloat()); } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextDouble()); } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextDoubleFast()); } } } /* * */ if (BENCH_GAUSSIANS) { System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; bench(random, nbrOfThreads, new MyUser_nextGaussian(), ((nbrOfThreads > 1) ? LOOP_DIVISOR_FOR_CONC_GAUSSIAN : 1)); } System.out.println(); for (Random random : newRandoms(sequentialAllowed)) { if(handlePill(random))continue; if (random instanceof AbstractRNG) { bench(random, nbrOfThreads, new MyUser_nextGaussianFast()); } } } } } System.out.println("--- ..."+RandomsPerf.class.getSimpleName()+" ---"); } private void bench( final Random random, int nbrOfThreads, final MyInterfaceUser user) { final int loopDivisor = 1; bench( random, nbrOfThreads, user, loopDivisor); } /** * @param loopDivisor To run less loops, for slow cases. */ private void bench( final Random random, int nbrOfThreads, final MyInterfaceUser user, int loopDivisor) { TestUtils.settle(); final String csn = random.getClass().getSimpleName(); final int usedNbrOfCalls = NBR_OF_CALLS/loopDivisor; final int nbrOfCallsPerThread = usedNbrOfCalls/nbrOfThreads; // For warmup (class load and code optim). user.use(random, NBR_OF_CALLS); for (int k=0;k<NBR_OF_RUNS;k++) { long a = System.nanoTime(); if (nbrOfThreads == 1) { // Taking care to use current thread, // in case ThreadLocalRandom would not like otherwise. user.use(random, nbrOfCallsPerThread); } else { final ExecutorService executor = Executors.newCachedThreadPool(); for (int i=0;i<nbrOfThreads;i++) { executor.execute(new Runnable() { //@Override public void run() { user.use(random, nbrOfCallsPerThread); } }); } TestUtils.shutdownAndAwaitTermination(executor); } long b = System.nanoTime(); final String loopDivision = ((loopDivisor == 1) ? "" : "(/"+loopDivisor+")"); System.out.println("Loop"+loopDivision+" on "+csn+"."+user.methodSignature()+", "+nbrOfThreads+" caller(s), took "+TestUtils.nsToSRounded(b-a)+" s"); } } private static ArrayList<Random> newRandoms(boolean sequentialAllowed) { ArrayList<Random> result = new ArrayList<Random>(); result.add(new Random()); result.add(new RandomConcRNG()); result.add(new MTConcRNG()); result.add(new MTSyncRNG()); if (sequentialAllowed) { result.add(SEQ_PILL); // TODO Java7 result.add(ThreadLocalRandom.current()); result.add(new MTSeqRNG()); result.add(new MXSIntSeqRNG()); result.add(new MXSLongSeqRNG()); } return result; } }
/* * Copyright 2011 Miltiadis Allamanis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package uk.ac.cam.cl.passgori.app; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.TreeMap; import uk.ac.cam.cl.passgori.IPasswordStore; import uk.ac.cam.cl.passgori.Password; import uk.ac.cam.cl.passgori.PasswordStoreException; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import android.widget.Toast; import com.google.nigori.client.DAG; import com.google.nigori.client.Node; import com.google.nigori.common.Revision; /** * An activity presenting the a password entity. * * @author Miltiadis Allamanis * */ public class PassgoriPresentPasswordsActivity extends AbstractLoadingActivity { public class DeletePasswordThread extends Thread { private final String mPasswordId; public DeletePasswordThread(final String passwordId) { mPasswordId = passwordId; } @Override public void run() { try { if (mPasswordStore.removePassword(mPasswordId)) { runOnUiThread(new PasswordDeleted()); // go back! } else { // update GUI runOnUiThread(new FailureNotification( "Password unaccessbile")); } } catch (PasswordStoreException e) { runOnUiThread(new FailureNotification(e)); } } } public class PasswordDeleted implements Runnable { @Override public void run() { mLoadingDialog.dismiss(); setResult(1); // on finish ask previous activity to refresh finish(); Toast.makeText(getApplicationContext(), "Password Deleted", Toast.LENGTH_LONG); } } private class GetPassword extends Thread { @Override public void run() { try { Password password = mPasswordStore.retrivePassword(getIntent() .getExtras().getString("passwordId")); if (password != null) { UpdatePasswordDetails updater = new UpdatePasswordDetails( password); runOnUiThread(updater); } else { // Update GUI about failure!! runOnUiThread(new FailureNotification( "Password Unaccessible")); } } catch (PasswordStoreException e) { runOnUiThread(new FailureNotification(e)); } } } private class UpdatePasswordDetails implements Runnable { private final Password mPassword; public UpdatePasswordDetails(Password password) { mPassword = password; } @Override public void run() { mUsernameField.setText(mPassword.getUsername()); mPasswordField.setText(mPassword.getPassword()); mNotesField.setText(mPassword.getNotes()); mUsernameField.setVisibility(View.VISIBLE); mPasswordField.setVisibility(View.VISIBLE); mNotesField.setVisibility(View.VISIBLE); mHistoryList.setVisibility(View.VISIBLE); mLoadingDialog.dismiss(); } } /** * The TextView corresponding to the password's title. */ private TextView mPasswordTitle; /** * The TextView corresponding to the paswords's username. */ private TextView mUsernameField; /** * The TextView corresponding to the password's password. */ private TextView mPasswordField; /** * The TextView corresponding to the password's notes. */ private TextView mNotesField; private ExpandableListView mHistoryList; /** * The password store. */ private IPasswordStore mPasswordStore; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.password_present); // Assign content mPasswordTitle = (TextView) findViewById(R.id.passwordTitle); mUsernameField = (TextView) findViewById(R.id.usernameField); mPasswordField = (TextView) findViewById(R.id.passwordField); mNotesField = (TextView) findViewById(R.id.notesField); mHistoryList = (ExpandableListView) findViewById(R.id.historyList); mLoadingDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true); String id = getIntent().getExtras().getString("passwordId"); mPasswordTitle.setText(id); mUsernameField.setVisibility(View.INVISIBLE); mPasswordField.setVisibility(View.INVISIBLE); mNotesField.setVisibility(View.INVISIBLE); mHistoryList.setVisibility(View.INVISIBLE); try { mHistoryList.setAdapter(new HistoryAdapter(this,id)); } catch (PasswordStoreException e) { runOnUiThread(new FailureNotification("Error getting history: " + e.toString())); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.password_present_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.editPasswordOption: Intent intent = new Intent(this, PassgoriEditPasswordActivity.class); intent.putExtra("passwordId", getIntent().getExtras().getString("passwordId")); startActivityForResult(intent, 0); return true; case R.id.deletePasswordOption: mLoadingDialog = ProgressDialog.show(this, "", "Deleting. Please wait...", true); new DeletePasswordThread(getIntent().getExtras().getString( "passwordId")).start(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onStop() { super.onStop(); // Close activity to avoid storing the password if someone exits us from // the home button finish(); } @Override protected void onStart() { super.onStart(); // Bind to PasswordStoreService Intent intent = new Intent(this, PasswordStoreService.class); if (!getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE)) { // Inform GUI for failure!! mLoadingDialog.dismiss(); new FailureNotification("Unable to connect to internal server") .run(); } // Once the service is binded, we will load the list } private class HistoryAdapter extends BaseExpandableListAdapter { protected LayoutInflater inflater; protected List<Revision> revisions; private String id; private boolean initialised = false; protected Map<Integer,Password> cache = new TreeMap<Integer,Password>(); public HistoryAdapter(Context con, String id) throws PasswordStoreException{ inflater = LayoutInflater.from(con); revisions = new ArrayList<Revision>(); this.id = id; } private void initialise() { if (!initialised && mPasswordStore != null) { try { DAG<Revision> history = mPasswordStore.getHistory(id); if (history != null) { for (Node<Revision> revision : history) { revisions.add(revision.getValue()); } } } catch (PasswordStoreException e) { runOnUiThread(new FailureNotification("Error while getting history" + e.toString())); } initialised = true; } } @Override public Password getChild(int groupPosition, int childPosition) { if (groupPosition != 0){ return null; } try { initialise(); Password password = cache.get(childPosition); if (password == null) { password = mPasswordStore.retrivePassword(id, revisions.get(childPosition)); cache.put(childPosition, password); } return password; } catch (PasswordStoreException e) { runOnUiThread(new FailureNotification("Error retrieving old password")); return null; } } @Override public long getChildId(int groupPosition, int childPosition) { if (groupPosition != 0){ return 0; } return childPosition; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (groupPosition != 0){ return null; } Password password = getChild(groupPosition,childPosition); if (convertView == null){ convertView = inflater.inflate(R.layout.history_child, null); } TextView title = (TextView) convertView.findViewById(R.id.passwordTitle); title.setText(password.getId()); TextView username = (TextView) convertView.findViewById(R.id.usernameField); username.setText(password.getUsername()); TextView passwordField = (TextView) convertView.findViewById(R.id.passwordField); passwordField.setText(password.getPassword()); TextView notes = (TextView) convertView.findViewById(R.id.notesField); notes.setText(password.getNotes()); TextView date = (TextView) convertView.findViewById(R.id.historyChildDate); date.setText(new Date(password.getGeneratedAt()).toLocaleString()); return convertView; } @Override public int getChildrenCount(int groupPosition) { if (groupPosition != 0){ return 0; } initialise(); return revisions.size(); } @Override public List<Revision> getGroup(int groupPosition) { if (groupPosition != 0){ return null; } initialise(); return revisions; } @Override public int getGroupCount() { return 1; } @Override public long getGroupId(int groupPosition) { return R.layout.history_group; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null){ convertView = inflater.inflate(R.layout.history_group, null); } return convertView; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { if (groupPosition != 0) { return false; } initialise(); if (childPosition < revisions.size()) { return true; } else { return false; } } } @Override protected void displayError(String errorMessage) { Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show(); } @Override protected void onConnected() throws PasswordStoreException { mPasswordStore = binder.getStore(); new GetPassword().start(); } }
/** * ***************************************************************************** * * Copyright (c) 2004-2010 Oracle Corporation. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * ****************************************************************************** */ package hudson.model; import hudson.model.RunMap.RunValue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Assert; import junit.framework.TestCase; /** * Unit test for {@link Job}. */ public class SimpleJobTest extends TestCase { public void testGetEstimatedDuration() throws IOException { final SortedMap<Integer, TestBuild> runs = new TreeMap<Integer, TestBuild>(); Job project = createMockProject(runs); TestBuild previousPreviousBuild = new TestBuild(project, Result.SUCCESS, 20, null); runs.put(3, previousPreviousBuild); TestBuild previousBuild = new TestBuild(project, Result.SUCCESS, 15, previousPreviousBuild); runs.put(2, previousBuild); TestBuild lastBuild = new TestBuild(project, Result.SUCCESS, 42, previousBuild); runs.put(1, lastBuild); // without assuming to know to much about the internal calculation // we can only assume that the result is between the maximum and the minimum Assert.assertTrue(project.getEstimatedDuration() < 42); Assert.assertTrue(project.getEstimatedDuration() > 15); } public void testGetEstimatedDurationWithOneRun() throws IOException { final SortedMap<Integer, TestBuild> runs = new TreeMap<Integer, TestBuild>(); Job project = createMockProject(runs); TestBuild lastBuild = new TestBuild(project, Result.SUCCESS, 42, null); runs.put(1, lastBuild); Assert.assertEquals(42, project.getEstimatedDuration()); } public void testGetEstimatedDurationWithFailedRun() throws IOException { final SortedMap<Integer, TestBuild> runs = new TreeMap<Integer, TestBuild>(); Job project = createMockProject(runs); TestBuild lastBuild = new TestBuild(project, Result.FAILURE, 42, null); runs.put(1, lastBuild); Assert.assertEquals(-1, project.getEstimatedDuration()); } public void testGetEstimatedDurationWithNoRuns() throws IOException { final SortedMap<Integer, TestBuild> runs = new TreeMap<Integer, TestBuild>(); Job project = createMockProject(runs); Assert.assertEquals(-1, project.getEstimatedDuration()); } public void testGetEstimatedDurationIfPrevious3BuildsFailed() throws IOException { final SortedMap<Integer, TestBuild> runs = new TreeMap<Integer, TestBuild>(); Job project = createMockProject(runs); TestBuild prev4Build = new TestBuild(project, Result.SUCCESS, 1, null); runs.put(5, prev4Build); TestBuild prev3Build = new TestBuild(project, Result.SUCCESS, 1, prev4Build); runs.put(4, prev3Build); TestBuild previous2Build = new TestBuild(project, Result.FAILURE, 50, prev3Build); runs.put(3, previous2Build); TestBuild previousBuild = new TestBuild(project, Result.FAILURE, 50, previous2Build); runs.put(2, previousBuild); TestBuild lastBuild = new TestBuild(project, Result.FAILURE, 50, previousBuild); runs.put(1, lastBuild); // failed builds must not be used. Instead the last successful builds before them // must be used Assert.assertEquals(project.getEstimatedDuration(), 1); } private Job createMockProject(final SortedMap<Integer, TestBuild> runs) { Job project = new Job(null, "name") { int i = 1; @Override public int assignBuildNumber() throws IOException { return i++; } @Override public SortedMap<Integer, ? extends Run> _getRuns() { return runs; } @Override public boolean isBuildable() { return true; } @Override protected void removeRun(Run run) { } @Override public BuildHistory getBuildHistoryData() { return createMockBuildHistory(_getRuns()); } public long getEstimatedDuration() { List<Run> builds = getLastBuildsOverThreshold(3, Result.UNSTABLE); if (builds.isEmpty()) { return -1; } long totalDuration = 0; for (Run b : builds) { totalDuration += b.getDuration(); } if (totalDuration == 0) { return -1; } return Math.round((double) totalDuration / builds.size()); } }; return project; } private BuildHistory createMockBuildHistory(final SortedMap<Integer, ? extends Run> runs) { return new BuildHistory() { @Override public BuildHistory.Record getFirst() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLast() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLastCompleted() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLastFailed() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLastStable() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLastUnstable() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLastSuccessful() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public BuildHistory.Record getLastUnsuccessful() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<Record> getLastRecordsOverThreshold(int n, Result threshold) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastBuild() { try { return runs.get(runs.lastKey()); } catch (NoSuchElementException e) { return null; } } @Override public Run getFirstBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastSuccessfulBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastUnsuccessfulBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastUnstableBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastStableBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastFailedBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Run getLastCompletedBuild() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List getLastBuildsOverThreshold(int n, Result threshold) { List<Run> result = new ArrayList<Run>(n); Run r = getLastBuild(); while (r != null && result.size() < n) { if (!r.isBuilding() && (r.getResult() != null && r.getResult().isBetterOrEqualTo(threshold))) { result.add(r); } r = r.getPreviousBuild(); } return result; } @Override public Iterator iterator() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List allRecords() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; } private static class TestBuild extends Run { public TestBuild(Job project, Result result, long duration, TestBuild previousBuild) throws IOException { super(project); setResult(result); this.duration = duration; this.previousBuild = previousBuild; } @Override public int compareTo(Run o) { return 0; } @Override public boolean isBuilding() { return false; } @Override public String toString() { return "TestBuild"; } } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.15 at 08:44:37 PM EDT // package org.sierraecg.schema.jaxb._1_03; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlList; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{http://www3.medical.philips.com}globalmeasurements.elements"/> * &lt;/sequence> * &lt;attribute name="fixedmultpflag" use="required" type="{http://www3.medical.philips.com}TYPEflag" /> * &lt;attribute name="multptestvalidflag" use="required" type="{http://www3.medical.philips.com}TYPEflag" /> * &lt;attribute name="qrslikeartfflag" use="required" type="{http://www3.medical.philips.com}TYPEflag" /> * &lt;attribute name="pacebeatmeasflag" use="required" type="{http://www3.medical.philips.com}TYPEflag" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "pacedetectleads", "pacepulses", "pacemodes", "pacemalf", "pacemisc", "ectopicrhythm", "qtintdispersion", "numberofcomplexes", "numberofgroups", "beatclassification", "qamessagecodes", "qaactioncode", "pon", "qrson", "qrsoff", "ton", "toff", "pfrontaxis", "phorizaxis", "i40Frontaxis", "i40Horizaxis", "qrsfrontaxis", "qrshorizaxis", "t40Frontaxis", "t40Horizaxis", "stfrontaxis", "sthorizaxis", "tfrontaxis", "thorizaxis", "atrialrate", "lowventrate", "meanventrate", "highventrate", "meanprint", "meanprseg", "meanqrsdur", "meanqtint", "meanqtc", "deltawavecount", "deltawavepercent", "bigeminycount", "bigeminystring", "trigeminycount", "trigeminystring", "wenckcount", "wenckstring", "flutterfibcount", "qrsinitangle", "qrsinitmag", "qrsmaxangle", "qrsmaxmag", "qrstermangle", "qrstermmag", "qrsrotation", "globalreserved" }) @XmlRootElement(name = "globalmeasurements") public class Globalmeasurements { @XmlList @XmlSchemaType(name = "anySimpleType") protected List<String> pacedetectleads; @XmlElement(required = true) protected Pacepulses pacepulses; @XmlElement(required = true) protected Pacemodes pacemodes; @XmlElement(required = true) protected String pacemalf; @XmlElement(required = true) protected String pacemisc; @XmlElement(required = true) protected String ectopicrhythm; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String qtintdispersion; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String numberofcomplexes; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String numberofgroups; @XmlList @XmlElement(type = Integer.class) @XmlSchemaType(name = "anySimpleType") protected List<Integer> beatclassification; @XmlElement(required = true) protected Qamessagecodes qamessagecodes; @XmlElement(required = true) @XmlSchemaType(name = "string") protected TYPEactioncode qaactioncode; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String pon; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String qrson; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String qrsoff; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String ton; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String toff; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String pfrontaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String phorizaxis; @XmlElement(name = "i40frontaxis", required = true) @XmlSchemaType(name = "anySimpleType") protected String i40Frontaxis; @XmlElement(name = "i40horizaxis", required = true) @XmlSchemaType(name = "anySimpleType") protected String i40Horizaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String qrsfrontaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String qrshorizaxis; @XmlElement(name = "t40frontaxis", required = true) @XmlSchemaType(name = "anySimpleType") protected String t40Frontaxis; @XmlElement(name = "t40horizaxis", required = true) @XmlSchemaType(name = "anySimpleType") protected String t40Horizaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String stfrontaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String sthorizaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String tfrontaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String thorizaxis; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String atrialrate; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String lowventrate; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String meanventrate; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String highventrate; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String meanprint; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String meanprseg; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String meanqrsdur; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String meanqtint; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String meanqtc; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String deltawavecount; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String deltawavepercent; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String bigeminycount; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String bigeminystring; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String trigeminycount; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String trigeminystring; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String wenckcount; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String wenckstring; @XmlElement(required = true) @XmlSchemaType(name = "anySimpleType") protected String flutterfibcount; @XmlSchemaType(name = "anySimpleType") protected String qrsinitangle; @XmlSchemaType(name = "anySimpleType") protected String qrsinitmag; @XmlSchemaType(name = "anySimpleType") protected String qrsmaxangle; @XmlSchemaType(name = "anySimpleType") protected String qrsmaxmag; @XmlSchemaType(name = "anySimpleType") protected String qrstermangle; @XmlSchemaType(name = "anySimpleType") protected String qrstermmag; @XmlSchemaType(name = "anySimpleType") protected String qrsrotation; @XmlElement(required = true) protected String globalreserved; @XmlAttribute(name = "fixedmultpflag", required = true) protected TYPEflag fixedmultpflag; @XmlAttribute(name = "multptestvalidflag", required = true) protected TYPEflag multptestvalidflag; @XmlAttribute(name = "qrslikeartfflag", required = true) protected TYPEflag qrslikeartfflag; @XmlAttribute(name = "pacebeatmeasflag", required = true) protected TYPEflag pacebeatmeasflag; /** * Gets the value of the pacedetectleads property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the pacedetectleads property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPacedetectleads().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getPacedetectleads() { if (pacedetectleads == null) { pacedetectleads = new ArrayList<String>(); } return this.pacedetectleads; } /** * Gets the value of the pacepulses property. * * @return * possible object is * {@link Pacepulses } * */ public Pacepulses getPacepulses() { return pacepulses; } /** * Sets the value of the pacepulses property. * * @param value * allowed object is * {@link Pacepulses } * */ public void setPacepulses(Pacepulses value) { this.pacepulses = value; } /** * Gets the value of the pacemodes property. * * @return * possible object is * {@link Pacemodes } * */ public Pacemodes getPacemodes() { return pacemodes; } /** * Sets the value of the pacemodes property. * * @param value * allowed object is * {@link Pacemodes } * */ public void setPacemodes(Pacemodes value) { this.pacemodes = value; } /** * Gets the value of the pacemalf property. * * @return * possible object is * {@link String } * */ public String getPacemalf() { return pacemalf; } /** * Sets the value of the pacemalf property. * * @param value * allowed object is * {@link String } * */ public void setPacemalf(String value) { this.pacemalf = value; } /** * Gets the value of the pacemisc property. * * @return * possible object is * {@link String } * */ public String getPacemisc() { return pacemisc; } /** * Sets the value of the pacemisc property. * * @param value * allowed object is * {@link String } * */ public void setPacemisc(String value) { this.pacemisc = value; } /** * Gets the value of the ectopicrhythm property. * * @return * possible object is * {@link String } * */ public String getEctopicrhythm() { return ectopicrhythm; } /** * Sets the value of the ectopicrhythm property. * * @param value * allowed object is * {@link String } * */ public void setEctopicrhythm(String value) { this.ectopicrhythm = value; } /** * Gets the value of the qtintdispersion property. * * @return * possible object is * {@link String } * */ public String getQtintdispersion() { return qtintdispersion; } /** * Sets the value of the qtintdispersion property. * * @param value * allowed object is * {@link String } * */ public void setQtintdispersion(String value) { this.qtintdispersion = value; } /** * Gets the value of the numberofcomplexes property. * * @return * possible object is * {@link String } * */ public String getNumberofcomplexes() { return numberofcomplexes; } /** * Sets the value of the numberofcomplexes property. * * @param value * allowed object is * {@link String } * */ public void setNumberofcomplexes(String value) { this.numberofcomplexes = value; } /** * Gets the value of the numberofgroups property. * * @return * possible object is * {@link String } * */ public String getNumberofgroups() { return numberofgroups; } /** * Sets the value of the numberofgroups property. * * @param value * allowed object is * {@link String } * */ public void setNumberofgroups(String value) { this.numberofgroups = value; } /** * Gets the value of the beatclassification property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the beatclassification property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBeatclassification().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Integer } * * */ public List<Integer> getBeatclassification() { if (beatclassification == null) { beatclassification = new ArrayList<Integer>(); } return this.beatclassification; } /** * Gets the value of the qamessagecodes property. * * @return * possible object is * {@link Qamessagecodes } * */ public Qamessagecodes getQamessagecodes() { return qamessagecodes; } /** * Sets the value of the qamessagecodes property. * * @param value * allowed object is * {@link Qamessagecodes } * */ public void setQamessagecodes(Qamessagecodes value) { this.qamessagecodes = value; } /** * Gets the value of the qaactioncode property. * * @return * possible object is * {@link TYPEactioncode } * */ public TYPEactioncode getQaactioncode() { return qaactioncode; } /** * Sets the value of the qaactioncode property. * * @param value * allowed object is * {@link TYPEactioncode } * */ public void setQaactioncode(TYPEactioncode value) { this.qaactioncode = value; } /** * Gets the value of the pon property. * * @return * possible object is * {@link String } * */ public String getPon() { return pon; } /** * Sets the value of the pon property. * * @param value * allowed object is * {@link String } * */ public void setPon(String value) { this.pon = value; } /** * Gets the value of the qrson property. * * @return * possible object is * {@link String } * */ public String getQrson() { return qrson; } /** * Sets the value of the qrson property. * * @param value * allowed object is * {@link String } * */ public void setQrson(String value) { this.qrson = value; } /** * Gets the value of the qrsoff property. * * @return * possible object is * {@link String } * */ public String getQrsoff() { return qrsoff; } /** * Sets the value of the qrsoff property. * * @param value * allowed object is * {@link String } * */ public void setQrsoff(String value) { this.qrsoff = value; } /** * Gets the value of the ton property. * * @return * possible object is * {@link String } * */ public String getTon() { return ton; } /** * Sets the value of the ton property. * * @param value * allowed object is * {@link String } * */ public void setTon(String value) { this.ton = value; } /** * Gets the value of the toff property. * * @return * possible object is * {@link String } * */ public String getToff() { return toff; } /** * Sets the value of the toff property. * * @param value * allowed object is * {@link String } * */ public void setToff(String value) { this.toff = value; } /** * Gets the value of the pfrontaxis property. * * @return * possible object is * {@link String } * */ public String getPfrontaxis() { return pfrontaxis; } /** * Sets the value of the pfrontaxis property. * * @param value * allowed object is * {@link String } * */ public void setPfrontaxis(String value) { this.pfrontaxis = value; } /** * Gets the value of the phorizaxis property. * * @return * possible object is * {@link String } * */ public String getPhorizaxis() { return phorizaxis; } /** * Sets the value of the phorizaxis property. * * @param value * allowed object is * {@link String } * */ public void setPhorizaxis(String value) { this.phorizaxis = value; } /** * Gets the value of the i40Frontaxis property. * * @return * possible object is * {@link String } * */ public String getI40Frontaxis() { return i40Frontaxis; } /** * Sets the value of the i40Frontaxis property. * * @param value * allowed object is * {@link String } * */ public void setI40Frontaxis(String value) { this.i40Frontaxis = value; } /** * Gets the value of the i40Horizaxis property. * * @return * possible object is * {@link String } * */ public String getI40Horizaxis() { return i40Horizaxis; } /** * Sets the value of the i40Horizaxis property. * * @param value * allowed object is * {@link String } * */ public void setI40Horizaxis(String value) { this.i40Horizaxis = value; } /** * Gets the value of the qrsfrontaxis property. * * @return * possible object is * {@link String } * */ public String getQrsfrontaxis() { return qrsfrontaxis; } /** * Sets the value of the qrsfrontaxis property. * * @param value * allowed object is * {@link String } * */ public void setQrsfrontaxis(String value) { this.qrsfrontaxis = value; } /** * Gets the value of the qrshorizaxis property. * * @return * possible object is * {@link String } * */ public String getQrshorizaxis() { return qrshorizaxis; } /** * Sets the value of the qrshorizaxis property. * * @param value * allowed object is * {@link String } * */ public void setQrshorizaxis(String value) { this.qrshorizaxis = value; } /** * Gets the value of the t40Frontaxis property. * * @return * possible object is * {@link String } * */ public String getT40Frontaxis() { return t40Frontaxis; } /** * Sets the value of the t40Frontaxis property. * * @param value * allowed object is * {@link String } * */ public void setT40Frontaxis(String value) { this.t40Frontaxis = value; } /** * Gets the value of the t40Horizaxis property. * * @return * possible object is * {@link String } * */ public String getT40Horizaxis() { return t40Horizaxis; } /** * Sets the value of the t40Horizaxis property. * * @param value * allowed object is * {@link String } * */ public void setT40Horizaxis(String value) { this.t40Horizaxis = value; } /** * Gets the value of the stfrontaxis property. * * @return * possible object is * {@link String } * */ public String getStfrontaxis() { return stfrontaxis; } /** * Sets the value of the stfrontaxis property. * * @param value * allowed object is * {@link String } * */ public void setStfrontaxis(String value) { this.stfrontaxis = value; } /** * Gets the value of the sthorizaxis property. * * @return * possible object is * {@link String } * */ public String getSthorizaxis() { return sthorizaxis; } /** * Sets the value of the sthorizaxis property. * * @param value * allowed object is * {@link String } * */ public void setSthorizaxis(String value) { this.sthorizaxis = value; } /** * Gets the value of the tfrontaxis property. * * @return * possible object is * {@link String } * */ public String getTfrontaxis() { return tfrontaxis; } /** * Sets the value of the tfrontaxis property. * * @param value * allowed object is * {@link String } * */ public void setTfrontaxis(String value) { this.tfrontaxis = value; } /** * Gets the value of the thorizaxis property. * * @return * possible object is * {@link String } * */ public String getThorizaxis() { return thorizaxis; } /** * Sets the value of the thorizaxis property. * * @param value * allowed object is * {@link String } * */ public void setThorizaxis(String value) { this.thorizaxis = value; } /** * Gets the value of the atrialrate property. * * @return * possible object is * {@link String } * */ public String getAtrialrate() { return atrialrate; } /** * Sets the value of the atrialrate property. * * @param value * allowed object is * {@link String } * */ public void setAtrialrate(String value) { this.atrialrate = value; } /** * Gets the value of the lowventrate property. * * @return * possible object is * {@link String } * */ public String getLowventrate() { return lowventrate; } /** * Sets the value of the lowventrate property. * * @param value * allowed object is * {@link String } * */ public void setLowventrate(String value) { this.lowventrate = value; } /** * Gets the value of the meanventrate property. * * @return * possible object is * {@link String } * */ public String getMeanventrate() { return meanventrate; } /** * Sets the value of the meanventrate property. * * @param value * allowed object is * {@link String } * */ public void setMeanventrate(String value) { this.meanventrate = value; } /** * Gets the value of the highventrate property. * * @return * possible object is * {@link String } * */ public String getHighventrate() { return highventrate; } /** * Sets the value of the highventrate property. * * @param value * allowed object is * {@link String } * */ public void setHighventrate(String value) { this.highventrate = value; } /** * Gets the value of the meanprint property. * * @return * possible object is * {@link String } * */ public String getMeanprint() { return meanprint; } /** * Sets the value of the meanprint property. * * @param value * allowed object is * {@link String } * */ public void setMeanprint(String value) { this.meanprint = value; } /** * Gets the value of the meanprseg property. * * @return * possible object is * {@link String } * */ public String getMeanprseg() { return meanprseg; } /** * Sets the value of the meanprseg property. * * @param value * allowed object is * {@link String } * */ public void setMeanprseg(String value) { this.meanprseg = value; } /** * Gets the value of the meanqrsdur property. * * @return * possible object is * {@link String } * */ public String getMeanqrsdur() { return meanqrsdur; } /** * Sets the value of the meanqrsdur property. * * @param value * allowed object is * {@link String } * */ public void setMeanqrsdur(String value) { this.meanqrsdur = value; } /** * Gets the value of the meanqtint property. * * @return * possible object is * {@link String } * */ public String getMeanqtint() { return meanqtint; } /** * Sets the value of the meanqtint property. * * @param value * allowed object is * {@link String } * */ public void setMeanqtint(String value) { this.meanqtint = value; } /** * Gets the value of the meanqtc property. * * @return * possible object is * {@link String } * */ public String getMeanqtc() { return meanqtc; } /** * Sets the value of the meanqtc property. * * @param value * allowed object is * {@link String } * */ public void setMeanqtc(String value) { this.meanqtc = value; } /** * Gets the value of the deltawavecount property. * * @return * possible object is * {@link String } * */ public String getDeltawavecount() { return deltawavecount; } /** * Sets the value of the deltawavecount property. * * @param value * allowed object is * {@link String } * */ public void setDeltawavecount(String value) { this.deltawavecount = value; } /** * Gets the value of the deltawavepercent property. * * @return * possible object is * {@link String } * */ public String getDeltawavepercent() { return deltawavepercent; } /** * Sets the value of the deltawavepercent property. * * @param value * allowed object is * {@link String } * */ public void setDeltawavepercent(String value) { this.deltawavepercent = value; } /** * Gets the value of the bigeminycount property. * * @return * possible object is * {@link String } * */ public String getBigeminycount() { return bigeminycount; } /** * Sets the value of the bigeminycount property. * * @param value * allowed object is * {@link String } * */ public void setBigeminycount(String value) { this.bigeminycount = value; } /** * Gets the value of the bigeminystring property. * * @return * possible object is * {@link String } * */ public String getBigeminystring() { return bigeminystring; } /** * Sets the value of the bigeminystring property. * * @param value * allowed object is * {@link String } * */ public void setBigeminystring(String value) { this.bigeminystring = value; } /** * Gets the value of the trigeminycount property. * * @return * possible object is * {@link String } * */ public String getTrigeminycount() { return trigeminycount; } /** * Sets the value of the trigeminycount property. * * @param value * allowed object is * {@link String } * */ public void setTrigeminycount(String value) { this.trigeminycount = value; } /** * Gets the value of the trigeminystring property. * * @return * possible object is * {@link String } * */ public String getTrigeminystring() { return trigeminystring; } /** * Sets the value of the trigeminystring property. * * @param value * allowed object is * {@link String } * */ public void setTrigeminystring(String value) { this.trigeminystring = value; } /** * Gets the value of the wenckcount property. * * @return * possible object is * {@link String } * */ public String getWenckcount() { return wenckcount; } /** * Sets the value of the wenckcount property. * * @param value * allowed object is * {@link String } * */ public void setWenckcount(String value) { this.wenckcount = value; } /** * Gets the value of the wenckstring property. * * @return * possible object is * {@link String } * */ public String getWenckstring() { return wenckstring; } /** * Sets the value of the wenckstring property. * * @param value * allowed object is * {@link String } * */ public void setWenckstring(String value) { this.wenckstring = value; } /** * Gets the value of the flutterfibcount property. * * @return * possible object is * {@link String } * */ public String getFlutterfibcount() { return flutterfibcount; } /** * Sets the value of the flutterfibcount property. * * @param value * allowed object is * {@link String } * */ public void setFlutterfibcount(String value) { this.flutterfibcount = value; } /** * Gets the value of the qrsinitangle property. * * @return * possible object is * {@link String } * */ public String getQrsinitangle() { return qrsinitangle; } /** * Sets the value of the qrsinitangle property. * * @param value * allowed object is * {@link String } * */ public void setQrsinitangle(String value) { this.qrsinitangle = value; } /** * Gets the value of the qrsinitmag property. * * @return * possible object is * {@link String } * */ public String getQrsinitmag() { return qrsinitmag; } /** * Sets the value of the qrsinitmag property. * * @param value * allowed object is * {@link String } * */ public void setQrsinitmag(String value) { this.qrsinitmag = value; } /** * Gets the value of the qrsmaxangle property. * * @return * possible object is * {@link String } * */ public String getQrsmaxangle() { return qrsmaxangle; } /** * Sets the value of the qrsmaxangle property. * * @param value * allowed object is * {@link String } * */ public void setQrsmaxangle(String value) { this.qrsmaxangle = value; } /** * Gets the value of the qrsmaxmag property. * * @return * possible object is * {@link String } * */ public String getQrsmaxmag() { return qrsmaxmag; } /** * Sets the value of the qrsmaxmag property. * * @param value * allowed object is * {@link String } * */ public void setQrsmaxmag(String value) { this.qrsmaxmag = value; } /** * Gets the value of the qrstermangle property. * * @return * possible object is * {@link String } * */ public String getQrstermangle() { return qrstermangle; } /** * Sets the value of the qrstermangle property. * * @param value * allowed object is * {@link String } * */ public void setQrstermangle(String value) { this.qrstermangle = value; } /** * Gets the value of the qrstermmag property. * * @return * possible object is * {@link String } * */ public String getQrstermmag() { return qrstermmag; } /** * Sets the value of the qrstermmag property. * * @param value * allowed object is * {@link String } * */ public void setQrstermmag(String value) { this.qrstermmag = value; } /** * Gets the value of the qrsrotation property. * * @return * possible object is * {@link String } * */ public String getQrsrotation() { return qrsrotation; } /** * Sets the value of the qrsrotation property. * * @param value * allowed object is * {@link String } * */ public void setQrsrotation(String value) { this.qrsrotation = value; } /** * Gets the value of the globalreserved property. * * @return * possible object is * {@link String } * */ public String getGlobalreserved() { return globalreserved; } /** * Sets the value of the globalreserved property. * * @param value * allowed object is * {@link String } * */ public void setGlobalreserved(String value) { this.globalreserved = value; } /** * Gets the value of the fixedmultpflag property. * * @return * possible object is * {@link TYPEflag } * */ public TYPEflag getFixedmultpflag() { return fixedmultpflag; } /** * Sets the value of the fixedmultpflag property. * * @param value * allowed object is * {@link TYPEflag } * */ public void setFixedmultpflag(TYPEflag value) { this.fixedmultpflag = value; } /** * Gets the value of the multptestvalidflag property. * * @return * possible object is * {@link TYPEflag } * */ public TYPEflag getMultptestvalidflag() { return multptestvalidflag; } /** * Sets the value of the multptestvalidflag property. * * @param value * allowed object is * {@link TYPEflag } * */ public void setMultptestvalidflag(TYPEflag value) { this.multptestvalidflag = value; } /** * Gets the value of the qrslikeartfflag property. * * @return * possible object is * {@link TYPEflag } * */ public TYPEflag getQrslikeartfflag() { return qrslikeartfflag; } /** * Sets the value of the qrslikeartfflag property. * * @param value * allowed object is * {@link TYPEflag } * */ public void setQrslikeartfflag(TYPEflag value) { this.qrslikeartfflag = value; } /** * Gets the value of the pacebeatmeasflag property. * * @return * possible object is * {@link TYPEflag } * */ public TYPEflag getPacebeatmeasflag() { return pacebeatmeasflag; } /** * Sets the value of the pacebeatmeasflag property. * * @param value * allowed object is * {@link TYPEflag } * */ public void setPacebeatmeasflag(TYPEflag value) { this.pacebeatmeasflag = value; } }
/** */ package kieker.model.analysismodel.type.impl; import kieker.model.analysismodel.type.OperationType; import kieker.model.analysismodel.type.TypePackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.BasicEMap; import org.eclipse.emf.common.util.EMap; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Interface EString To Operation Type Map Entry</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link kieker.model.analysismodel.type.impl.InterfaceEStringToOperationTypeMapEntryImpl#getTypedKey <em>Key</em>}</li> * <li>{@link kieker.model.analysismodel.type.impl.InterfaceEStringToOperationTypeMapEntryImpl#getTypedValue <em>Value</em>}</li> * </ul> * * @generated */ public class InterfaceEStringToOperationTypeMapEntryImpl extends MinimalEObjectImpl.Container implements BasicEMap.Entry<String,OperationType> { /** * The default value of the '{@link #getTypedKey() <em>Key</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypedKey() * @generated * @ordered */ protected static final String KEY_EDEFAULT = null; /** * The cached value of the '{@link #getTypedKey() <em>Key</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypedKey() * @generated * @ordered */ protected String key = KEY_EDEFAULT; /** * The cached value of the '{@link #getTypedValue() <em>Value</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypedValue() * @generated * @ordered */ protected OperationType value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected InterfaceEStringToOperationTypeMapEntryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TypePackage.Literals.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getTypedKey() { return key; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTypedKey(String newKey) { String oldKey = key; key = newKey; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__KEY, oldKey, key)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OperationType getTypedValue() { if (value != null && value.eIsProxy()) { InternalEObject oldValue = (InternalEObject)value; value = (OperationType)eResolveProxy(oldValue); if (value != oldValue) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__VALUE, oldValue, value)); } } return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OperationType basicGetTypedValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTypedValue(OperationType newValue) { OperationType oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__VALUE, oldValue, value)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__KEY: return getTypedKey(); case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__VALUE: if (resolve) return getTypedValue(); return basicGetTypedValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__KEY: setTypedKey((String)newValue); return; case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__VALUE: setTypedValue((OperationType)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__KEY: setTypedKey(KEY_EDEFAULT); return; case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__VALUE: setTypedValue((OperationType)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__KEY: return KEY_EDEFAULT == null ? key != null : !KEY_EDEFAULT.equals(key); case TypePackage.INTERFACE_ESTRING_TO_OPERATION_TYPE_MAP_ENTRY__VALUE: return value != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (key: "); result.append(key); result.append(')'); return result.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected int hash = -1; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int getHash() { if (hash == -1) { Object theKey = getKey(); hash = (theKey == null ? 0 : theKey.hashCode()); } return hash; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setHash(int hash) { this.hash = hash; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getKey() { return getTypedKey(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setKey(String key) { setTypedKey(key); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public OperationType getValue() { return getTypedValue(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public OperationType setValue(OperationType value) { OperationType oldValue = getValue(); setTypedValue(value); return oldValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") public EMap<String, OperationType> getEMap() { EObject container = eContainer(); return container == null ? null : (EMap<String, OperationType>)container.eGet(eContainmentFeature()); } } //InterfaceEStringToOperationTypeMapEntryImpl
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.concurrent; import org.apache.flink.util.Preconditions; import javax.annotation.Nonnull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; /** * Simple {@link ScheduledExecutor} implementation for testing purposes. */ public class ManuallyTriggeredScheduledExecutor implements ScheduledExecutor { private final Executor executorDelegate; private final ArrayDeque<Runnable> queuedRunnables = new ArrayDeque<>(); private final ConcurrentLinkedQueue<ScheduledTask<?>> nonPeriodicScheduledTasks = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<ScheduledTask<?>> periodicScheduledTasks = new ConcurrentLinkedQueue<>(); public ManuallyTriggeredScheduledExecutor() { this.executorDelegate = Runnable::run; } @Override public void execute(@Nonnull Runnable command) { synchronized (queuedRunnables) { queuedRunnables.addLast(command); } } /** Triggers all {@code queuedRunnables}. */ public void triggerAll() { while (numQueuedRunnables() > 0) { trigger(); } } /** * Triggers the next queued runnable and executes it synchronously. * This method throws an exception if no Runnable is currently queued. */ public void trigger() { final Runnable next; synchronized (queuedRunnables) { next = queuedRunnables.removeFirst(); } CompletableFuture.runAsync(next, executorDelegate).join(); } /** * Gets the number of Runnables currently queued. */ public int numQueuedRunnables() { synchronized (queuedRunnables) { return queuedRunnables.size(); } } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return insertNonPeriodicTask(command, delay, unit); } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return insertNonPeriodicTask(callable, delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return insertPeriodicRunnable(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return insertPeriodicRunnable(command, initialDelay, delay, unit); } public Collection<ScheduledFuture<?>> getScheduledTasks() { final ArrayList<ScheduledFuture<?>> scheduledTasks = new ArrayList<>(nonPeriodicScheduledTasks.size() + periodicScheduledTasks.size()); scheduledTasks.addAll(getNonPeriodicScheduledTask()); scheduledTasks.addAll(getPeriodicScheduledTask()); return scheduledTasks; } public Collection<ScheduledFuture<?>> getPeriodicScheduledTask() { return periodicScheduledTasks .stream() .filter(scheduledTask -> !scheduledTask.isCancelled()) .collect(Collectors.toList()); } public Collection<ScheduledFuture<?>> getNonPeriodicScheduledTask() { return nonPeriodicScheduledTasks .stream() .filter(scheduledTask -> !scheduledTask.isCancelled()) .collect(Collectors.toList()); } /** * Triggers all registered tasks. */ public void triggerScheduledTasks() { triggerPeriodicScheduledTasks(); triggerNonPeriodicScheduledTasks(); } /** * Triggers a single non-periodically scheduled task. * * @throws NoSuchElementException If there is no such task. */ public void triggerNonPeriodicScheduledTask() { final ScheduledTask<?> poll = nonPeriodicScheduledTasks.remove(); if (poll != null) { poll.execute(); } } public void triggerNonPeriodicScheduledTasks() { final Iterator<ScheduledTask<?>> iterator = nonPeriodicScheduledTasks.iterator(); while (iterator.hasNext()) { final ScheduledTask<?> scheduledTask = iterator.next(); if (!scheduledTask.isCancelled()) { scheduledTask.execute(); } iterator.remove(); } } public void triggerPeriodicScheduledTasks() { for (ScheduledTask<?> scheduledTask : periodicScheduledTasks) { if (!scheduledTask.isCancelled()) { scheduledTask.execute(); } } } private ScheduledFuture<?> insertPeriodicRunnable( Runnable command, long delay, long period, TimeUnit unit) { final ScheduledTask<?> scheduledTask = new ScheduledTask<>( () -> { command.run(); return null; }, unit.convert(delay, TimeUnit.MILLISECONDS), unit.convert(period, TimeUnit.MILLISECONDS)); periodicScheduledTasks.offer(scheduledTask); return scheduledTask; } private ScheduledFuture<?> insertNonPeriodicTask(Runnable command, long delay, TimeUnit unit) { return insertNonPeriodicTask(() -> { command.run(); return null; }, delay, unit); } private <V> ScheduledFuture<V> insertNonPeriodicTask( Callable<V> callable, long delay, TimeUnit unit) { final ScheduledTask<V> scheduledTask = new ScheduledTask<>(callable, unit.convert(delay, TimeUnit.MILLISECONDS)); nonPeriodicScheduledTasks.offer(scheduledTask); return scheduledTask; } private static final class ScheduledTask<T> implements ScheduledFuture<T> { private final Callable<T> callable; private final long delay; private final long period; private final CompletableFuture<T> result; private ScheduledTask(Callable<T> callable, long delay) { this(callable, delay, 0); } private ScheduledTask(Callable<T> callable, long delay, long period) { this.callable = Preconditions.checkNotNull(callable); this.result = new CompletableFuture<>(); this.delay = delay; this.period = period; } private boolean isPeriodic() { return period > 0; } public void execute() { if (!result.isDone()) { if (!isPeriodic()) { try { result.complete(callable.call()); } catch (Exception e) { result.completeExceptionally(e); } } else { try { callable.call(); } catch (Exception e) { result.completeExceptionally(e); } } } } @Override public long getDelay(TimeUnit unit) { return unit.convert(delay, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { return Long.compare(getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS)); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return result.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return result.isCancelled(); } @Override public boolean isDone() { return result.isDone(); } @Override public T get() throws InterruptedException, ExecutionException { return result.get(); } @Override public T get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return result.get(timeout, unit); } } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2016 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.parosproxy.paros.core.scanner; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.List; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; import org.parosproxy.paros.network.HttpHeaderField; import org.parosproxy.paros.network.HttpMalformedHeaderException; import org.parosproxy.paros.network.HttpMessage; import org.parosproxy.paros.network.HttpRequestHeader; /** * Unit test for {@link VariantHeader}. */ public class VariantHeaderUnitTest { @Test public void shouldHaveParametersListEmptyByDefault() { // Given VariantHeader variantHeader = new VariantHeader(); // When List<NameValuePair> parameters = variantHeader.getParamList(); // Then assertThat(parameters, is(empty())); } @Test(expected = UnsupportedOperationException.class) public void shouldNotAllowToModifyReturnedParametersList() { // Given VariantHeader variantHeader = new VariantHeader(); // When variantHeader.getParamList().add(header("Name", "Value", 0)); // Then = UnsupportedOperationException } @Test(expected = IllegalArgumentException.class) public void shouldFailToExtractParametersFromUndefinedMessage() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage undefinedMessage = null; // When variantHeader.setMessage(undefinedMessage); // Then = IllegalArgumentException } @Test public void shouldNotExtractAnyParameterIfThereAreNoHeaders() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage messageWithHeaders = createMessageWithoutInjectableHeaders(); // When variantHeader.setMessage(messageWithHeaders); // Then assertThat(variantHeader.getParamList(), is(empty())); } @Test public void shouldNotExtractAnyParameterIfThereAreNoInjectableHeaders() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage messageWithHeaders = createMessageWithHeaders( header(HttpRequestHeader.CONTENT_LENGTH, "A"), header(HttpRequestHeader.PRAGMA, "1"), header(HttpRequestHeader.CACHE_CONTROL, "B"), header(HttpRequestHeader.COOKIE, "3"), header(HttpRequestHeader.AUTHORIZATION, "C"), header(HttpRequestHeader.PROXY_AUTHORIZATION, "5"), header(HttpRequestHeader.CONNECTION, "D"), header(HttpRequestHeader.PROXY_CONNECTION, "7"), header(HttpRequestHeader.IF_MODIFIED_SINCE, "E"), header(HttpRequestHeader.IF_NONE_MATCH, "9"), header(HttpRequestHeader.X_CSRF_TOKEN, "F"), header(HttpRequestHeader.X_CSRFTOKEN, "11"), header(HttpRequestHeader.X_XSRF_TOKEN, "G"), header(HttpRequestHeader.X_ZAP_SCAN_ID, "13"), header(HttpRequestHeader.X_ZAP_REQUESTID, "H"), header(HttpRequestHeader.X_SECURITY_PROXY, "15")); // When variantHeader.setMessage(messageWithHeaders); // Then assertThat(variantHeader.getParamList(), is(empty())); } @Test public void shouldExtractParametersFromInjectableHeaders() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage messageWithHeaders = createMessageWithHeaders( header("X-Header-A", "X"), header("X-Header-B", "Y"), header("X-Header-C", "Z")); // When variantHeader.setMessage(messageWithHeaders); // Then assertThat(variantHeader.getParamList().size(), is(equalTo(3))); assertThat( variantHeader.getParamList(), contains(header("X-Header-A", "X", 0), header("X-Header-B", "Y", 1), header("X-Header-C", "Z", 2))); } @Test public void shouldExtractParametersFromInjectableHeadersEvenIfThereAreNoInjectableHeaders() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage messageWithHeaders = createMessageWithHeaders( header(HttpRequestHeader.CONTENT_LENGTH, "A"), header("X-Header-A", "X"), header(HttpRequestHeader.CONNECTION, "D"), header("X-Header-B", "Y"), header(HttpRequestHeader.PROXY_AUTHORIZATION, "5"), header("X-Header-C", "Z")); // When variantHeader.setMessage(messageWithHeaders); // Then assertThat(variantHeader.getParamList().size(), is(equalTo(3))); assertThat( variantHeader.getParamList(), contains(header("X-Header-A", "X", 0), header("X-Header-B", "Y", 1), header("X-Header-C", "Z", 2))); } @Test public void shouldNotAccumulateExtractedParameters() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage messageWithHeaders = createMessageWithHeaders( header("X-Header-A", "X"), header("X-Header-B", "Y"), header("X-Header-C", "Z")); HttpMessage otherMessageWithHeaders = createMessageWithHeaders( header("X-Header-D", "1"), header("X-Header-E", "2"), header("X-Header-F", "3")); // When variantHeader.setMessage(messageWithHeaders); variantHeader.setMessage(otherMessageWithHeaders); // Then assertThat(variantHeader.getParamList().size(), is(equalTo(3))); assertThat( variantHeader.getParamList(), contains(header("X-Header-D", "1", 0), header("X-Header-E", "2", 1), header("X-Header-F", "3", 2))); } @Test public void shouldInjectHeaderValueModification() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage message = createMessageWithHeaders( header("X-Header-A", "X"), header("X-Header-B", "Y"), header("X-Header-C", "Z")); variantHeader.setMessage(message); // When String injectedHeader = variantHeader.setParameter(message, header("X-Header-A", "X", 0), "X-Header-A", "Value"); // Then assertThat(injectedHeader, is(equalTo("X-Header-A: Value"))); assertThat(message, containsHeader("X-Header-A", "Value")); } @Test public void shouldRemoveHeaderIfInjectedHeaderValueIsNull() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage message = createMessageWithHeaders( header("X-Header-A", "X"), header("X-Header-B", "Y"), header("X-Header-C", "Z")); variantHeader.setMessage(message); // When String injectedHeader = variantHeader.setParameter(message, header("X-Header-A", "X", 0), "X-Header-A", null); // Then assertThat(injectedHeader, is(equalTo(""))); assertThat(message.getRequestHeader().getHeader("X-Header-A"), is((String) null)); } @Test public void shouldIgnoreChangesToHeaderName() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage message = createMessageWithHeaders( header("X-Header-A", "X"), header("X-Header-B", "Y"), header("X-Header-C", "Z")); variantHeader.setMessage(message); // When String injectedHeader = variantHeader.setParameter(message, header("X-Header-A", "X", 0), "X-Header-Z", "X"); // Then assertThat(injectedHeader, is(equalTo("X-Header-A: X"))); assertThat(message, containsHeader("X-Header-A", "X")); } @Test public void shouldHaveSameEffectInjectingEscapedHeaderValueModification() { // Given VariantHeader variantHeader = new VariantHeader(); HttpMessage message = createMessageWithHeaders( header("X-Header-A", "X"), header("X-Header-B", "Y"), header("X-Header-C", "Z")); variantHeader.setMessage(message); // When String injectedHeader = variantHeader.setEscapedParameter(message, header("X-Header-A", "X", 0), "X-Header-A", "Value"); // Then assertThat(injectedHeader, is(equalTo("X-Header-A: Value"))); assertThat(message, containsHeader("X-Header-A", "Value")); } private static HttpMessage createMessageWithoutInjectableHeaders() { HttpMessage message = new HttpMessage(); try { message.setRequestHeader("GET / HTTP/1.1\r\n"); } catch (HttpMalformedHeaderException e) { throw new RuntimeException(e); } return message; } private static HttpMessage createMessageWithHeaders(NameValuePair... headers) { HttpMessage message = new HttpMessage(); try { StringBuilder requestHeaderBuilder = new StringBuilder("GET / HTTP/1.1\r\n"); for (NameValuePair header : headers) { requestHeaderBuilder.append(header.getName()); requestHeaderBuilder.append(": "); requestHeaderBuilder.append(header.getValue()); requestHeaderBuilder.append("\r\n"); } message.setRequestHeader(requestHeaderBuilder.toString()); } catch (HttpMalformedHeaderException e) { throw new RuntimeException(e); } return message; } private static NameValuePair header(String name, String value) { return new NameValuePair(NameValuePair.TYPE_HEADER, name, value, 0); } private static NameValuePair header(String name, String value, int position) { return new NameValuePair(NameValuePair.TYPE_HEADER, name, value, position); } private static Matcher<HttpMessage> containsHeader(final String name, final String value) { return new BaseMatcher<HttpMessage>() { @Override public boolean matches(Object actualValue) { HttpMessage message = (HttpMessage) actualValue; List<HttpHeaderField> headers = message.getRequestHeader().getHeaders(); if (headers.isEmpty()) { return false; } for (HttpHeaderField header : headers) { if (name.equals(header.getName()) && value.equals(header.getValue())) { return true; } } return false; } @Override public void describeTo(Description description) { description.appendText("header ").appendValue(name + ": " + value); } public void describeMismatch(Object item, Description description) { HttpMessage message = (HttpMessage) item; List<HttpHeaderField> headers = message.getRequestHeader().getHeaders(); if (headers.isEmpty()) { description.appendText("has no headers"); } else { description.appendText("was ").appendValue(headers); } } }; } }
package com.wonderpush.sdk; import android.net.Uri; import android.os.Bundle; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; public class JSONUtil { public static void merge(JSONObject base, JSONObject diff) throws JSONException { merge(base, diff, true); } public static void merge(JSONObject base, JSONObject diff, boolean nullFieldRemoves) throws JSONException { if (base == null) throw new NullPointerException(); if (diff == null) return; Iterator<String> it = diff.keys(); while (it.hasNext()) { String key = it.next(); Object vDiff = diff.get(key); if (!base.has(key)) { if (vDiff instanceof JSONObject) { vDiff = new JSONObject(vDiff.toString()); } else if (vDiff instanceof JSONArray) { vDiff = new JSONArray(vDiff.toString()); } if ((vDiff != null && vDiff != JSONObject.NULL) || !nullFieldRemoves) { base.put(key, vDiff); } } else if (vDiff instanceof JSONObject) { Object vBase = base.get(key); if (vBase instanceof JSONObject) { merge((JSONObject)vBase, (JSONObject)vDiff, nullFieldRemoves); } else { base.put(key, vDiff); } } else if (vDiff instanceof JSONArray) { base.put(key, new JSONArray(vDiff.toString())); } else if ((vDiff == null || vDiff == JSONObject.NULL) && nullFieldRemoves) { base.remove(key); } else { base.put(key, vDiff); } } } public static JSONObject diff(JSONObject from, JSONObject to) throws JSONException { if (from == null) { if (to == null) { return null; } else { return new JSONObject(to.toString()); } } else if (to == null) { return null; } JSONObject rtn = new JSONObject(); Iterator<String> it; it = from.keys(); while (it.hasNext()) { String key = it.next(); if (!to.has(key)) { rtn.put(key, JSONObject.NULL); continue; } Object vFrom = from.opt(key); Object vTo = to.opt(key); if (!equals(vFrom, vTo)) { if (vFrom instanceof JSONObject && vTo instanceof JSONObject) { rtn.put(key, diff((JSONObject)vFrom, (JSONObject)vTo)); } else if (vTo instanceof JSONObject) { rtn.put(key, new JSONObject(vTo.toString())); } else if (vTo instanceof JSONArray) { rtn.put(key, new JSONArray(vTo.toString())); } else { rtn.put(key, vTo); } } } it = to.keys(); while (it.hasNext()) { String key = it.next(); if (from.has(key)) continue; Object vTo = to.opt(key); if (vTo instanceof JSONObject) { rtn.put(key, new JSONObject(vTo.toString())); } else if (vTo instanceof JSONArray) { rtn.put(key, new JSONArray(vTo.toString())); } else { rtn.put(key, vTo); } } return rtn; } public static void stripNulls(JSONObject object) throws JSONException { if (object == null) return; Iterator<String> it = object.keys(); while (it.hasNext()) { String key = it.next(); Object value = object.opt(key); if (value == null || value == JSONObject.NULL) { it.remove(); } else if (value instanceof JSONObject) { stripNulls((JSONObject) value); } // leave JSONArrays (and any sub-objects) untouched } } public static boolean equals(JSONObject a, JSONObject b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else if (a.length() != b.length()) { return false; } Iterator<String> it; it = a.keys(); while (it.hasNext()) { String key = it.next(); if (!b.has(key) || !equals(a.opt(key), b.opt(key))) { return false; } } return true; } public static boolean equals(JSONArray a, JSONArray b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else if (a.length() != b.length()) { return false; } for (int i = 0; i < a.length(); ++i) { if (!equals(a.opt(i), b.opt(i))) { return false; } } return true; } public static boolean equals(Object a, Object b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else if (a instanceof Number && b instanceof Number) { if (a instanceof Float || b instanceof Float || a instanceof Double || b instanceof Double) { return ((Number) a).doubleValue() == ((Number) b).doubleValue(); } return ((Number) a).longValue() == ((Number) b).longValue(); } else if (a.getClass() != b.getClass()) { return false; } else if (a instanceof JSONObject) { return equals((JSONObject)a, (JSONObject)b); } else if (a instanceof JSONArray) { return equals((JSONArray)a, (JSONArray)b); } else { return a.equals(b); } } public static String getString(JSONObject object, String field) { if (!object.has(field) || object.isNull(field)) { return null; } else { return object.optString(field, null); } } public static JSONObject deepCopy(JSONObject from) throws JSONException { if (from == null) { return null; } return new JSONObject(from.toString()); } public static Object parseAllJSONStrings(Object base) { if (base instanceof JSONObject) { JSONObject rtn = new JSONObject(); Iterator<String> it = ((JSONObject) base).keys(); while (it.hasNext()) { String key = it.next(); try { rtn.put(key, parseAllJSONStrings(((JSONObject) base).opt(key))); } catch (JSONException ex) { WonderPush.logError("Failed to copy key " + key, ex); } } return rtn; } if (base instanceof JSONArray) { JSONArray rtn = new JSONArray(); for (int i = 0; i < ((JSONArray) base).length(); ++i) { try { rtn.put(i, parseAllJSONStrings(((JSONArray) base).opt(i))); } catch (JSONException ex) { WonderPush.logError("Failed to copy value at index " + i, ex); } } return rtn; } if (base instanceof String && ((String) base).startsWith("{") && ((String) base).endsWith("}")) { try { return parseAllJSONStrings(new JSONObject((String) base)); } catch (JSONException ex) {} } if (base instanceof String && ((String) base).startsWith("[") && ((String) base).endsWith("]")) { try { return parseAllJSONStrings(new JSONArray((String) base)); } catch (JSONException ex) {} } return base; } public static String optString(JSONObject object, String field) { if (object == null) return null; if (!object.has(field) || object.isNull(field)) return null; Object value = object.opt(field); if (value instanceof String) { return (String) value; } return null; } public static Boolean optBoolean(JSONObject object, String field) { if (object == null) return null; if (!object.has(field) || object.isNull(field)) return null; Object value = object.opt(field); if (value instanceof Boolean) { return (Boolean) value; } return null; } public static Integer optInteger(JSONObject object, String field) { if (object == null) return null; if (!object.has(field) || object.isNull(field)) return null; Object value = object.opt(field); if (value instanceof Integer) { return (Integer) value; } else if (value instanceof Number) { return ((Number) value).intValue(); } return null; } public static long[] optLongArray(JSONObject object, String field) { if (object == null) return null; if (!object.has(field) || object.isNull(field)) return null; JSONArray array = object.optJSONArray(field); if (array == null) return null; long[] rtn = new long[array.length()]; for (int i = 0, l = array.length(); i < l; ++i) { Object value = array.opt(i); if (value instanceof Long) { rtn[i] = (Long) value; } else if (value instanceof Number) { rtn[i] = ((Number) value).longValue(); } else { return null; } } return rtn; } public static Uri optUri(JSONObject object, String field) { if (object == null) return null; if (!object.has(field) || object.isNull(field)) return null; String value = object.optString(field, null); if (value == null) return null; return Uri.parse(value); } /** * @see JSONObject#wrap(Object) */ public static Object wrap(Object o) { if (o == null) { return JSONObject.NULL; } if (o instanceof JSONArray || o instanceof JSONObject) { return o; } if (o.equals(JSONObject.NULL)) { return o; } try { if (o instanceof Collection) { return new JSONArray((Collection) o); } else if (o.getClass().isArray()) { return JSONArray(o); } if (o instanceof Map) { return new JSONObject((Map) o); } if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof String) { return o; } if (o.getClass().getPackage().getName().startsWith("java.")) { return o.toString(); } } catch (Exception ignored) { } return null; } /** * @see JSONArray#JSONArray(Object) */ public static JSONArray JSONArray(Object array) throws JSONException { if (!array.getClass().isArray()) { throw new JSONException("Not a primitive array: " + array.getClass()); } final JSONArray rtn = new JSONArray(); final int length = Array.getLength(array); for (int i = 0; i < length; ++i) { rtn.put(wrap(Array.get(array, i))); } return rtn; } public static <T> List<T> JSONArrayToList(JSONArray array, Class<T> typecheck, boolean removeNulls) { final int length = array == null ? 0 : array.length(); ArrayList<T> rtn = new ArrayList<>(length); if (array != null) { for (int i = 0; i < length; ++i) { try { Object item = array.get(i); if (!typecheck.isInstance(item)) continue; if (removeNulls && item == JSONObject.NULL) continue; rtn.add(typecheck.cast(item)); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Unexpected exception in JSONArrayToList", ex); } catch (ClassCastException ex) { Log.e(WonderPush.TAG, "Unexpected exception in JSONArrayToList", ex); } } } return rtn; } public static Bundle toBundle(JSONObject input) { if (input == null) { return null; } Bundle rtn = new Bundle(); Iterator<String> it = input.keys(); while (it.hasNext()) { String key = it.next(); Object value = input.opt(key); if (value == null || value == JSONObject.NULL) { rtn.putString(key, null); } else if (value instanceof String) { rtn.putString(key, (String) value); } else if (value instanceof Boolean) { rtn.putBoolean(key, (Boolean) value); } else if (value instanceof Double) { rtn.putDouble(key, (Double) value); } else if (value instanceof Integer) { rtn.putInt(key, (Integer) value); } else if (value instanceof Long) { rtn.putLong(key, (Long) value); } else if (value instanceof Number) { rtn.putDouble(key, ((Number) value).doubleValue()); } else if (value instanceof JSONObject) { rtn.putBundle(key, toBundle((JSONObject) value)); } else if (value instanceof JSONArray) { // TODO Detect common type between all values and build an array of the appropriate type WonderPush.logError("Coercing a JSONArray into an String[] for JSONObject to Bundle conversion: " + input.toString()); JSONArray jsonArray = (JSONArray) value; int length = jsonArray.length(); String[] list = new String[length]; for (int i = 0; i < length; ++i) { list[i] = jsonArray.optString(i, null); } rtn.putStringArray(key, list); } } return rtn; } }
/****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.allseen.timeservice.sample.client.application; import org.alljoyn.bus.AboutListener; import org.alljoyn.bus.BusAttachment; import org.alljoyn.bus.SessionOpts; import org.alljoyn.bus.Status; import org.alljoyn.bus.alljoyn.DaemonInit; import org.alljoyn.services.android.security.AuthPasswordHandler; import org.alljoyn.services.android.security.SrpAnonymousKeyListener; import org.alljoyn.services.android.utils.AndroidLogger; import org.allseen.timeservice.TimeServiceConst; import android.content.Context; import android.util.Log; /** * Initializes an Alljoyn daemon and manages a list of AllJoyn devices the * daemon is announced on. This class will also enable the user to connect * Alljoyn bus attachment and disconnect from it. */ public class ProtocolManager { private static final String TAG = "ProtocolManager"; public static final String ALARM_INTERFACE = TimeServiceConst.IFNAME_PREFIX + ".Alarm"; public static final String ALARM_FACTORY_INTERFACE = TimeServiceConst.IFNAME_PREFIX + ".AlarmFactory"; public static final String CLOCK_INTERFACE = TimeServiceConst.IFNAME_PREFIX + ".Clock"; public static final String TIME_AUTHORITY_INTERFACE = TimeServiceConst.IFNAME_PREFIX + ".TimeAuthority"; public static final String TIMER_INTERFACE = TimeServiceConst.IFNAME_PREFIX + ".Timer"; public static final String TIMER_FACTORY_INTERFACE = TimeServiceConst.IFNAME_PREFIX + ".TimerFactory"; private static final String DAEMON_NAME_PREFIX = "org.alljoyn.BusNode.TimeService"; /** * Unique prefix indicated that this daemon will be advertised quietly. */ private static final String DAEMON_QUIET_PREFIX = "quiet@"; /** * Android application context. */ private Context context = null; /** * Alljoyn bus attachment. */ private static BusAttachment busAttachment = null; /** * Announce handler. */ private AboutListener announcementHandler; /** * String for Alljoyn daemon to be advertised with. */ private static String daemonName = null; /** * Initialize the device list and starts the Alljoyn daemon. * * @param context * Android application context */ protected void init(Context context, AboutListener announceHandler) { Log.i(TAG, "init"); this.context = context; this.announcementHandler = announceHandler; boolean prepareDaemonResult = DaemonInit.PrepareDaemon(context.getApplicationContext()); Log.i(TAG, "PrepareDaemon returned " + prepareDaemonResult); connectToBus(); } /** * Creates new busAttachment, connects it. Register authListener on the bus. * Starts about service client. Registers the announce handler. */ public void connectToBus() { Log.i(TAG, "connectToBus"); if (context == null) { Log.e(TAG, "Failed to connect AJ, m_context == null !!"); return; } // prepare bus attachment busAttachment = new BusAttachment(context.getPackageName(), BusAttachment.RemoteMessage.Receive); Status reqStatus = busAttachment.connect(); if (reqStatus != Status.OK) { Log.e(TAG, "failed to connect to bus"); return; } else { Log.d(TAG, "Succefully connected to bus"); } // request the name for the daemon and advertise it. daemonName = DAEMON_NAME_PREFIX + ".G" + busAttachment.getGlobalGUIDString(); int flag = BusAttachment.ALLJOYN_REQUESTNAME_FLAG_DO_NOT_QUEUE; reqStatus = busAttachment.requestName(daemonName, flag); if (reqStatus == Status.OK) { // advertise the name with a quite prefix for devices to find it Status adStatus = busAttachment.advertiseName(DAEMON_QUIET_PREFIX + daemonName, SessionOpts.TRANSPORT_ANY); if (adStatus != Status.OK) { busAttachment.releaseName(daemonName); Log.w(TAG, "failed to advertise daemon name " + daemonName); return; } else { Log.d(TAG, "Succefully advertised daemon name " + daemonName); } } try { busAttachment.registerAboutListener(announcementHandler); busAttachment.whoImplements(new String[] { TimeServiceConst.IFNAME_PREFIX + "*" }); // Add authentication listener - needed for TimeService secure calls String keyStoreFileName = context.getFileStreamPath("alljoyn_keystore").getAbsolutePath(); SrpAnonymousKeyListener m_authListener = new SrpAnonymousKeyListener(new AuthPasswordHandler() { private final String TAG = "AlljoynOnAuthPasswordHandler"; @Override public char[] getPassword(String peerName) { return SrpAnonymousKeyListener.DEFAULT_PINCODE; } @Override public void completed(String mechanism, String authPeer, boolean authenticated) { Log.d(TAG, "Auth completed: mechanism = " + mechanism + " authPeer= " + authPeer + " --> " + authenticated); if (!authenticated) { Log.e(TAG, "Failed to Authenticate"); } } }, new AndroidLogger(), new String[] { "ALLJOYN_SRP_KEYX", "ALLJOYN_ECDHE_PSK", "ALLJOYN_PIN_KEYX" }); Log.i(TAG, "m_authListener.getAuthMechanismsAsString: " + m_authListener.getAuthMechanismsAsString()); Status authStatus = busAttachment.registerAuthListener(m_authListener.getAuthMechanismsAsString(), m_authListener, keyStoreFileName); if (authStatus != Status.OK) { Log.e(TAG, "Failed to registerAuthListener"); return; } } catch (Exception e) { Log.e(TAG, "fail to startAboutClient", e); } } /** * Remove Match from Alljoyn bus attachment, Stop about client and cancel * bus advertise name. */ public void disconnectFromBus() { Log.i(TAG, "disconnectFromBus"); /* * It is important to unregister the BusObject before disconnecting from * the bus. Failing to do so could result in a resource leak. */ try { if (busAttachment != null && busAttachment.isConnected()) { busAttachment.cancelWhoImplements(new String[] { TimeServiceConst.IFNAME_PREFIX + "*" }); busAttachment.unregisterAboutListener(announcementHandler); busAttachment.cancelAdvertiseName(DAEMON_QUIET_PREFIX + daemonName, SessionOpts.TRANSPORT_ANY); busAttachment.releaseName(daemonName); busAttachment.disconnect(); busAttachment = null; } } catch (Exception e) { Log.e(TAG, "Error when disconnectFromAJ "); e.printStackTrace(); } Log.i(TAG, "bus disconnected"); } /** * * @return true if the bus is connected. */ public boolean isConnectedToBus() { if (busAttachment == null) { return false; } boolean isConnected = busAttachment.isConnected(); Log.i(TAG, "isConnectToBus = " + isConnected); return isConnected; } /** * * @return the busAttachment. */ public BusAttachment getBusAttachment() { return busAttachment; } }
/** */ package CIM15.IEC61970.Topology; import CIM15.IEC61970.Core.BaseVoltage; import CIM15.IEC61970.Core.ConnectivityNode; import CIM15.IEC61970.Core.ConnectivityNodeContainer; import CIM15.IEC61970.Core.CorePackage; import CIM15.IEC61970.Core.IdentifiedObject; import CIM15.IEC61970.Core.ReportingGroup; import CIM15.IEC61970.Core.Terminal; import CIM15.IEC61970.StateVariables.StateVariablesPackage; import CIM15.IEC61970.StateVariables.SvInjection; import CIM15.IEC61970.StateVariables.SvShortCircuit; import CIM15.IEC61970.StateVariables.SvVoltage; import CIM15.IEC61970.StateVariables.TopologicalIsland; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.BasicInternalEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Topological Node</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getSvShortCircuit <em>Sv Short Circuit</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getConnectivityNodeContainer <em>Connectivity Node Container</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getSvInjection <em>Sv Injection</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getConnectivityNodes <em>Connectivity Nodes</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getSvVoltage <em>Sv Voltage</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getBaseVoltage <em>Base Voltage</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getTopologicalIsland <em>Topological Island</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getReportingGroup <em>Reporting Group</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getTerminal <em>Terminal</em>}</li> * <li>{@link CIM15.IEC61970.Topology.TopologicalNode#getAngleRef_TopologicalIsland <em>Angle Ref Topological Island</em>}</li> * </ul> * </p> * * @generated */ public class TopologicalNode extends IdentifiedObject { /** * The cached value of the '{@link #getSvShortCircuit() <em>Sv Short Circuit</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSvShortCircuit() * @generated * @ordered */ protected SvShortCircuit svShortCircuit; /** * The cached value of the '{@link #getConnectivityNodeContainer() <em>Connectivity Node Container</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConnectivityNodeContainer() * @generated * @ordered */ protected ConnectivityNodeContainer connectivityNodeContainer; /** * The cached value of the '{@link #getSvInjection() <em>Sv Injection</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSvInjection() * @generated * @ordered */ protected SvInjection svInjection; /** * The cached value of the '{@link #getConnectivityNodes() <em>Connectivity Nodes</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConnectivityNodes() * @generated * @ordered */ protected EList<ConnectivityNode> connectivityNodes; /** * The cached value of the '{@link #getSvVoltage() <em>Sv Voltage</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSvVoltage() * @generated * @ordered */ protected SvVoltage svVoltage; /** * The cached value of the '{@link #getBaseVoltage() <em>Base Voltage</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBaseVoltage() * @generated * @ordered */ protected BaseVoltage baseVoltage; /** * The cached value of the '{@link #getTopologicalIsland() <em>Topological Island</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTopologicalIsland() * @generated * @ordered */ protected TopologicalIsland topologicalIsland; /** * The cached value of the '{@link #getReportingGroup() <em>Reporting Group</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReportingGroup() * @generated * @ordered */ protected ReportingGroup reportingGroup; /** * The cached value of the '{@link #getTerminal() <em>Terminal</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTerminal() * @generated * @ordered */ protected EList<Terminal> terminal; /** * The cached value of the '{@link #getAngleRef_TopologicalIsland() <em>Angle Ref Topological Island</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAngleRef_TopologicalIsland() * @generated * @ordered */ protected TopologicalIsland angleRef_TopologicalIsland; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TopologicalNode() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TopologyPackage.Literals.TOPOLOGICAL_NODE; } /** * Returns the value of the '<em><b>Sv Short Circuit</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.StateVariables.SvShortCircuit#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sv Short Circuit</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sv Short Circuit</em>' reference. * @see #setSvShortCircuit(SvShortCircuit) * @see CIM15.IEC61970.StateVariables.SvShortCircuit#getTopologicalNode * @generated */ public SvShortCircuit getSvShortCircuit() { if (svShortCircuit != null && svShortCircuit.eIsProxy()) { InternalEObject oldSvShortCircuit = (InternalEObject)svShortCircuit; svShortCircuit = (SvShortCircuit)eResolveProxy(oldSvShortCircuit); if (svShortCircuit != oldSvShortCircuit) { } } return svShortCircuit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SvShortCircuit basicGetSvShortCircuit() { return svShortCircuit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSvShortCircuit(SvShortCircuit newSvShortCircuit, NotificationChain msgs) { SvShortCircuit oldSvShortCircuit = svShortCircuit; svShortCircuit = newSvShortCircuit; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getSvShortCircuit <em>Sv Short Circuit</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sv Short Circuit</em>' reference. * @see #getSvShortCircuit() * @generated */ public void setSvShortCircuit(SvShortCircuit newSvShortCircuit) { if (newSvShortCircuit != svShortCircuit) { NotificationChain msgs = null; if (svShortCircuit != null) msgs = ((InternalEObject)svShortCircuit).eInverseRemove(this, StateVariablesPackage.SV_SHORT_CIRCUIT__TOPOLOGICAL_NODE, SvShortCircuit.class, msgs); if (newSvShortCircuit != null) msgs = ((InternalEObject)newSvShortCircuit).eInverseAdd(this, StateVariablesPackage.SV_SHORT_CIRCUIT__TOPOLOGICAL_NODE, SvShortCircuit.class, msgs); msgs = basicSetSvShortCircuit(newSvShortCircuit, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Connectivity Node Container</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Core.ConnectivityNodeContainer#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Connectivity Node Container</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Connectivity Node Container</em>' reference. * @see #setConnectivityNodeContainer(ConnectivityNodeContainer) * @see CIM15.IEC61970.Core.ConnectivityNodeContainer#getTopologicalNode * @generated */ public ConnectivityNodeContainer getConnectivityNodeContainer() { if (connectivityNodeContainer != null && connectivityNodeContainer.eIsProxy()) { InternalEObject oldConnectivityNodeContainer = (InternalEObject)connectivityNodeContainer; connectivityNodeContainer = (ConnectivityNodeContainer)eResolveProxy(oldConnectivityNodeContainer); if (connectivityNodeContainer != oldConnectivityNodeContainer) { } } return connectivityNodeContainer; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ConnectivityNodeContainer basicGetConnectivityNodeContainer() { return connectivityNodeContainer; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetConnectivityNodeContainer(ConnectivityNodeContainer newConnectivityNodeContainer, NotificationChain msgs) { ConnectivityNodeContainer oldConnectivityNodeContainer = connectivityNodeContainer; connectivityNodeContainer = newConnectivityNodeContainer; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getConnectivityNodeContainer <em>Connectivity Node Container</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Connectivity Node Container</em>' reference. * @see #getConnectivityNodeContainer() * @generated */ public void setConnectivityNodeContainer(ConnectivityNodeContainer newConnectivityNodeContainer) { if (newConnectivityNodeContainer != connectivityNodeContainer) { NotificationChain msgs = null; if (connectivityNodeContainer != null) msgs = ((InternalEObject)connectivityNodeContainer).eInverseRemove(this, CorePackage.CONNECTIVITY_NODE_CONTAINER__TOPOLOGICAL_NODE, ConnectivityNodeContainer.class, msgs); if (newConnectivityNodeContainer != null) msgs = ((InternalEObject)newConnectivityNodeContainer).eInverseAdd(this, CorePackage.CONNECTIVITY_NODE_CONTAINER__TOPOLOGICAL_NODE, ConnectivityNodeContainer.class, msgs); msgs = basicSetConnectivityNodeContainer(newConnectivityNodeContainer, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Sv Injection</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.StateVariables.SvInjection#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sv Injection</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sv Injection</em>' reference. * @see #setSvInjection(SvInjection) * @see CIM15.IEC61970.StateVariables.SvInjection#getTopologicalNode * @generated */ public SvInjection getSvInjection() { if (svInjection != null && svInjection.eIsProxy()) { InternalEObject oldSvInjection = (InternalEObject)svInjection; svInjection = (SvInjection)eResolveProxy(oldSvInjection); if (svInjection != oldSvInjection) { } } return svInjection; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SvInjection basicGetSvInjection() { return svInjection; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSvInjection(SvInjection newSvInjection, NotificationChain msgs) { SvInjection oldSvInjection = svInjection; svInjection = newSvInjection; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getSvInjection <em>Sv Injection</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sv Injection</em>' reference. * @see #getSvInjection() * @generated */ public void setSvInjection(SvInjection newSvInjection) { if (newSvInjection != svInjection) { NotificationChain msgs = null; if (svInjection != null) msgs = ((InternalEObject)svInjection).eInverseRemove(this, StateVariablesPackage.SV_INJECTION__TOPOLOGICAL_NODE, SvInjection.class, msgs); if (newSvInjection != null) msgs = ((InternalEObject)newSvInjection).eInverseAdd(this, StateVariablesPackage.SV_INJECTION__TOPOLOGICAL_NODE, SvInjection.class, msgs); msgs = basicSetSvInjection(newSvInjection, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Connectivity Nodes</b></em>' reference list. * The list contents are of type {@link CIM15.IEC61970.Core.ConnectivityNode}. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Core.ConnectivityNode#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Connectivity Nodes</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Connectivity Nodes</em>' reference list. * @see CIM15.IEC61970.Core.ConnectivityNode#getTopologicalNode * @generated */ public EList<ConnectivityNode> getConnectivityNodes() { if (connectivityNodes == null) { connectivityNodes = new BasicInternalEList<ConnectivityNode>(ConnectivityNode.class); } return connectivityNodes; } /** * Returns the value of the '<em><b>Sv Voltage</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.StateVariables.SvVoltage#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sv Voltage</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sv Voltage</em>' reference. * @see #setSvVoltage(SvVoltage) * @see CIM15.IEC61970.StateVariables.SvVoltage#getTopologicalNode * @generated */ public SvVoltage getSvVoltage() { if (svVoltage != null && svVoltage.eIsProxy()) { InternalEObject oldSvVoltage = (InternalEObject)svVoltage; svVoltage = (SvVoltage)eResolveProxy(oldSvVoltage); if (svVoltage != oldSvVoltage) { } } return svVoltage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SvVoltage basicGetSvVoltage() { return svVoltage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSvVoltage(SvVoltage newSvVoltage, NotificationChain msgs) { SvVoltage oldSvVoltage = svVoltage; svVoltage = newSvVoltage; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getSvVoltage <em>Sv Voltage</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sv Voltage</em>' reference. * @see #getSvVoltage() * @generated */ public void setSvVoltage(SvVoltage newSvVoltage) { if (newSvVoltage != svVoltage) { NotificationChain msgs = null; if (svVoltage != null) msgs = ((InternalEObject)svVoltage).eInverseRemove(this, StateVariablesPackage.SV_VOLTAGE__TOPOLOGICAL_NODE, SvVoltage.class, msgs); if (newSvVoltage != null) msgs = ((InternalEObject)newSvVoltage).eInverseAdd(this, StateVariablesPackage.SV_VOLTAGE__TOPOLOGICAL_NODE, SvVoltage.class, msgs); msgs = basicSetSvVoltage(newSvVoltage, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Base Voltage</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Core.BaseVoltage#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Base Voltage</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Base Voltage</em>' reference. * @see #setBaseVoltage(BaseVoltage) * @see CIM15.IEC61970.Core.BaseVoltage#getTopologicalNode * @generated */ public BaseVoltage getBaseVoltage() { if (baseVoltage != null && baseVoltage.eIsProxy()) { InternalEObject oldBaseVoltage = (InternalEObject)baseVoltage; baseVoltage = (BaseVoltage)eResolveProxy(oldBaseVoltage); if (baseVoltage != oldBaseVoltage) { } } return baseVoltage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BaseVoltage basicGetBaseVoltage() { return baseVoltage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetBaseVoltage(BaseVoltage newBaseVoltage, NotificationChain msgs) { BaseVoltage oldBaseVoltage = baseVoltage; baseVoltage = newBaseVoltage; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getBaseVoltage <em>Base Voltage</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Base Voltage</em>' reference. * @see #getBaseVoltage() * @generated */ public void setBaseVoltage(BaseVoltage newBaseVoltage) { if (newBaseVoltage != baseVoltage) { NotificationChain msgs = null; if (baseVoltage != null) msgs = ((InternalEObject)baseVoltage).eInverseRemove(this, CorePackage.BASE_VOLTAGE__TOPOLOGICAL_NODE, BaseVoltage.class, msgs); if (newBaseVoltage != null) msgs = ((InternalEObject)newBaseVoltage).eInverseAdd(this, CorePackage.BASE_VOLTAGE__TOPOLOGICAL_NODE, BaseVoltage.class, msgs); msgs = basicSetBaseVoltage(newBaseVoltage, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Topological Island</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.StateVariables.TopologicalIsland#getTopologicalNodes <em>Topological Nodes</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Topological Island</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Topological Island</em>' reference. * @see #setTopologicalIsland(TopologicalIsland) * @see CIM15.IEC61970.StateVariables.TopologicalIsland#getTopologicalNodes * @generated */ public TopologicalIsland getTopologicalIsland() { if (topologicalIsland != null && topologicalIsland.eIsProxy()) { InternalEObject oldTopologicalIsland = (InternalEObject)topologicalIsland; topologicalIsland = (TopologicalIsland)eResolveProxy(oldTopologicalIsland); if (topologicalIsland != oldTopologicalIsland) { } } return topologicalIsland; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TopologicalIsland basicGetTopologicalIsland() { return topologicalIsland; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTopologicalIsland(TopologicalIsland newTopologicalIsland, NotificationChain msgs) { TopologicalIsland oldTopologicalIsland = topologicalIsland; topologicalIsland = newTopologicalIsland; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getTopologicalIsland <em>Topological Island</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Topological Island</em>' reference. * @see #getTopologicalIsland() * @generated */ public void setTopologicalIsland(TopologicalIsland newTopologicalIsland) { if (newTopologicalIsland != topologicalIsland) { NotificationChain msgs = null; if (topologicalIsland != null) msgs = ((InternalEObject)topologicalIsland).eInverseRemove(this, StateVariablesPackage.TOPOLOGICAL_ISLAND__TOPOLOGICAL_NODES, TopologicalIsland.class, msgs); if (newTopologicalIsland != null) msgs = ((InternalEObject)newTopologicalIsland).eInverseAdd(this, StateVariablesPackage.TOPOLOGICAL_ISLAND__TOPOLOGICAL_NODES, TopologicalIsland.class, msgs); msgs = basicSetTopologicalIsland(newTopologicalIsland, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Reporting Group</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Core.ReportingGroup#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Reporting Group</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Reporting Group</em>' reference. * @see #setReportingGroup(ReportingGroup) * @see CIM15.IEC61970.Core.ReportingGroup#getTopologicalNode * @generated */ public ReportingGroup getReportingGroup() { if (reportingGroup != null && reportingGroup.eIsProxy()) { InternalEObject oldReportingGroup = (InternalEObject)reportingGroup; reportingGroup = (ReportingGroup)eResolveProxy(oldReportingGroup); if (reportingGroup != oldReportingGroup) { } } return reportingGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReportingGroup basicGetReportingGroup() { return reportingGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetReportingGroup(ReportingGroup newReportingGroup, NotificationChain msgs) { ReportingGroup oldReportingGroup = reportingGroup; reportingGroup = newReportingGroup; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getReportingGroup <em>Reporting Group</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Reporting Group</em>' reference. * @see #getReportingGroup() * @generated */ public void setReportingGroup(ReportingGroup newReportingGroup) { if (newReportingGroup != reportingGroup) { NotificationChain msgs = null; if (reportingGroup != null) msgs = ((InternalEObject)reportingGroup).eInverseRemove(this, CorePackage.REPORTING_GROUP__TOPOLOGICAL_NODE, ReportingGroup.class, msgs); if (newReportingGroup != null) msgs = ((InternalEObject)newReportingGroup).eInverseAdd(this, CorePackage.REPORTING_GROUP__TOPOLOGICAL_NODE, ReportingGroup.class, msgs); msgs = basicSetReportingGroup(newReportingGroup, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Terminal</b></em>' reference list. * The list contents are of type {@link CIM15.IEC61970.Core.Terminal}. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Core.Terminal#getTopologicalNode <em>Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Terminal</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Terminal</em>' reference list. * @see CIM15.IEC61970.Core.Terminal#getTopologicalNode * @generated */ public EList<Terminal> getTerminal() { if (terminal == null) { terminal = new BasicInternalEList<Terminal>(Terminal.class); } return terminal; } /** * Returns the value of the '<em><b>Angle Ref Topological Island</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.StateVariables.TopologicalIsland#getAngleRef_TopologicalNode <em>Angle Ref Topological Node</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Angle Ref Topological Island</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Angle Ref Topological Island</em>' reference. * @see #setAngleRef_TopologicalIsland(TopologicalIsland) * @see CIM15.IEC61970.StateVariables.TopologicalIsland#getAngleRef_TopologicalNode * @generated */ public TopologicalIsland getAngleRef_TopologicalIsland() { if (angleRef_TopologicalIsland != null && angleRef_TopologicalIsland.eIsProxy()) { InternalEObject oldAngleRef_TopologicalIsland = (InternalEObject)angleRef_TopologicalIsland; angleRef_TopologicalIsland = (TopologicalIsland)eResolveProxy(oldAngleRef_TopologicalIsland); if (angleRef_TopologicalIsland != oldAngleRef_TopologicalIsland) { } } return angleRef_TopologicalIsland; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TopologicalIsland basicGetAngleRef_TopologicalIsland() { return angleRef_TopologicalIsland; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetAngleRef_TopologicalIsland(TopologicalIsland newAngleRef_TopologicalIsland, NotificationChain msgs) { TopologicalIsland oldAngleRef_TopologicalIsland = angleRef_TopologicalIsland; angleRef_TopologicalIsland = newAngleRef_TopologicalIsland; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61970.Topology.TopologicalNode#getAngleRef_TopologicalIsland <em>Angle Ref Topological Island</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Angle Ref Topological Island</em>' reference. * @see #getAngleRef_TopologicalIsland() * @generated */ public void setAngleRef_TopologicalIsland(TopologicalIsland newAngleRef_TopologicalIsland) { if (newAngleRef_TopologicalIsland != angleRef_TopologicalIsland) { NotificationChain msgs = null; if (angleRef_TopologicalIsland != null) msgs = ((InternalEObject)angleRef_TopologicalIsland).eInverseRemove(this, StateVariablesPackage.TOPOLOGICAL_ISLAND__ANGLE_REF_TOPOLOGICAL_NODE, TopologicalIsland.class, msgs); if (newAngleRef_TopologicalIsland != null) msgs = ((InternalEObject)newAngleRef_TopologicalIsland).eInverseAdd(this, StateVariablesPackage.TOPOLOGICAL_ISLAND__ANGLE_REF_TOPOLOGICAL_NODE, TopologicalIsland.class, msgs); msgs = basicSetAngleRef_TopologicalIsland(newAngleRef_TopologicalIsland, msgs); if (msgs != null) msgs.dispatch(); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case TopologyPackage.TOPOLOGICAL_NODE__SV_SHORT_CIRCUIT: if (svShortCircuit != null) msgs = ((InternalEObject)svShortCircuit).eInverseRemove(this, StateVariablesPackage.SV_SHORT_CIRCUIT__TOPOLOGICAL_NODE, SvShortCircuit.class, msgs); return basicSetSvShortCircuit((SvShortCircuit)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODE_CONTAINER: if (connectivityNodeContainer != null) msgs = ((InternalEObject)connectivityNodeContainer).eInverseRemove(this, CorePackage.CONNECTIVITY_NODE_CONTAINER__TOPOLOGICAL_NODE, ConnectivityNodeContainer.class, msgs); return basicSetConnectivityNodeContainer((ConnectivityNodeContainer)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__SV_INJECTION: if (svInjection != null) msgs = ((InternalEObject)svInjection).eInverseRemove(this, StateVariablesPackage.SV_INJECTION__TOPOLOGICAL_NODE, SvInjection.class, msgs); return basicSetSvInjection((SvInjection)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODES: return ((InternalEList<InternalEObject>)(InternalEList<?>)getConnectivityNodes()).basicAdd(otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__SV_VOLTAGE: if (svVoltage != null) msgs = ((InternalEObject)svVoltage).eInverseRemove(this, StateVariablesPackage.SV_VOLTAGE__TOPOLOGICAL_NODE, SvVoltage.class, msgs); return basicSetSvVoltage((SvVoltage)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__BASE_VOLTAGE: if (baseVoltage != null) msgs = ((InternalEObject)baseVoltage).eInverseRemove(this, CorePackage.BASE_VOLTAGE__TOPOLOGICAL_NODE, BaseVoltage.class, msgs); return basicSetBaseVoltage((BaseVoltage)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__TOPOLOGICAL_ISLAND: if (topologicalIsland != null) msgs = ((InternalEObject)topologicalIsland).eInverseRemove(this, StateVariablesPackage.TOPOLOGICAL_ISLAND__TOPOLOGICAL_NODES, TopologicalIsland.class, msgs); return basicSetTopologicalIsland((TopologicalIsland)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__REPORTING_GROUP: if (reportingGroup != null) msgs = ((InternalEObject)reportingGroup).eInverseRemove(this, CorePackage.REPORTING_GROUP__TOPOLOGICAL_NODE, ReportingGroup.class, msgs); return basicSetReportingGroup((ReportingGroup)otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__TERMINAL: return ((InternalEList<InternalEObject>)(InternalEList<?>)getTerminal()).basicAdd(otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__ANGLE_REF_TOPOLOGICAL_ISLAND: if (angleRef_TopologicalIsland != null) msgs = ((InternalEObject)angleRef_TopologicalIsland).eInverseRemove(this, StateVariablesPackage.TOPOLOGICAL_ISLAND__ANGLE_REF_TOPOLOGICAL_NODE, TopologicalIsland.class, msgs); return basicSetAngleRef_TopologicalIsland((TopologicalIsland)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case TopologyPackage.TOPOLOGICAL_NODE__SV_SHORT_CIRCUIT: return basicSetSvShortCircuit(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODE_CONTAINER: return basicSetConnectivityNodeContainer(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__SV_INJECTION: return basicSetSvInjection(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODES: return ((InternalEList<?>)getConnectivityNodes()).basicRemove(otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__SV_VOLTAGE: return basicSetSvVoltage(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__BASE_VOLTAGE: return basicSetBaseVoltage(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__TOPOLOGICAL_ISLAND: return basicSetTopologicalIsland(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__REPORTING_GROUP: return basicSetReportingGroup(null, msgs); case TopologyPackage.TOPOLOGICAL_NODE__TERMINAL: return ((InternalEList<?>)getTerminal()).basicRemove(otherEnd, msgs); case TopologyPackage.TOPOLOGICAL_NODE__ANGLE_REF_TOPOLOGICAL_ISLAND: return basicSetAngleRef_TopologicalIsland(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TopologyPackage.TOPOLOGICAL_NODE__SV_SHORT_CIRCUIT: if (resolve) return getSvShortCircuit(); return basicGetSvShortCircuit(); case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODE_CONTAINER: if (resolve) return getConnectivityNodeContainer(); return basicGetConnectivityNodeContainer(); case TopologyPackage.TOPOLOGICAL_NODE__SV_INJECTION: if (resolve) return getSvInjection(); return basicGetSvInjection(); case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODES: return getConnectivityNodes(); case TopologyPackage.TOPOLOGICAL_NODE__SV_VOLTAGE: if (resolve) return getSvVoltage(); return basicGetSvVoltage(); case TopologyPackage.TOPOLOGICAL_NODE__BASE_VOLTAGE: if (resolve) return getBaseVoltage(); return basicGetBaseVoltage(); case TopologyPackage.TOPOLOGICAL_NODE__TOPOLOGICAL_ISLAND: if (resolve) return getTopologicalIsland(); return basicGetTopologicalIsland(); case TopologyPackage.TOPOLOGICAL_NODE__REPORTING_GROUP: if (resolve) return getReportingGroup(); return basicGetReportingGroup(); case TopologyPackage.TOPOLOGICAL_NODE__TERMINAL: return getTerminal(); case TopologyPackage.TOPOLOGICAL_NODE__ANGLE_REF_TOPOLOGICAL_ISLAND: if (resolve) return getAngleRef_TopologicalIsland(); return basicGetAngleRef_TopologicalIsland(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TopologyPackage.TOPOLOGICAL_NODE__SV_SHORT_CIRCUIT: setSvShortCircuit((SvShortCircuit)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODE_CONTAINER: setConnectivityNodeContainer((ConnectivityNodeContainer)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__SV_INJECTION: setSvInjection((SvInjection)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODES: getConnectivityNodes().clear(); getConnectivityNodes().addAll((Collection<? extends ConnectivityNode>)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__SV_VOLTAGE: setSvVoltage((SvVoltage)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__BASE_VOLTAGE: setBaseVoltage((BaseVoltage)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__TOPOLOGICAL_ISLAND: setTopologicalIsland((TopologicalIsland)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__REPORTING_GROUP: setReportingGroup((ReportingGroup)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__TERMINAL: getTerminal().clear(); getTerminal().addAll((Collection<? extends Terminal>)newValue); return; case TopologyPackage.TOPOLOGICAL_NODE__ANGLE_REF_TOPOLOGICAL_ISLAND: setAngleRef_TopologicalIsland((TopologicalIsland)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TopologyPackage.TOPOLOGICAL_NODE__SV_SHORT_CIRCUIT: setSvShortCircuit((SvShortCircuit)null); return; case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODE_CONTAINER: setConnectivityNodeContainer((ConnectivityNodeContainer)null); return; case TopologyPackage.TOPOLOGICAL_NODE__SV_INJECTION: setSvInjection((SvInjection)null); return; case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODES: getConnectivityNodes().clear(); return; case TopologyPackage.TOPOLOGICAL_NODE__SV_VOLTAGE: setSvVoltage((SvVoltage)null); return; case TopologyPackage.TOPOLOGICAL_NODE__BASE_VOLTAGE: setBaseVoltage((BaseVoltage)null); return; case TopologyPackage.TOPOLOGICAL_NODE__TOPOLOGICAL_ISLAND: setTopologicalIsland((TopologicalIsland)null); return; case TopologyPackage.TOPOLOGICAL_NODE__REPORTING_GROUP: setReportingGroup((ReportingGroup)null); return; case TopologyPackage.TOPOLOGICAL_NODE__TERMINAL: getTerminal().clear(); return; case TopologyPackage.TOPOLOGICAL_NODE__ANGLE_REF_TOPOLOGICAL_ISLAND: setAngleRef_TopologicalIsland((TopologicalIsland)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TopologyPackage.TOPOLOGICAL_NODE__SV_SHORT_CIRCUIT: return svShortCircuit != null; case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODE_CONTAINER: return connectivityNodeContainer != null; case TopologyPackage.TOPOLOGICAL_NODE__SV_INJECTION: return svInjection != null; case TopologyPackage.TOPOLOGICAL_NODE__CONNECTIVITY_NODES: return connectivityNodes != null && !connectivityNodes.isEmpty(); case TopologyPackage.TOPOLOGICAL_NODE__SV_VOLTAGE: return svVoltage != null; case TopologyPackage.TOPOLOGICAL_NODE__BASE_VOLTAGE: return baseVoltage != null; case TopologyPackage.TOPOLOGICAL_NODE__TOPOLOGICAL_ISLAND: return topologicalIsland != null; case TopologyPackage.TOPOLOGICAL_NODE__REPORTING_GROUP: return reportingGroup != null; case TopologyPackage.TOPOLOGICAL_NODE__TERMINAL: return terminal != null && !terminal.isEmpty(); case TopologyPackage.TOPOLOGICAL_NODE__ANGLE_REF_TOPOLOGICAL_ISLAND: return angleRef_TopologicalIsland != null; } return super.eIsSet(featureID); } } // TopologicalNode
/******************************************************************************* * Copyright 2017 Cognizant Technology Solutions * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.cognizant.devops.platformregressiontest.test.ui.configurationfilemanagement; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.SkipException; import com.cognizant.devops.platformregressiontest.test.common.ConfigOptionsTest; import com.cognizant.devops.platformregressiontest.test.common.LoginAndSelectModule; import com.cognizant.devops.platformregressiontest.test.ui.testdata.WebhookDataProvider; import com.cognizant.devops.platformregressiontest.test.ui.testdatamodel.ConfigurationFileManagementDataModel; /** * @author NivethethaS * * Class contains the business logic for Configuration File Management * module test cases * */ public class ConfigurationFileManagementConfiguration extends ConfigurationFileManagementObjectRepository { WebDriverWait wait = new WebDriverWait(driver, 20); private static final Logger log = LogManager.getLogger(ConfigurationFileManagementConfiguration.class); public static final String CONFIG_FILES_PATH = System.getenv().get(ConfigOptionsTest.INSIGHTS_HOME) + File.separator + ConfigOptionsTest.AUTO_DIR + File.separator + ConfigOptionsTest.CONFIGURATION_FILE_DIR + File.separator; WebhookDataProvider actionButton = new WebhookDataProvider(); public ConfigurationFileManagementConfiguration() { PageFactory.initElements(driver, this); } /** * checks whether landing page is displayed or not * * @return true if landing page is displayed o/w false * @throws InterruptedException */ public boolean navigateToConfigurationLandingPage() { log.info("Configuration Landing page displayed"); return configurationLandingPage.isDisplayed(); } /** * Creates new Configuration for a particular module and adds it to the database * * @return true if new configuration is created o/w false * @throws InterruptedException */ public boolean addNewConfiguration(ConfigurationFileManagementDataModel data) throws InterruptedException { if (checkIfModuleConfigurationPresent(data.getModule())) { log.debug("module name already exists"); throw new SkipException("Skipping test case as module configuration already exists"); } else { addButton.click(); fileName.sendKeys(data.getFilename()); fileType.click(); selectFileType(data.getFiletype()); wait.until(ExpectedConditions.visibilityOf(fileModule)).click(); selectModuleName(data.getModule()); uploadFile.sendKeys(CONFIG_FILES_PATH + data.getFilepath()); saveButton.click(); wait.until(ExpectedConditions.elementToBeClickable(yesButton)); yesButton.click(); wait.until(ExpectedConditions.elementToBeClickable(okButton)); try { if (successMessage.isDisplayed()) { wait.until(ExpectedConditions.elementToBeClickable(okButton)); okButton.click(); log.info("successfully added module configuration"); return true; } } catch (Exception e) { log.info("error while creating module configuration"); redirectButton.click(); return false; } log.info("unexpected error while adding new configuration"); return false; } } /** * Checks if Configuration for the module is already present in the UI * * @param module * @return true if Configuration for the module is not present o/w false */ private boolean checkIfModuleConfigurationPresent(String module) { driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); List<WebElement> rws = configurationDetailsTable.findElements(By.tagName("tr")); for (int i = 0; i < rws.size(); i++) { List<WebElement> cols = (rws.get(i)).findElements(By.tagName("td")); if ((cols.get(3).getText()).equals(module)) { List<WebElement> radioButtons = rws.get(i) .findElements(By.xpath(".//preceding::span[contains(@class, 'mat-radio-container')]")); driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS); radioButtons.get(i).click(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); log.info("{} module name is present.", module); return true; } } driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); log.info("{} module name is not present.", module); return false; } /** * selects module name from the list of module names available * * @param type * @throws InterruptedException */ private void selectModuleName(String type) throws InterruptedException { driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); Thread.sleep(1000); for (WebElement toolValue : fileTypeList) { if ((toolValue.getText()).equals(type)) { wait.until(ExpectedConditions.visibilityOf(toolValue)); toolValue.click(); break; } } } /** * selects file type from the list of file types available * * @param moduleName * @throws InterruptedException */ private void selectFileType(String moduleName) throws InterruptedException { Thread.sleep(1000); for (WebElement moduleValue : fileModuleList) { if ((moduleValue.getText()).equals(moduleName)) { wait.until(ExpectedConditions.elementToBeClickable(moduleValue)); moduleValue.click(); break; } } } /** * Checks whether error message is popped out if we add existing configuration * * @return true if error message is popped up o/w false * @throws InterruptedException */ public boolean addSameConfiguration() throws InterruptedException { if (!checkIfModuleConfigurationPresent(LoginAndSelectModule.testData.get("module"))) { log.debug("module name already exists"); throw new SkipException("Skipping test case as module configuration already exists"); } else { addButton.click(); fileName.sendKeys(LoginAndSelectModule.testData.get("filename")); fileType.click(); selectFileType(LoginAndSelectModule.testData.get("filetype")); fileModule.click(); selectModuleName(LoginAndSelectModule.testData.get("module")); uploadFile.sendKeys(CONFIG_FILES_PATH + LoginAndSelectModule.testData.get("filepath")); saveButton.click(); wait.until(ExpectedConditions.elementToBeClickable(yesButton)); yesButton.click(); wait.until(ExpectedConditions.elementToBeClickable(okButton)); try { if (errorMessage.isDisplayed()) { wait.until(ExpectedConditions.elementToBeClickable(okButton)); okButton.click(); log.info("error message is displayed when we try to add same module configuration"); redirectButton.click(); return true; } } catch (Exception e) { log.info("error while creating same module configuration"); redirectButton.click(); return false; } log.info("unexpected error while creating same module configuration"); return false; } } /** * Edits the configuration with updated configuration file * * @return true if editing is successful o/w false */ public boolean editConfiguration() { if (!checkIfModuleConfigurationPresent(LoginAndSelectModule.testData.get("module"))) { log.debug("module cofiguration is not present"); throw new SkipException("Skipping test case as module configuration is not available to edit"); } else { wait.until(ExpectedConditions.elementToBeClickable(deleteButton)); editButton.click(); uploadFile.sendKeys(CONFIG_FILES_PATH + LoginAndSelectModule.testData.get("updatedfilepath")); saveButton.click(); wait.until(ExpectedConditions.elementToBeClickable(yesButton)); yesButton.click(); wait.until(ExpectedConditions.elementToBeClickable(okButton)); try { if (successMessage.isDisplayed()) { wait.until(ExpectedConditions.elementToBeClickable(okButton)); okButton.click(); log.info("Module configuration is editted successfully"); return true; } } catch (Exception e) { log.info("error while editting module configuration"); redirectButton.click(); return false; } log.info("something went wrong"); return false; } } /** * checks if refresh, reset and redirect to landing page functionalities are * successful * * @return true if all the functionalities are successful o/w false * @throws InterruptedException */ public boolean refreshAndResetFunctionality() throws InterruptedException { if (resetFunctionalityCheck()) { log.info("refresh & reset functionality successful"); redirectButton.click(); wait.until(ExpectedConditions.elementToBeClickable(landingPage)); try { if (landingPage.isDisplayed()) { log.info("navigate to landing page successful"); return true; } } catch (Exception e) { log.info("navigate to landing page unsuccessful"); return false; } return true; } log.info("refresh & reset functionality unsuccessful"); return false; } /** * checks if reset functionality is successful * * @return true if reset functionality is successful o/w false */ private boolean resetFunctionalityCheck() { addButton.click(); fileName.sendKeys(LoginAndSelectModule.testData.get("filename")); resetButton.click(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); if (fileName.getText().length() == 0) { log.info("reset functionality successful"); return true; } log.info("reset functionality unsuccessful"); return false; } /** * Deletes the configuration created * * @return true if deletion is successful o/w false */ public boolean deleteConfiguration() { if (!checkIfModuleConfigurationPresent(LoginAndSelectModule.testData.get("module"))) { log.debug("module cofiguration is not present or already deleted"); throw new SkipException("Skipping test case as module configuration is already deleted"); } else { wait.until(ExpectedConditions.elementToBeClickable(deleteButton)); deleteButton.click(); wait.until(ExpectedConditions.elementToBeClickable(yesButton)); yesButton.click(); wait.until(ExpectedConditions.elementToBeClickable(okButton)); try { if (successMessage.isDisplayed()) { wait.until(ExpectedConditions.elementToBeClickable(okButton)); okButton.click(); log.info("successfully deleted module configuration"); return true; } } catch (Exception e) { log.info("error while deleting module configuration"); redirectButton.click(); return false; } log.info("something went wrong - unexpected error while deleting configuration"); return false; } } }
package com.hockeyhurd.hcorelib.api.math; /** * Helper sorting class used to sort things (hopefully) quickly. * * @author hockeyhurd * @version 1/27/16 */ public final class Sorts { /** * SortType enumeration. * * @author hockeyhurd * @version 1/27/16 */ public enum SortType { ASCENDING, DESCENDING } private Sorts() { } /** * Selection sorts int array. * * @param arr Int array. * @param sortType SortType to use. * @return Result; true for success, false for error. */ public static boolean selectionSorti(int[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; int value; for (int y = arr.length - 1; y > 0; y--) { insertIndex = 0; for (int x = 0; x <= y; x++) { if (sortType == SortType.ASCENDING && arr[x] > arr[insertIndex]) insertIndex = x; else if (sortType == SortType.DESCENDING && arr[x] < arr[insertIndex]) insertIndex = x; } value = arr[y]; arr[y] = arr[insertIndex]; arr[insertIndex] = value; } return true; } /** * Selection sorts long array. * * @param arr Long array. * @param sortType SortType to use. * @return Result; true for success, false for error. */ public static boolean selectionSortl(long[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; long value; for (int y = arr.length - 1; y > 0; y--) { insertIndex = 0; for (int x = 0; x <= y; x++) { if (sortType == SortType.ASCENDING && arr[x] > arr[insertIndex]) insertIndex = x; else if (sortType == SortType.DESCENDING && arr[x] < arr[insertIndex]) insertIndex = x; } value = arr[y]; arr[y] = arr[insertIndex]; arr[insertIndex] = value; } return true; } /** * Selection sorts float array. * * @param arr Float array. * @param sortType SortType to use. * @return Result; true for success, false for error. */ public static boolean selectionSortf(float[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; float value; for (int y = arr.length - 1; y > 0; y--) { insertIndex = 0; for (int x = 0; x <= y; x++) { if (sortType == SortType.ASCENDING && arr[x] > arr[insertIndex]) insertIndex = x; else if (sortType == SortType.DESCENDING && arr[x] < arr[insertIndex]) insertIndex = x; } value = arr[y]; arr[y] = arr[insertIndex]; arr[insertIndex] = value; } return true; } /** * Selection sorts double array. * * @param arr Double array. * @param sortType SortType to use. * @return Result; true for success, false for error. */ public static boolean selectionSortd(double[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; double value; for (int y = arr.length - 1; y > 0; y--) { insertIndex = 0; for (int x = 0; x <= y; x++) { if (sortType == SortType.ASCENDING && arr[x] > arr[insertIndex]) insertIndex = x; else if (sortType == SortType.DESCENDING && arr[x] < arr[insertIndex]) insertIndex = x; } value = arr[y]; arr[y] = arr[insertIndex]; arr[insertIndex] = value; } return true; } /** * Selection sorts a comparable object array. * * @param comparables A comparable array. * @param sortType SortType to use. * @return Result; true for success, false for error. */ @SuppressWarnings("unchecked") public static boolean selectionSort(Comparable[] comparables, SortType sortType) { if (comparables == null || comparables.length == 0) return false; else if (comparables.length == 1) return true; int insertIndex; Comparable value; for (int y = comparables.length - 1; y > 0; y--) { insertIndex = 0; for (int x = 0; x <= y; x++) { if (sortType == SortType.ASCENDING && comparables[x].compareTo(comparables[insertIndex]) == 1) insertIndex = x; else if (sortType == SortType.DESCENDING && comparables[x].compareTo(comparables[insertIndex]) == -1) insertIndex = x; } value = comparables[y]; comparables[y] = comparables[insertIndex]; comparables[insertIndex] = value; } return true; } /** * Quick sorts an int array. * @param arr Int array. * @param lower Lower index bound. * @param higher Upper index bound. * @param sortType SortType to use. * @return Result; true if success, false if failure. */ public static boolean quickSorti(int[] arr, final int lower, final int higher, SortType sortType) { if (arr == null || arr.length == 0 || lower > higher) return false; else if (arr.length == 1) return true; int i = lower; int j = higher; final int pivot = arr[lower + (higher - lower) / 2]; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { // Sawp values. final int value = arr[i]; arr[i] = arr[j]; arr[j] = value; i++; j--; } } // Call recursively. if (lower < j) quickSorti(arr, lower, j, sortType); if (i < higher) quickSorti(arr, i, higher, sortType); return true; } /** * Quick sorts an long array. * @param arr Long array. * @param lower Lower index bound. * @param higher Upper index bound. * @param sortType SortType to use. * @return Result; true if success, false if failure. */ public static boolean quickSortl(long[] arr, final int lower, final int higher, SortType sortType) { if (arr == null || arr.length == 0 || lower > higher) return false; else if (arr.length == 1) return true; int i = lower; int j = higher; final long pivot = arr[lower + (higher - lower) / 2]; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { // Sawp values. final long value = arr[i]; arr[i] = arr[j]; arr[j] = value; i++; j--; } } // Call recursively. if (lower < j) quickSortl(arr, lower, j, sortType); if (i < higher) quickSortl(arr, i, higher, sortType); return true; } /** * Quick sorts an float array. * @param arr Float array. * @param lower Lower index bound. * @param higher Upper index bound. * @param sortType SortType to use. * @return Result; true if success, false if failure. */ public static boolean quickSortf(float[] arr, final int lower, final int higher, SortType sortType) { if (arr == null || arr.length == 0 || lower > higher) return false; else if (arr.length == 1) return true; int i = lower; int j = higher; final float pivot = arr[lower + (higher - lower) / 2]; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { // Sawp values. final float value = arr[i]; arr[i] = arr[j]; arr[j] = value; i++; j--; } } // Call recursively. if (lower < j) quickSortf(arr, lower, j, sortType); if (i < higher) quickSortf(arr, i, higher, sortType); return true; } /** * Quick sorts an double array. * @param arr Double array. * @param lower Lower index bound. * @param higher Upper index bound. * @param sortType SortType to use. * @return Result; true if success, false if failure. */ public static boolean quickSortd(double[] arr, final int lower, final int higher, SortType sortType) { if (arr == null || arr.length == 0 || lower > higher) return false; else if (arr.length == 1) return true; int i = lower; int j = higher; final double pivot = arr[lower + (higher - lower) / 2]; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { // Sawp values. final double value = arr[i]; arr[i] = arr[j]; arr[j] = value; i++; j--; } } // Call recursively. if (lower < j) quickSortd(arr, lower, j, sortType); if (i < higher) quickSortd(arr, i, higher, sortType); return true; } /** * Quick sorts a comparable object array. * * @param comparables Comparable object array. * @param lower Lower index bound. * @param higher Upper index bound. * @param sortType SortType to use. * @return Result; true if success, false if failure. */ @SuppressWarnings("unchecked") public static boolean quickSort(Comparable[] comparables, final int lower, final int higher, SortType sortType) { if (comparables == null || comparables.length == 0 || lower > higher) return false; else if (comparables.length == 1) return true; int i = lower; int j = higher; final Comparable pivot = comparables[lower + (higher - lower) / 2]; while (i <= j) { while (comparables[i].compareTo(pivot) == -1) i++; while (comparables[j].compareTo(pivot) == 1) j--; if (i <= j) { // Swap values. final Comparable value = comparables[i]; comparables[i] = comparables[j]; comparables[j] = value; i++; j--; } } // Call recursively. if (lower < j) quickSort(comparables, lower, j, sortType); if (i < higher) quickSort(comparables, i, higher, sortType); return true; } /** * Insertion sorts an int array. * * @param arr Int array to sort. * @param sortType SortType to use. * @return Result; true if successful, else false. */ public static boolean insertionSorti(int[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; int k; int next; for (int i = 0; i < arr.length; i++) { next = arr[i]; insertIndex = 0; k = i; while (k > 0 && insertIndex == 0) { if (sortType == SortType.ASCENDING && next > arr[k - 1]) insertIndex = k; else if (sortType == SortType.DESCENDING && next < arr[k - 1]) insertIndex = k; else arr[k] = arr[k - 1]; k--; } arr[insertIndex] = next; } return true; } /** * Insertion sorts an long array. * * @param arr Long array to sort. * @param sortType SortType to use. * @return Result; true if successful, else false. */ public static boolean insertionSortl(long[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; int k; long next; for (int i = 0; i < arr.length; i++) { next = arr[i]; insertIndex = 0; k = i; while (k > 0 && insertIndex == 0) { if (sortType == SortType.ASCENDING && next > arr[k - 1]) insertIndex = k; else if (sortType == SortType.DESCENDING && next < arr[k - 1]) insertIndex = k; else arr[k] = arr[k - 1]; k--; } arr[insertIndex] = next; } return true; } /** * Insertion sorts an float array. * * @param arr Float array to sort. * @param sortType SortType to use. * @return Result; true if successful, else false. */ public static boolean insertionSortf(float[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; int k; float next; for (int i = 0; i < arr.length; i++) { next = arr[i]; insertIndex = 0; k = i; while (k > 0 && insertIndex == 0) { if (sortType == SortType.ASCENDING && next > arr[k - 1]) insertIndex = k; else if (sortType == SortType.DESCENDING && next < arr[k - 1]) insertIndex = k; else arr[k] = arr[k - 1]; k--; } arr[insertIndex] = next; } return true; } /** * Insertion sorts an double array. * * @param arr Double array to sort. * @param sortType SortType to use. * @return Result; true if successful, else false. */ public static boolean insertionSortd(double[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int insertIndex; int k; double next; for (int i = 0; i < arr.length; i++) { next = arr[i]; insertIndex = 0; k = i; while (k > 0 && insertIndex == 0) { if (sortType == SortType.ASCENDING && next > arr[k - 1]) insertIndex = k; else if (sortType == SortType.DESCENDING && next < arr[k - 1]) insertIndex = k; else arr[k] = arr[k - 1]; k--; } arr[insertIndex] = next; } return true; } /** * Insertion sorts a comparable object array. * * @param comparables Comparable array to sort. * @param sortType SortType to use. * @return Result; true if successful, else false. */ @SuppressWarnings("unchecked") public static boolean insertionSort(Comparable[] comparables, SortType sortType) { if (comparables == null || comparables.length == 0) return false; else if (comparables.length == 1) return true; int insertIndex; int k; Comparable next; for (int i = 0; i < comparables.length; i++) { next = comparables[i]; insertIndex = 0; k = i; while (k > 0 && insertIndex == 0) { if (sortType == SortType.ASCENDING && next.compareTo(comparables[k - 1]) == 1) insertIndex = k; else if (sortType == SortType.DESCENDING && next.compareTo(comparables[k - 1]) == -1) insertIndex = k; else comparables[k] = comparables[k - 1]; k--; } comparables[insertIndex] = next; } return true; } /** * Radix sorts int array. * * @param arr int array to sort. * @param sortType SortType to use. * @return Sorted array if successful, else returns false. */ public static boolean radixSorti(int[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; int[] output = new int[arr.length]; for (int byteIndex = 0; byteIndex < 0x20; byteIndex += 0x8) { int[] sortOffsets = new int[0x100]; for (int i = 0; i < arr.length; i++) { int radixVal = intToU32(arr[i]); int radixPiece = (radixVal >> byteIndex) & 0xff; sortOffsets[radixPiece]++; } int total = 0; for (int i = 0; i < sortOffsets.length; i++) { int count = sortOffsets[i]; sortOffsets[i] = total; total += count; } for (int i = 0; i < arr.length; i++) { int radixVal = intToU32(arr[i]); int radixPiece = (radixVal >> byteIndex) & 0xff; if (sortOffsets[radixPiece] < output.length) output[sortOffsets[radixPiece]++] = arr[i]; } // arr = output; for (int i = 0; i < arr.length; i++) { arr[i] = output[i]; } } int i; for (i = 0; i < arr.length; i++) { if (arr[i] >= 0) break; } if (i > 0 && i < arr.length) { int posNumLen = arr.length - i; int negNumLen = i; int index; int[] posNums = new int[posNumLen]; int[] negNums = new int[negNumLen]; for (index = 0; index < posNumLen; index++) { posNums[index] = arr[index + i]; } for (index = 0; index < negNumLen; index++) { negNums[index] = arr[index]; } reverseArrayi(negNums); // Reassemble the array: i = 0; for (index = 0; index < negNumLen; index++) { arr[i++] = negNums[index]; } for (index = 0; index < posNumLen; index++) { arr[i++] = posNums[index]; } } if (sortType == SortType.DESCENDING) reverseArrayi(arr); return true; } /** * Radix sorts float array. * * @param arr float array to sort. * @param sortType SortType to use. * @return Sorted array if successful, else returns false. */ public static boolean radixSortf(float[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; float[] output = new float[arr.length]; for (int byteIndex = 0; byteIndex < 0x20; byteIndex += 0x8) { int[] sortOffsets = new int[0x100]; for (int i = 0; i < arr.length; i++) { int radixVal = floatToU32(arr[i]); int radixPiece = (radixVal >> byteIndex) & 0xff; sortOffsets[radixPiece]++; } int total = 0; for (int i = 0; i < sortOffsets.length; i++) { int count = sortOffsets[i]; sortOffsets[i] = total; total += count; } for (int i = 0; i < arr.length; i++) { int radixVal = floatToU32(arr[i]); int radixPiece = (radixVal >> byteIndex) & 0xff; if (sortOffsets[radixPiece] < output.length) output[sortOffsets[radixPiece]++] = arr[i]; } for (int i = 0; i < arr.length; i++) { arr[i] = output[i]; } } int i; for (i = 0; i < arr.length; i++) { if (arr[i] >= 0) break; } if (i > 0 && i < arr.length) { int posNumLen = arr.length - i; int negNumLen = i; int index; float[] posNums = new float[posNumLen]; float[] negNums = new float[negNumLen]; for (index = 0; index < posNumLen; index++) { posNums[index] = arr[index + i]; } for (index = 0; index < negNumLen; index++) { negNums[index] = arr[index]; } reverseArrayf(negNums); // Reassemble the array: i = 0; for (index = 0; index < negNumLen; index++) { arr[i++] = negNums[index]; } for (index = 0; index < posNumLen; index++) { arr[i++] = posNums[index]; } } if (sortType == SortType.DESCENDING) reverseArrayf(arr); return true; } /** * Radix sorts double array. * * @param arr double array to sort. * @param sortType SortType to use. * @return Sorted array if successful, else returns false. */ public static boolean radixSortd(double[] arr, SortType sortType) { if (arr == null || arr.length == 0) return false; else if (arr.length == 1) return true; double[] output = new double[arr.length]; for (int byteIndex = 0; byteIndex < 0x20; byteIndex += 0x8) { int[] sortOffsets = new int[0x100]; for (int i = 0; i < arr.length; i++) { int radixVal = doubleToU32(arr[i]); int radixPiece = (radixVal >> byteIndex) & 0xff; sortOffsets[radixPiece]++; } int total = 0; for (int i = 0; i < sortOffsets.length; i++) { int count = sortOffsets[i]; sortOffsets[i] = total; total += count; } for (int i = 0; i < arr.length; i++) { int radixVal = doubleToU32(arr[i]); int radixPiece = (radixVal >> byteIndex) & 0xff; if (sortOffsets[radixPiece] < output.length) output[sortOffsets[radixPiece]++] = arr[i]; } for (int i = 0; i < arr.length; i++) { arr[i] = output[i]; } } int i; for (i = 0; i < arr.length; i++) { if (arr[i] >= 0) break; } if (i > 0 && i < arr.length) { int posNumLen = arr.length - i; int negNumLen = i; int index; double[] posNums = new double[posNumLen]; double[] negNums = new double[negNumLen]; for (index = 0; index < posNumLen; index++) { posNums[index] = arr[index + i]; } for (index = 0; index < negNumLen; index++) { negNums[index] = arr[index]; } reverseArrayd(negNums); // Reassemble the array: i = 0; for (index = 0; index < negNumLen; index++) { arr[i++] = negNums[index]; } for (index = 0; index < posNumLen; index++) { arr[i++] = posNums[index]; } } if (sortType == SortType.DESCENDING) reverseArrayd(arr); return true; } /** * Reverses byte array. * * @param arr byte array to reverse. */ public static void reverseArrayb(byte[] arr) { if (arr == null || arr.length <= 1) return; byte temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Reverses short array. * * @param arr short array to reverse. */ public static void reverseArrays(short[] arr) { if (arr == null || arr.length <= 1) return; short temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Reverses int array. * * @param arr int array to reverse. */ public static void reverseArrayi(int[] arr) { if (arr == null || arr.length <= 1) return; int temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Reverses long array. * * @param arr long array to reverse. */ public static void reverseArrayl(long[] arr) { if (arr == null || arr.length <= 1) return; long temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Reverses float array. * * @param arr float array to reverse. */ public static void reverseArrayf(float[] arr) { if (arr == null || arr.length <= 1) return; float temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Reverses double array. * * @param arr double array to reverse. */ public static void reverseArrayd(double[] arr) { if (arr == null || arr.length <= 1) return; double temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Reverses object array. * * @param arr object array to reverse. */ public static void reverseArray(Object[] arr) { if (arr == null || arr.length <= 1) return; Object temp; for (int i = 0; i < arr.length / 2; i++) { temp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[i]; arr[i] = temp; } } /** * Attempts to convert an int to a u32 int. * * @param val value to convert. * @return converted int. */ public static int intToU32(int val) { int result = val; if (result < 0) result = ~result; else result |= 0x80000000; return result; } /** * Attempts to convert an int to a u32 int. * * @param val value to convert. * @return converted int. */ public static int floatToU32(float val) { int result = (int) val; if (result < 0) result = ~result; else result |= 0x80000000; return result; } /** * Attempts to convert an int to a u32 int. * * @param val value to convert. * @return converted int. */ public static int doubleToU32(double val) { int result = (int) val; if (result < 0) result = ~result; else result |= 0x80000000; return result; } }
package de.uniaugsburg.isse; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import de.uniaugsburg.isse.abstraction.CplexExporter; import de.uniaugsburg.isse.abstraction.GeneralAbstraction; import de.uniaugsburg.isse.abstraction.SamplingAbstraction; import de.uniaugsburg.isse.abstraction.TemporalAbstraction; import de.uniaugsburg.isse.abstraction.types.Interval; import de.uniaugsburg.isse.abstraction.types.PiecewiseLinearFunction; import de.uniaugsburg.isse.constraints.BoundsConstraint; import de.uniaugsburg.isse.constraints.Constraint; import de.uniaugsburg.isse.constraints.RateOfChangeConstraint; import de.uniaugsburg.isse.cplex.CPLEXSolverFacade; import de.uniaugsburg.isse.powerplants.PowerPlantData; import de.uniaugsburg.isse.powerplants.PowerPlantState; import de.uniaugsburg.isse.solver.AbstractModel; import de.uniaugsburg.isse.solver.AbstractSolver; import de.uniaugsburg.isse.solver.CplexModel; import de.uniaugsburg.isse.solver.CplexSolver; import de.uniaugsburg.isse.solver.SolverFacade; import de.uniaugsburg.isse.util.AbstractionParameterLiterals; import de.uniaugsburg.isse.util.PowerPlantUtil; import de.uniaugsburg.isse.util.Utils; public class SamplingAbstractionTest { private Collection<PowerPlantData> children; private PowerPlantData avpp; private GeneralAbstraction ga; private AbstractSolver solver; private Map<String, PowerPlantState> singletonState; private Map<String, PowerPlantState> allStates; @Before public void setUp() throws Exception { avpp = new PowerPlantData("AVPP1"); avpp.setAVPP(true); avpp.put(AbstractionParameterLiterals.POWER_INIT, "265.0"); avpp.put(AbstractionParameterLiterals.CONSRUNNING_INIT, "1"); avpp.put(AbstractionParameterLiterals.CONSSTOPPING_INIT, "0"); PowerPlantState avppState = new PowerPlantState(); avppState.setConsRunning(new Interval<Integer>(1)); avppState.setConsStopping(new Interval<Integer>(0)); avppState.setPower(new Interval<Double>(265.0)); // has three plants available allStates = new HashMap<String, PowerPlantState>(); PowerPlantData pp1 = PowerPlantUtil.getPowerPlant("PP1", 50.0, 100.0, 0.15); PowerPlantUtil.addState(allStates, pp1); // pp1 gets two soft constraints // c1_rateOfChangeOpt 7% Constraint c1RateOpt = new RateOfChangeConstraint(pp1, 0.07); // c2_rateOfChangePref 10% Constraint c2RatePref = new RateOfChangeConstraint(pp1, 0.1); // TODO use cr c1RateOpt.setWeight(2); c2RatePref.setWeight(1); c1RateOpt.setSoft(true); c2RatePref.setSoft(true); pp1.addConstraint(c1RateOpt); pp1.addConstraint(c2RatePref); PowerPlantData pp2 = PowerPlantUtil.getPowerPlant("PP2", 15.0, 35.0, 0.125); PowerPlantUtil.addState(allStates, pp2); // pp2 gets three soft constraints // c1_economically_optimal: production[t] >= 22 && production[t] <= 25; // c2_economically_good: production[t] >= 20 && production[t] <= 30; // c3_economically_acc: production[t] >= 18 && production[t] <= 33; Constraint c1EconomicallyOptimal = new BoundsConstraint(pp2, 22.0, 25.0); Constraint c2EconomicallyGood = new BoundsConstraint(pp2, 20.0, 30.0); Constraint c3EconomicallyAcc = new BoundsConstraint(pp2, 18.0, 33.0); c1EconomicallyOptimal.setSoft(true); c2EconomicallyGood.setSoft(true); c3EconomicallyAcc.setSoft(true); // TODO use CRs c1EconomicallyOptimal.setWeight(4); c2EconomicallyGood.setWeight(2); c3EconomicallyAcc.setWeight(1); pp2.addConstraint(c1EconomicallyOptimal); pp2.addConstraint(c2EconomicallyGood); pp2.addConstraint(c3EconomicallyAcc); PowerPlantData pp3 = PowerPlantUtil.getPowerPlant("PP3", 200.0, 400.0, 0.2); PowerPlantUtil.addState(allStates, pp3); // pp3 gets three soft constraints // c1_economically_optimal: production[t] >= 300.0 && production[t] <= 350.0; // c2_economically_good: production[t] >= 280.0 && production[t] <= 370.0; // c3_rate_of_change_opt: (running[t] == 1) => abs(production[t] - production[t+1]) <= production[t] * 0.1; Constraint c1EconomicallyOptimalP3 = new BoundsConstraint(pp3, 300, 350.0); Constraint c2EconomicallyGoodP3 = new BoundsConstraint(pp3, 280.0, 370.0); Constraint c3RateOfChangeOpt = new RateOfChangeConstraint(pp3, 0.1); c1EconomicallyOptimalP3.setSoft(true); c2EconomicallyGoodP3.setSoft(true); c3RateOfChangeOpt.setSoft(true); c1EconomicallyOptimalP3.setWeight(3); c2EconomicallyGoodP3.setWeight(1); c3RateOfChangeOpt.setWeight(1); pp3.addConstraint(c1EconomicallyOptimalP3); pp3.addConstraint(c2EconomicallyGoodP3); pp3.addConstraint(c3RateOfChangeOpt); // not really needed any more pp1.put(AbstractionParameterLiterals.COSTS_PER_KWH, "13.0"); pp2.put(AbstractionParameterLiterals.COSTS_PER_KWH, "70.0"); pp3.put(AbstractionParameterLiterals.COSTS_PER_KWH, "5.0"); pp1.setCostFunction(new PiecewiseLinearFunction(50.0, 100.0, 13.0)); pp2.setCostFunction(new PiecewiseLinearFunction(15.0, 35.0, 70.0)); pp3.setCostFunction(new PiecewiseLinearFunction(200.0, 400.0, 5.0)); children = new ArrayList<PowerPlantData>(3); children.add(pp1); children.add(pp2); children.add(pp3); ga = new GeneralAbstraction(); ga.setPowerPlants(children); ga.perform(); ga.print(); TemporalAbstraction ta = new TemporalAbstraction(); ta.setPowerPlants(children); ta.setGeneralFeasibleRegions(ga.getFeasibleRegions()); ta.setGeneralHoles(ga.getHoles()); ta.perform(3); avpp.setFeasibleRegions(ga.getFeasibleRegions()); avpp.setAllFeasibleRegions(ta.getAllFeasibleRegions()); avpp.setAllHoles(ta.getAllHoles()); singletonState = new HashMap<String, PowerPlantState>(); singletonState.put(avpp.getName(), avppState); solver = new CplexSolver(); AbstractModel model = new CplexModel(); model.setUseSoftConstraints(true); PowerPlantUtil.populateDefaultSamplingModel(solver, model, avpp, children); // use soft constraint penalty as dexpr Collection<String> dexpr = new ArrayList<String>(1); dexpr.add(AbstractionParameterLiterals.PENALTY_SUM + "Init = " + AbstractionParameterLiterals.PENALTY_SUM + "[0]"); model.addDecisionExpressions(dexpr); } @Test public void test() { System.out.println("STARTING TEST:::: "); ga.print(); SamplingAbstraction sa = new SamplingAbstraction(ga.getFeasibleRegions(), ga.getHoles()); // ----------------------------------------- parameters for experiment boolean doPDelta, doNDelta, doPenalty, doCosts; doPDelta = false; doNDelta = false; doCosts = true; doPenalty = false; int samplingPoints = 50; // ----------------------------------------- end parameters for experiment Collection<String> objectives = new ArrayList<String>(1); if (doPDelta) objectives.add(AbstractionParameterLiterals.DEXP_POWER + "Succ"); Collection<String> minimizationObjectives = new ArrayList<String>(2); if (doNDelta) minimizationObjectives.add(AbstractionParameterLiterals.DEXP_POWER + "Succ"); if (doCosts) minimizationObjectives.add(AbstractionParameterLiterals.DEXP_COSTS + "Init"); if (doPenalty) minimizationObjectives.add(AbstractionParameterLiterals.PENALTY_SUM + "Init"); sa.setMaximizationDecisionExpressions(objectives); sa.setMinimizationDecisionExpressions(minimizationObjectives); sa.setSolver(solver); sa.perform(samplingPoints); PiecewiseLinearFunction positiveDelta = null; if (doPDelta) { positiveDelta = sa.getPiecewiseLinearFunction(AbstractionParameterLiterals.DEXP_POWER + "Succ", false); avpp.setPositiveDelta(positiveDelta); } PiecewiseLinearFunction negativeDelta = null; if (doNDelta) { negativeDelta = sa.getPiecewiseLinearFunction(AbstractionParameterLiterals.DEXP_POWER + "Succ", true); avpp.setNegativeDelta(negativeDelta); } PiecewiseLinearFunction costFunction = sa.getPiecewiseLinearFunction(AbstractionParameterLiterals.DEXP_COSTS + "Init", true); PiecewiseLinearFunction penaltyFunction = sa.getPiecewiseLinearFunction(AbstractionParameterLiterals.PENALTY_SUM + "Init", true); if (doPDelta) writeData("PositiveDelta_" + samplingPoints + ".csv", positiveDelta); if (doNDelta) writeData("NegativeDelta_" + samplingPoints + ".csv", negativeDelta); if (doCosts) writeData("Costs" + samplingPoints + ".csv", costFunction); if (doPenalty) writeData("Penalty" + samplingPoints + ".csv", penaltyFunction); if (doCosts && doNDelta && doPDelta && doPenalty) { CplexExporter exporter = new CplexExporter(); exporter.setUseSamplingAbstraction(true); Collection<PowerPlantData> singleton = new ArrayList<PowerPlantData>(1); singleton.add(avpp); exporter.setTimeHorizon(3); System.out.println("=================================== SYNTHESIZED MODEL ================================= "); printSynthesizedModel(exporter); System.out.println("=================================== ABSTRACTED MODEL ================================= "); printAbstractedModel(exporter, singleton); } } private void writeData(String fileName, PiecewiseLinearFunction pwlFunction) { StringBuilder content = new StringBuilder(); double[] ins = pwlFunction.getIns(), outs = pwlFunction.getOuts(); for (int i = 0; i < pwlFunction.getNumberInputOutputPairs(); ++i) { content.append(Double.toString(ins[i]) + ";" + Double.toString(outs[i]) + "\n"); } Utils.writeFile(fileName, content.toString()); } private void printSynthesizedModel(CplexExporter exporter) { String synthesizedModel = exporter.createModel(children); TemporalAbstraction ta = new TemporalAbstraction(); GeneralAbstraction ga = new GeneralAbstraction(); ga.setPowerPlants(children); ga.perform(); ta.setGeneralFeasibleRegions(ga.getFeasibleRegions()); ta.setGeneralHoles(ga.getHoles()); ta.setPowerPlants(children); ta.perform(3); Double[] residualLoad = new Double[] { 50.0, 70.0, 120.0 }; String load = exporter.createResidualLoad(residualLoad); String initStateData = exporter.createInitStateData(allStates); System.out.println("========================================================="); System.out.println(synthesizedModel); System.out.println("=============================="); System.out.println(load + "\n" + initStateData); } private void printAbstractedModel(CplexExporter exporter, Collection<PowerPlantData> singleton) { String abstractedModel = exporter.createModel(singleton); String functionalData = exporter.writePiecewiseLinearData(singleton); TemporalAbstraction ta = new TemporalAbstraction(); GeneralAbstraction ga = new GeneralAbstraction(); ga.setPowerPlants(singleton); ga.perform(); ta.setGeneralFeasibleRegions(ga.getFeasibleRegions()); ta.setGeneralHoles(ga.getHoles()); ta.setPowerPlants(singleton); ta.perform(3); avpp.setAllFeasibleRegions(ta.getAllFeasibleRegions()); avpp.setAllHoles(ta.getAllHoles()); avpp.setHoles(ga.getHoles()); avpp.setFeasibleRegions(ga.getFeasibleRegions()); Double[] residualLoad = new Double[] { 50.0, 70.0, 120.0 }; String load = exporter.createResidualLoad(residualLoad); String initStateData = exporter.createInitStateData(singletonState); String abstractionData = exporter.getGeneralAbstractionData(singleton) + "\n" + exporter.getTemporalAbstractionData(singleton); System.out.println("========================================================="); System.out.println(abstractedModel); System.out.println("========================================================="); System.out.println(functionalData + "\n" + load + "\n" + initStateData + "\n" + abstractionData); } @Test public void testExtractingDecisionExpression() { SolverFacade facade = new CPLEXSolverFacade(); facade.solve("ExtractDecisionExpression.mod", null); double val = facade.getTotalProduction(1); System.out.println("VALUE? : " + val); } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2010 psiinon@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.encoder2; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.encoder.Encoder; import org.parosproxy.paros.view.AbstractFrame; import org.parosproxy.paros.view.View; import org.zaproxy.zap.utils.FontUtils; import org.zaproxy.zap.utils.ZapTextArea; public class EncodeDecodeDialog extends AbstractFrame { private static final long serialVersionUID = 1L; public static final String ENCODE_DECODE_FIELD = "EncodeDecodeInputField"; public static final String ENCODE_DECODE_RESULTFIELD = "EncodeDecodeResultField"; private static final Logger log = Logger.getLogger(EncodeDecodeDialog.class); private JTabbedPane jTabbed = null; private JPanel jPanel = null; private ZapTextArea inputField = null; private ZapTextArea base64EncodeField = null; private ZapTextArea base64DecodeField = null; private ZapTextArea urlEncodeField = null; private ZapTextArea urlDecodeField = null; private ZapTextArea asciiHexEncodeField = null; private ZapTextArea asciiHexDecodeField = null; private ZapTextArea HTMLEncodeField = null;// private ZapTextArea HTMLDecodeField = null;// private ZapTextArea JavaScriptEncodeField = null;// private ZapTextArea JavaScriptDecodeField = null;// private ZapTextArea sha1HashField = null; private ZapTextArea md5HashField = null; private ZapTextArea illegalUTF82ByteField = null; private ZapTextArea illegalUTF83ByteField = null; private ZapTextArea illegalUTF84ByteField = null; private ZapTextArea escapedTextField =null; private ZapTextArea unescapedTextField =null; private Encoder encoder = null; /** * @throws HeadlessException */ public EncodeDecodeDialog() throws HeadlessException { super(); initialize(); } /** * This method initializes this */ private void initialize() { this.setAlwaysOnTop(false); this.setContentPane(getJTabbed()); this.setTitle(Constant.messages.getString("enc2.title")); } private void addField (JPanel parent, int index, JComponent c, String title) { final java.awt.GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = index; gbc.insets = new java.awt.Insets(1,1,1,1); gbc.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc.fill = java.awt.GridBagConstraints.BOTH; gbc.weightx = 0.5D; gbc.weighty = 0.5D; final JScrollPane jsp = new JScrollPane(); jsp.setViewportView(c); jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jsp.setBorder( BorderFactory.createTitledBorder( null, title, TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, FontUtils.getFont(FontUtils.Size.standard), java.awt.Color.black)); parent.add(jsp, gbc); } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJTabbed() { if (jPanel == null) { /* jPanel = new JPanel(); jPanel.setPreferredSize(new java.awt.Dimension(800,600)); jPanel.setLayout(new GridBagLayout()); */ // jPanel is the outside one jPanel = new JPanel(); jPanel.setPreferredSize(new java.awt.Dimension(800,600)); jPanel.setLayout(new GridBagLayout()); jTabbed = new JTabbedPane(); jTabbed.setPreferredSize(new java.awt.Dimension(800,500)); final JPanel jPanel1 = new JPanel(); jPanel1.setLayout(new GridBagLayout()); final JPanel jPanel2 = new JPanel(); //jPanel2.setPreferredSize(new java.awt.Dimension(800,500)); jPanel2.setLayout(new GridBagLayout()); final JPanel jPanel3 = new JPanel(); //jPanel3.setPreferredSize(new java.awt.Dimension(800,500)); jPanel3.setLayout(new GridBagLayout()); final JPanel jPanel4 = new JPanel(); jPanel4.setLayout(new GridBagLayout()); final JPanel jPanel5 = new JPanel(); jPanel5.setLayout(new GridBagLayout()); // 3 tabs - Encode, Decode, Hash?? addField(jPanel1, 1, getBase64EncodeField(), Constant.messages.getString("enc2.label.b64Enc")); addField(jPanel1, 2, getUrlEncodeField(), Constant.messages.getString("enc2.label.urlEnc")); addField(jPanel1, 3, getAsciiHexEncodeField(), Constant.messages.getString("enc2.label.asciiEnc")); addField(jPanel1, 4, getHTMLEncodeField(), Constant.messages.getString("enc2.label.HTMLEnc")); addField(jPanel1, 5, getJavaScriptEncodeField(), Constant.messages.getString("enc2.label.JavaScriptEnc")); addField(jPanel2, 1, getBase64DecodeField(), Constant.messages.getString("enc2.label.b64Dec")); addField(jPanel2, 2, getUrlDecodeField(), Constant.messages.getString("enc2.label.urlDec")); addField(jPanel2, 3, getAsciiHexDecodeField(), Constant.messages.getString("enc2.label.asciiDec")); addField(jPanel2, 4, getHTMLDecodeField(), Constant.messages.getString("enc2.label.HTMLDec")); addField(jPanel2, 5, getJavaScriptDecodeField(), Constant.messages.getString("enc2.label.JavaScriptDec")); addField(jPanel3, 1, getSha1HashField(), Constant.messages.getString("enc2.label.sha1Hash")); addField(jPanel3, 2, getMd5HashField(), Constant.messages.getString("enc2.label.md5Hash")); addField(jPanel4, 1, getIllegalUTF82ByteField(), Constant.messages.getString("enc2.label.illegalUTF8.2byte")); addField(jPanel4, 2, getIllegalUTF83ByteField(), Constant.messages.getString("enc2.label.illegalUTF8.3byte")); addField(jPanel4, 3, getIllegalUTF84ByteField(), Constant.messages.getString("enc2.label.illegalUTF8.4byte")); addField(jPanel5, 1, getEscapedTextField(), Constant.messages.getString("enc2.label.unicode.escapedText")); addField(jPanel5, 2, getUnescapedTextField(), Constant.messages.getString("enc2.label.unicode.unescapedText")); jTabbed.addTab(Constant.messages.getString("enc2.tab.encode"), jPanel1); jTabbed.addTab(Constant.messages.getString("enc2.tab.decode"), jPanel2); jTabbed.addTab(Constant.messages.getString("enc2.tab.hash"), jPanel3); jTabbed.addTab(Constant.messages.getString("enc2.tab.illegalUTF8"), jPanel4); jTabbed.addTab(Constant.messages.getString("enc2.tab.unicode"), jPanel5); final java.awt.GridBagConstraints gbc1 = new GridBagConstraints(); gbc1.gridx = 0; gbc1.gridy = 1; gbc1.insets = new java.awt.Insets(1,1,1,1); gbc1.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc1.fill = java.awt.GridBagConstraints.BOTH; gbc1.weightx = 1.0D; gbc1.weighty = 0.25D; final java.awt.GridBagConstraints gbc2 = new GridBagConstraints(); gbc2.gridx = 0; gbc2.gridy = 2; gbc2.insets = new java.awt.Insets(1,1,1,1); gbc2.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc2.fill = java.awt.GridBagConstraints.BOTH; gbc2.weightx = 1.0D; gbc2.weighty = 1.0D; final JScrollPane jsp = new JScrollPane(); jsp.setViewportView(getInputField()); jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jsp.setBorder( BorderFactory.createTitledBorder( null, Constant.messages.getString("enc2.label.text"), TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, FontUtils.getFont(FontUtils.Size.standard), java.awt.Color.black)); //addField(jPanel, 1, getInputField(), "Text to be encoded/decoded/hashed"); //addField(jPanel, 2, jTabbed, "Text to be encoded/decoded/hashed"); jPanel.add(jsp, gbc1); jPanel.add(jTabbed, gbc2); jPanel2.requestFocus(); } return jPanel; } private ZapTextArea newField(boolean editable) { final ZapTextArea field = new ZapTextArea(); field.setLineWrap(true); field.setBorder(BorderFactory.createEtchedBorder()); field.setEditable(editable); field.setName(ENCODE_DECODE_RESULTFIELD); field.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { View.getSingleton().getPopupMenu().show(e.getComponent(), e.getX(), e.getY()); } } }); return field; } private ZapTextArea getInputField() { if (inputField == null) { inputField = newField(true); inputField.setName(ENCODE_DECODE_FIELD); inputField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent documentEvent) { updateEncodeDecodeFields(); } @Override public void removeUpdate(DocumentEvent documentEvent) { updateEncodeDecodeFields(); } @Override public void changedUpdate(DocumentEvent documentEvent) { } }); inputField.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { View.getSingleton().getPopupMenu().show(e.getComponent(), e.getX(), e.getY()); } } }); } return inputField; } private ZapTextArea getBase64EncodeField() { if (base64EncodeField == null) { base64EncodeField = newField(false); } return base64EncodeField; } private ZapTextArea getBase64DecodeField() { if (base64DecodeField == null) { base64DecodeField = newField(false); } return base64DecodeField; } private ZapTextArea getUrlEncodeField() { if (urlEncodeField == null) { urlEncodeField = newField(false); } return urlEncodeField; } private ZapTextArea getUrlDecodeField() { if (urlDecodeField == null) { urlDecodeField = newField(false); } return urlDecodeField; } private ZapTextArea getAsciiHexEncodeField() { if (asciiHexEncodeField == null) { asciiHexEncodeField = newField(false); } return asciiHexEncodeField; } private ZapTextArea getAsciiHexDecodeField() { if (asciiHexDecodeField == null) { asciiHexDecodeField = newField(false); } return asciiHexDecodeField; } private ZapTextArea getHTMLEncodeField() {// if (HTMLEncodeField == null) { HTMLEncodeField = newField(false); } return HTMLEncodeField; } private ZapTextArea getHTMLDecodeField() {// if (HTMLDecodeField == null) { HTMLDecodeField = newField(false); } return HTMLDecodeField; } private ZapTextArea getJavaScriptEncodeField() {// if (JavaScriptEncodeField == null) { JavaScriptEncodeField = newField(false); } return JavaScriptEncodeField; } private ZapTextArea getJavaScriptDecodeField() {// if (JavaScriptDecodeField == null) { JavaScriptDecodeField = newField(false); } return JavaScriptDecodeField; } private ZapTextArea getSha1HashField() { if (sha1HashField == null) { sha1HashField = newField(false); } return sha1HashField; } private ZapTextArea getMd5HashField() { if (md5HashField == null) { md5HashField = newField(false); } return md5HashField; } private ZapTextArea getIllegalUTF82ByteField() { if (illegalUTF82ByteField == null) { illegalUTF82ByteField = newField(false); } return illegalUTF82ByteField; } private ZapTextArea getIllegalUTF83ByteField() { if (illegalUTF83ByteField == null) { illegalUTF83ByteField = newField(false); } return illegalUTF83ByteField; } private ZapTextArea getIllegalUTF84ByteField() { if (illegalUTF84ByteField == null) { illegalUTF84ByteField = newField(false); } return illegalUTF84ByteField; } private ZapTextArea getEscapedTextField() { if (escapedTextField == null) { escapedTextField = newField(false); } return escapedTextField; } private ZapTextArea getUnescapedTextField() { if (unescapedTextField == null) { unescapedTextField = newField(false); } return unescapedTextField; } private Encoder getEncoder() { if (encoder == null) { encoder = new Encoder(); } return encoder; } public String decodeHexString(String hexText) { String decodedText=""; String chunk=null; if(hexText!=null && hexText.length()>0) { final int numBytes = hexText.length()/2; final byte[] rawToByte = new byte[numBytes]; int offset=0; for(int i =0; i <numBytes; i++) { chunk = hexText.substring(offset,offset+2); offset+=2; rawToByte[i] = (byte) (Integer.parseInt(chunk,16) & 0x000000FF); } decodedText= new String(rawToByte); } return decodedText; } public String decodeHTMLString(String HTMLText) { return StringEscapeUtils.unescapeHtml(HTMLText); } public String decodeJavaScriptString(String JavaScriptText) { return StringEscapeUtils.unescapeJavaScript(JavaScriptText); } private static String encodeUnicodeString(String str) { str = str == null ? "" : str; String tmp; StringBuilder sb = new StringBuilder(); char c; int i, j; sb.setLength(0); for (i = 0; i < str.length(); i++) { c = str.charAt(i); sb.append("%u"); j = (c >>>8); //pop high 8 bits tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append('0'); sb.append(tmp); j = (c & 0xFF); //pop low 8 bits tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append('0'); sb.append(tmp); } return (sb.toString()); } private static String decodeUnicodeString(String str) { str = str == null ? "" : str; if (str.indexOf("%u") == -1) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i <= str.length() - 6;) { String strTemp = str.substring(i, i + 6); String value = strTemp.substring(2); int c = 0; for (int j = 0; j < value.length(); j++) { char tempChar = value.charAt(j); int t = 0; switch (tempChar) { case 'a': t = 10; break; case 'b': t = 11; break; case 'c': t = 12; break; case 'd': t = 13; break; case 'e': t = 14; break; case 'f': t = 15; break; default: t = tempChar - 48; break; } c += t * ((int) Math.pow(16, (value.length() - j - 1))); } sb.append((char) c); i = i + 6; } return sb.toString(); } private void updateEncodeDecodeFields() { // Base 64 try { base64EncodeField.setText(getEncoder().getBase64Encode(getInputField().getText())); } catch (NullPointerException | IOException e) { log.error(e.getMessage(), e); } try { base64DecodeField.setText(getEncoder().getBase64Decode(getInputField().getText())); base64DecodeField.setEnabled(base64DecodeField.getText().length() > 0); } catch (IOException | IllegalArgumentException e) { base64DecodeField.setText(e.getMessage()); base64DecodeField.setEnabled(false); } // URLs urlEncodeField.setText(getEncoder().getURLEncode(getInputField().getText())); try { urlDecodeField.setText(getEncoder().getURLDecode(getInputField().getText())); } catch (final Exception e) { // Not unexpected urlDecodeField.setText(""); } urlDecodeField.setEnabled(urlDecodeField.getText().length() > 0); // ASCII Hex asciiHexEncodeField.setText( getEncoder().getHexString( getInputField().getText().getBytes())); try { asciiHexDecodeField.setText(decodeHexString(getInputField().getText())); } catch (final Exception e) { // Not unexpected asciiHexDecodeField.setText(""); } asciiHexDecodeField.setEnabled(asciiHexDecodeField.getText().length() > 0); // HTML HTMLEncodeField.setText( getEncoder().getHTMLString( getInputField().getText())); try { HTMLDecodeField.setText(decodeHTMLString(getInputField().getText())); } catch (final Exception e) { // Not unexpected HTMLDecodeField.setText(""); } HTMLDecodeField.setEnabled(HTMLDecodeField.getText().length() > 0); // JavaScript JavaScriptEncodeField.setText( getEncoder().getJavaScriptString( getInputField().getText())); try { JavaScriptDecodeField.setText(decodeJavaScriptString(getInputField().getText())); } catch (final Exception e) { // Not unexpected JavaScriptDecodeField.setText(""); } JavaScriptDecodeField.setEnabled(JavaScriptDecodeField.getText().length() > 0); // Hashes try { sha1HashField.setText( getEncoder().getHexString( getEncoder().getHashSHA1( getInputField().getText().getBytes()))); } catch (final Exception e) { sha1HashField.setText(""); } try { md5HashField.setText( getEncoder().getHexString( getEncoder().getHashMD5( getInputField().getText().getBytes()))); } catch (final Exception e) { md5HashField.setText(""); } //Illegal UTF8 try { illegalUTF82ByteField.setText(getEncoder().getIllegalUTF8Encode(getInputField().getText(), 2)); } catch (final Exception e) { // Not unexpected illegalUTF82ByteField.setText(""); } try { illegalUTF83ByteField.setText(getEncoder().getIllegalUTF8Encode(getInputField().getText(), 3)); } catch (final Exception e) { // Not unexpected illegalUTF83ByteField.setText(""); } try { illegalUTF84ByteField.setText(getEncoder().getIllegalUTF8Encode(getInputField().getText(), 4)); } catch (final Exception e) { // Not unexpected illegalUTF84ByteField.setText(""); } try { escapedTextField.setText(encodeUnicodeString(getInputField().getText())); } catch (final Exception e) { escapedTextField.setText(""); } try { unescapedTextField.setText(decodeUnicodeString(getInputField().getText())); } catch (final Exception e) { unescapedTextField.setText(""); } } public void setInputField (String text) { this.getInputField().setText(text); this.updateEncodeDecodeFields(); } public void updateOptions(EncodeDecodeParam options) { getEncoder().setBase64Charset(options.getBase64Charset()); getEncoder().setBase64DoBreakLines(options.isBase64DoBreakLines()); updateEncodeDecodeFields(); } }
package com.symbolplay.tria.screens; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.ObjectMap; import com.symbolplay.gamelibrary.util.GameUtils; import com.symbolplay.tria.GameContainer; import com.symbolplay.tria.game.Sounds; import com.symbolplay.tria.game.rise.Rise; import com.symbolplay.tria.resources.ResourceNames; import com.symbolplay.tria.screens.general.ChangeParamKeys; import com.symbolplay.tria.screens.playscore.PlayScoreAccessor; public final class PlayScreen extends ScreenBase { // private static final long DEBUG_LABEL_UPDATE_INTERVAL = 100l; private final Rise rise; private Label livesLabel; private Label coinsLabel; private Label scoreLabel; // private final Label debugLabel; // private long debugLabelLastUpdateTime = 0l; public PlayScreen(GameContainer game) { super(game); guiStage.addListener(getStageInputListener()); PlayScoreAccessor playScoreAccessor = new PlayScoreAccessor(gameData, game.getTriaServiceAccessor()); rise = new Rise(cameraData, gameData.getCareerData(), resources.getGameAreaFont(), playScoreAccessor, assetManager); addTopDisplay(); // debugLabel = new Label("", guiSkin); // debugLabel.setBounds(0.0f, 0.0f, 20.0f, 72.0f); // debugLabel.setAlignment(Align.left); // guiStage.addActor(debugLabel); } @Override public void show(ObjectMap<String, Object> changeParams) { super.show(changeParams); rise.reset(); } @Override public void hide() { Sounds.stopAll(); cameraData.setGameAreaPosition(0.0f, 0.0f); super.hide(); } @Override public void pause() { Sounds.pauseAll(); super.pause(); } @Override public void resume(ObjectMap<String, Object> changeParams) { super.resume(changeParams); if (changeParams != null && (Boolean) changeParams.get(ChangeParamKeys.EXIT_PLAY)) { updateCareerData(); game.changeScreen(GameContainer.MAIN_MENU_SCREEN_NAME); } else { Sounds.resumeAll(); } } @Override protected void updateImpl(float delta) { // Profiling.startTime(1); if (rise.isFinished()) { updateCareerData(); ObjectMap<String, Object> changeParams = new ObjectMap<String, Object>(1); changeParams.put(ChangeParamKeys.SCORE, rise.getScore()); game.changeScreen(GameContainer.GAME_OVER_SCREEN_NAME, changeParams); } rise.update(delta); livesLabel.setText("x" + String.valueOf(rise.getLives())); coinsLabel.setText("x" + String.valueOf(rise.getCoins())); scoreLabel.setText(String.valueOf(rise.getScore())); // Profiling.endTime(1, "Update", true); } @Override public void renderImpl() { // Profiling.startTime(2); rise.render(); // TODO: only for debugging // if (System.currentTimeMillis() - debugLabelLastUpdateTime >= DEBUG_LABEL_UPDATE_INTERVAL) { // DebugData debugData = rise.getDebugData(); // debugLabel.setText(debugData.toString()); // debugLabelLastUpdateTime = System.currentTimeMillis(); // } // Profiling.endTime(2, "Render", true); } private void addTopDisplay() { TextureAtlas atlas = assetManager.get(ResourceNames.GRAPHICS_GUI_ATLAS); float topDisplayHeight = 40.0f; float padding = 5.0f; float topDisplayY = GameContainer.VIEWPORT_HEIGHT - topDisplayHeight; float topLineThickness = 2.0f; Image topBackgroundImage = getImage(atlas, ResourceNames.GUI_PLAY_TOP_BACKGROUND_IMAGE_NAME); topBackgroundImage.setBounds(0.0f, topDisplayY, GameContainer.VIEWPORT_WIDTH, topDisplayHeight); topBackgroundImage.setColor(1.0f, 1.0f, 1.0f, 0.8f); guiStage.addActor(topBackgroundImage); Image topLineImage = getImage(atlas, ResourceNames.GUI_PLAY_TOP_LINE_IMAGE_NAME); topLineImage.setBounds(0.0f, topDisplayY, GameContainer.VIEWPORT_WIDTH, topLineThickness); topLineImage.setColor(0.0f, 0.0f, 0.0f, 1.0f); guiStage.addActor(topLineImage); ImageButton pauseButton = new ImageButton(GameUtils.getTextureDrawable(atlas, ResourceNames.GUI_PLAY_PAUSE_IMAGE_NAME)); pauseButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { game.pushScreen(GameContainer.PAUSE_SCREEN_NAME); } }); Image livesImage = getImage(atlas, ResourceNames.GUI_PLAY_LIVES_IMAGE_NAME); guiStage.addActor(livesImage); livesLabel = new Label("", guiSkin, "font24"); livesLabel.setAlignment(Align.center | Align.left); guiStage.addActor(livesLabel); Image coinsImage = getImage(atlas, ResourceNames.GUI_PLAY_COINS_IMAGE_NAME); guiStage.addActor(coinsImage); coinsLabel = new Label("", guiSkin, "font24"); coinsLabel.setAlignment(Align.center | Align.left); guiStage.addActor(coinsLabel); scoreLabel = new Label("", guiSkin, "font32"); scoreLabel.setAlignment(Align.center | Align.right); guiStage.addActor(scoreLabel); float livesLabelWidth = 55.0f; float coinsLabelWidth = 83.0f; float scoreLabelWidth = GameContainer.VIEWPORT_WIDTH - padding * 9.0f - livesLabelWidth - coinsLabelWidth - pauseButton.getWidth() - livesImage.getWidth() - coinsImage.getWidth(); Table table = new Table(guiSkin); table.top().left(); table.setBounds(0.0f, topDisplayY, GameContainer.VIEWPORT_WIDTH, topDisplayHeight); table.add(pauseButton).padRight(padding); table.add(livesImage).padLeft(padding).padRight(padding).center(); table.add(livesLabel).width(livesLabelWidth).padTop(2.0f).padRight(padding + 2.0f).center(); table.add(coinsImage).padLeft(padding).padTop(2.0f).padRight(padding).center(); table.add(coinsLabel).width(coinsLabelWidth).padTop(2.0f).padRight(padding).center(); table.add(scoreLabel).width(scoreLabelWidth).padTop(-3.0f).padBottom(-3.0f).padRight(padding); guiStage.addActor(table); } private static Image getImage(TextureAtlas atlas, String imageName) { Image image = new Image(GameUtils.getTextureDrawable(atlas, imageName)); return image; } private void updateCareerData() { gameData.getCareerData().changeCoins(rise.getCoins()); gameData.getCareerData().setInitialLivesNextGame(0); } private InputListener getStageInputListener() { return new InputListener() { private boolean isBackAlreadyPressed = false; @Override public boolean keyDown(InputEvent event, int keycode) { if ((keycode == Keys.ESCAPE || keycode == Keys.BACK) && !isBackAlreadyPressed) { game.pushScreen(GameContainer.PAUSE_SCREEN_NAME); isBackAlreadyPressed = true; return true; } return false; } @Override public boolean keyUp(InputEvent event, int keycode) { if (keycode == Keys.ESCAPE || keycode == Keys.BACK) { isBackAlreadyPressed = false; return true; } return false; } }; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.authentication; import java.util.Base64; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; /** * Test for {@link IgniteAuthenticationProcessor}. */ public class AuthenticationProcessorSelfTest extends GridCommonAbstractTest { /** Nodes count. */ protected static final int NODES_COUNT = 4; /** Iterations count. */ private static final int ITERATIONS = 10; /** Client node. */ protected static final int CLI_NODE = NODES_COUNT - 1; /** Random. */ private static final Random RND = new Random(System.currentTimeMillis()); /** Authorization context for default user. */ protected AuthorizationContext actxDflt; /** * @param len String length. * @return Random string (Base64 on random bytes). */ private static String randomString(int len) { byte[] rndBytes = new byte[len / 2]; RND.nextBytes(rndBytes); return Base64.getEncoder().encodeToString(rndBytes); } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setAuthenticationEnabled(true); cfg.setDataStorageConfiguration(new DataStorageConfiguration() .setDefaultDataRegionConfiguration(new DataRegionConfiguration() .setMaxSize(200L * 1024 * 1024) .setPersistenceEnabled(true))); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); GridTestUtils.setFieldValue(User.class, "bCryptGensaltLog2Rounds", 4); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { super.afterTestsStopped(); GridTestUtils.setFieldValue(User.class, "bCryptGensaltLog2Rounds", 10); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); U.resolveWorkDirectory(U.defaultWorkDirectory(), "db", true); startGrids(NODES_COUNT - 1); startClientGrid(CLI_NODE); grid(0).cluster().active(true); actxDflt = grid(0).context().authentication().authenticate(User.DFAULT_USER_NAME, "ignite"); assertNotNull(actxDflt); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); super.afterTest(); } /** * @throws Exception If failed. */ @Test public void testDefaultUser() throws Exception { for (int i = 0; i < NODES_COUNT; ++i) { AuthorizationContext actx = grid(i).context().authentication().authenticate("ignite", "ignite"); assertNotNull(actx); assertEquals("ignite", actx.userName()); } } /** * @throws Exception If failed. */ @Test public void testDefaultUserUpdate() throws Exception { AuthorizationContext.context(actxDflt); try { // Change from all nodes for (int nodeIdx = 0; nodeIdx < NODES_COUNT; ++nodeIdx) { grid(nodeIdx).context().authentication().updateUser("ignite", "ignite" + nodeIdx); // Check each change from all nodes for (int i = 0; i < NODES_COUNT; ++i) { AuthorizationContext actx = grid(i).context().authentication().authenticate("ignite", "ignite" + nodeIdx); assertNotNull(actx); assertEquals("ignite", actx.userName()); } } } finally { AuthorizationContext.clear(); } } /** * @throws Exception If failed. */ @Test public void testRemoveDefault() throws Exception { AuthorizationContext.context(actxDflt); try { for (int i = 0; i < NODES_COUNT; ++i) { final int nodeIdx = i; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().removeUser("ignite"); return null; } }, IgniteAccessControlException.class, "Default user cannot be removed"); assertNotNull(grid(nodeIdx).context().authentication().authenticate("ignite", "ignite")); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testUserManagementPermission() throws Exception { AuthorizationContext.context(actxDflt); try { grid(0).context().authentication().addUser("test", "test"); final AuthorizationContext actx = grid(0).context().authentication().authenticate("test", "test"); for (int i = 0; i < NODES_COUNT; ++i) { final int nodeIdx = i; AuthorizationContext.context(actx); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().addUser("test1", "test1"); return null; } }, IgniteAccessControlException.class, "User management operations are not allowed for user"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().removeUser("test"); return null; } }, IgniteAccessControlException.class, "User management operations are not allowed for user"); grid(nodeIdx).context().authentication().updateUser("test", "new_password"); grid(nodeIdx).context().authentication().updateUser("test", "test"); // Check error on empty auth context: AuthorizationContext.context(null); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().removeUser("test"); return null; } }, IgniteAccessControlException.class, "Operation not allowed: authorized context is empty"); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testProceedUsersOnJoinNode() throws Exception { AuthorizationContext.context(actxDflt); try { grid(0).context().authentication().addUser("test0", "test"); grid(0).context().authentication().addUser("test1", "test"); int nodeIdx = NODES_COUNT; startGrid(nodeIdx); AuthorizationContext actx0 = grid(nodeIdx).context().authentication().authenticate("test0", "test"); AuthorizationContext actx1 = grid(nodeIdx).context().authentication().authenticate("test1", "test"); assertNotNull(actx0); assertEquals("test0", actx0.userName()); assertNotNull(actx1); assertEquals("test1", actx1.userName()); } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testAuthenticationInvalidUser() throws Exception { AuthorizationContext.context(actxDflt); try { for (int i = 0; i < NODES_COUNT; ++i) { final int nodeIdx = i; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().authenticate("invalid_name", "test"); return null; } }, IgniteAccessControlException.class, "The user name or password is incorrect"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().authenticate("test", "invalid_password"); return null; } }, IgniteAccessControlException.class, "The user name or password is incorrect"); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testAddUpdateRemoveUser() throws Exception { AuthorizationContext.context(actxDflt); try { for (int i = 0; i < NODES_COUNT; ++i) { for (int j = 0; j < NODES_COUNT; ++j) checkAddUpdateRemoveUser(grid(i), grid(j)); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testUpdateUser() throws Exception { AuthorizationContext.context(actxDflt); try { grid(0).context().authentication().addUser("test", "test"); AuthorizationContext actx = grid(0).context().authentication().authenticate("test", "test"); for (int i = 0; i < NODES_COUNT; ++i) { for (int j = 0; j < NODES_COUNT; ++j) checkUpdateUser(actx, grid(i), grid(j)); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testUpdateRemoveDoesNotExistsUser() throws Exception { AuthorizationContext.context(actxDflt); try { for (int i = 0; i < NODES_COUNT; ++i) { final int nodeIdx = i; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().updateUser("invalid_name", "test"); return null; } }, UserManagementException.class, "User doesn't exist"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().removeUser("invalid_name"); return null; } }, UserManagementException.class, "User doesn't exist"); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testAddAlreadyExistsUser() throws Exception { AuthorizationContext.context(actxDflt); try { grid(0).context().authentication().addUser("test", "test"); for (int i = 0; i < NODES_COUNT; ++i) { final int nodeIdx = i; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(nodeIdx).context().authentication().addUser("test", "new_passwd"); return null; } }, UserManagementException.class, "User already exists"); } } finally { AuthorizationContext.context(null); } } /** * @throws Exception If failed. */ @Test public void testAuthorizeOnClientDisconnect() throws Exception { AuthorizationContext.context(actxDflt); grid(CLI_NODE).context().authentication().addUser("test", "test"); AuthorizationContext.context(null); final IgniteInternalFuture stopServersFut = GridTestUtils.runAsync(new Runnable() { @Override public void run() { try { for (int i = 0; i < CLI_NODE; ++i) { Thread.sleep(500); stopGrid(i); } } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception"); } } }); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { while (!stopServersFut.isDone()) { AuthorizationContext actx = grid(CLI_NODE).context().authentication() .authenticate("test", "test"); assertNotNull(actx); } return null; } }, IgniteCheckedException.class, "Client node was disconnected from topology (operation result is unknown)"); stopServersFut.get(); } /** * @throws Exception If failed. */ @Test public void testConcurrentAddRemove() throws Exception { final AtomicInteger usrCnt = new AtomicInteger(); GridTestUtils.runMultiThreaded(new Runnable() { @Override public void run() { AuthorizationContext.context(actxDflt); String user = "test" + usrCnt.getAndIncrement(); try { for (int i = 0; i < ITERATIONS; ++i) { grid(CLI_NODE).context().authentication().addUser(user, "passwd_" + user); grid(CLI_NODE).context().authentication().removeUser(user); } } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception"); } } }, 10, "user-op"); } /** * @throws Exception If failed. */ @Test public void testUserPersistence() throws Exception { AuthorizationContext.context(actxDflt); try { for (int i = 0; i < NODES_COUNT; ++i) grid(i).context().authentication().addUser("test" + i, "passwd" + i); grid(CLI_NODE).context().authentication().updateUser("ignite", "new_passwd"); stopAllGrids(); startGrids(NODES_COUNT - 1); startClientGrid(CLI_NODE); for (int i = 0; i < NODES_COUNT; ++i) { for (int usrIdx = 0; usrIdx < NODES_COUNT; ++usrIdx) { AuthorizationContext actx0 = grid(i).context().authentication() .authenticate("test" + usrIdx, "passwd" + usrIdx); assertNotNull(actx0); assertEquals("test" + usrIdx, actx0.userName()); } AuthorizationContext actx = grid(i).context().authentication() .authenticate("ignite", "new_passwd"); assertNotNull(actx); assertEquals("ignite", actx.userName()); } } finally { AuthorizationContext.clear(); } } /** * @throws Exception If failed. */ @Test public void testDefaultUserPersistence() throws Exception { AuthorizationContext.context(actxDflt); try { grid(CLI_NODE).context().authentication().addUser("test", "passwd"); stopAllGrids(); U.sleep(500); startGrids(NODES_COUNT - 1); startClientGrid(CLI_NODE); for (int i = 0; i < NODES_COUNT; ++i) { AuthorizationContext actx = grid(i).context().authentication() .authenticate("ignite", "ignite"); assertNotNull(actx); assertEquals("ignite", actx.userName()); actx = grid(i).context().authentication() .authenticate("test", "passwd"); assertNotNull(actx); assertEquals("test", actx.userName()); } } finally { AuthorizationContext.clear(); } } /** * @throws Exception If failed. */ @Test public void testInvalidUserNamePassword() throws Exception { AuthorizationContext.context(actxDflt); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(CLI_NODE).context().authentication().addUser(null, "test"); return null; } }, UserManagementException.class, "User name is empty"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(CLI_NODE).context().authentication().addUser("", "test"); return null; } }, UserManagementException.class, "User name is empty"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(CLI_NODE).context().authentication().addUser("test", null); return null; } }, UserManagementException.class, "Password is empty"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(CLI_NODE).context().authentication().addUser("test", ""); return null; } }, UserManagementException.class, "Password is empty"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(CLI_NODE).context().authentication().addUser( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "a"); return null; } }, UserManagementException.class, "User name is too long"); } /** * @param name User name to check. */ private void checkInvalidUsername(final String name) { } /** * @param passwd User's password to check. */ private void checkInvalidPassword(final String passwd) { AuthorizationContext.context(actxDflt); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { grid(CLI_NODE).context().authentication().addUser("test", passwd); return null; } }, UserManagementException.class, "Invalid user name"); } /** * @param createNode Node to execute create operation. * @param authNode Node to execute authentication. * @throws Exception On error. */ private void checkAddUpdateRemoveUser(IgniteEx createNode, IgniteEx authNode) throws Exception { createNode.context().authentication().addUser("test", "test"); AuthorizationContext newActx = authNode.context().authentication().authenticate("test", "test"); assertNotNull(newActx); assertEquals("test", newActx.userName()); createNode.context().authentication().updateUser("test", "newpasswd"); newActx = authNode.context().authentication().authenticate("test", "newpasswd"); assertNotNull(newActx); assertEquals("test", newActx.userName()); createNode.context().authentication().removeUser("test"); } /** * @param actx Authorization context. * @param updNode Node to execute update operation. * @param authNode Node to execute authentication. * @throws Exception On error. */ private void checkUpdateUser(AuthorizationContext actx, IgniteEx updNode, IgniteEx authNode) throws Exception { String newPasswd = randomString(16); updNode.context().authentication().updateUser("test", newPasswd); AuthorizationContext actxNew = authNode.context().authentication().authenticate("test", newPasswd); assertNotNull(actxNew); assertEquals("test", actxNew.userName()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.query.continuous; import java.io.NotSerializableException; import java.util.concurrent.Callable; import java.util.concurrent.ThreadLocalRandom; import javax.cache.processor.EntryProcessor; import javax.cache.processor.EntryProcessorException; import javax.cache.processor.MutableEntry; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CacheWriteSynchronizationMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.transactions.Transaction; import org.apache.ignite.transactions.TransactionConcurrency; import org.apache.ignite.transactions.TransactionIsolation; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.PRIMARY_SYNC; import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC; import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC; import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED; import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ; import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE; /** * */ public class CacheEntryProcessorNonSerializableTest extends GridCommonAbstractTest { /** */ private static final int EXPECTED_VALUE = 42; /** */ private static final int WRONG_VALUE = -1; /** */ private static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** */ private static final int NODES = 3; /** */ public static final int ITERATION_CNT = 1; /** */ public static final int KEYS = 10; /** */ private boolean client; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder); ((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1); cfg.setClientMode(client); cfg.setMarshaller(new OptimizedMarshaller()); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGridsMultiThreaded(getServerNodeCount()); client = true; startGrid(getServerNodeCount()); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); super.afterTestsStopped(); } /** * @return Server nodes. */ private int getServerNodeCount() { return NODES; } /** * @throws Exception If failed. */ public void testPessimisticOnePhaseCommit() throws Exception { CacheConfiguration ccfg = cacheConfiguration(PRIMARY_SYNC, 1); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testPessimisticOnePhaseCommitWithNearCache() throws Exception { CacheConfiguration ccfg = cacheConfiguration(PRIMARY_SYNC, 1) .setNearConfiguration(new NearCacheConfiguration()); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testPessimisticOnePhaseCommitFullSync() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 1); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testPessimisticOnePhaseCommitFullSyncWithNearCache() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 1) .setNearConfiguration(new NearCacheConfiguration()); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testPessimistic() throws Exception { CacheConfiguration ccfg = cacheConfiguration(PRIMARY_SYNC, 2); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testPessimisticWithNearCache() throws Exception { CacheConfiguration ccfg = cacheConfiguration(PRIMARY_SYNC, 2) .setNearConfiguration(new NearCacheConfiguration()); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testPessimisticFullSync() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 2); doTestInvokeTest(ccfg, PESSIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, PESSIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, PESSIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testOptimisticOnePhaseCommit() throws Exception { CacheConfiguration ccfg = cacheConfiguration(PRIMARY_SYNC, 1); doTestInvokeTest(ccfg, OPTIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, OPTIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, OPTIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testOptimisticOnePhaseCommitFullSync() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 1); doTestInvokeTest(ccfg, OPTIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, OPTIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, OPTIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testOptimisticOnePhaseCommitFullSyncWithNearCache() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 1) .setNearConfiguration(new NearCacheConfiguration()); doTestInvokeTest(ccfg, OPTIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, OPTIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, OPTIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testOptimistic() throws Exception { CacheConfiguration ccfg = cacheConfiguration(PRIMARY_SYNC, 2); doTestInvokeTest(ccfg, OPTIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, OPTIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, OPTIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testOptimisticFullSync() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 2); doTestInvokeTest(ccfg, OPTIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, OPTIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, OPTIMISTIC, SERIALIZABLE); } /** * @throws Exception If failed. */ public void testOptimisticFullSyncWithNearCache() throws Exception { CacheConfiguration ccfg = cacheConfiguration(FULL_SYNC, 2); doTestInvokeTest(ccfg, OPTIMISTIC, READ_COMMITTED); doTestInvokeTest(ccfg, OPTIMISTIC, REPEATABLE_READ); doTestInvokeTest(ccfg, OPTIMISTIC, SERIALIZABLE); } /** * @param ccfg Cache configuration. * @throws Exception If failed. */ private void doTestInvokeTest(CacheConfiguration ccfg, TransactionConcurrency txConcurrency, TransactionIsolation txIsolation) throws Exception { IgniteEx cln = grid(getServerNodeCount()); grid(0).createCache(ccfg); IgniteCache clnCache; if (ccfg.getNearConfiguration() != null) clnCache = cln.createNearCache(ccfg.getName(), ccfg.getNearConfiguration()); else clnCache = cln.cache(ccfg.getName()); putKeys(clnCache, EXPECTED_VALUE); try { // Explicit tx. for (int i = 0; i < ITERATION_CNT; i++) { try (final Transaction tx = cln.transactions().txStart(txConcurrency, txIsolation)) { putKeys(clnCache, WRONG_VALUE); clnCache.invoke(KEYS, new NonSerialazibleEntryProcessor()); GridTestUtils.assertThrowsWithCause(new Callable<Object>() { @Override public Object call() throws Exception { tx.commit(); return null; } }, NotSerializableException.class); } checkKeys(clnCache, EXPECTED_VALUE); } // From affinity node. Ignite grid = grid(ThreadLocalRandom.current().nextInt(NODES)); final IgniteCache cache = grid.cache(ccfg.getName()); // Explicit tx. for (int i = 0; i < ITERATION_CNT; i++) { try (final Transaction tx = grid.transactions().txStart(txConcurrency, txIsolation)) { putKeys(cache, WRONG_VALUE); cache.invoke(KEYS, new NonSerialazibleEntryProcessor()); GridTestUtils.assertThrowsWithCause(new Callable<Object>() { @Override public Object call() throws Exception { tx.commit(); return null; } }, NotSerializableException.class); } checkKeys(cache, EXPECTED_VALUE); } final IgniteCache clnCache0 = clnCache; // Implicit tx. for (int i = 0; i < ITERATION_CNT; i++) { GridTestUtils.assertThrowsWithCause(new Callable<Object>() { @Override public Object call() throws Exception { clnCache0.invoke(KEYS, new NonSerialazibleEntryProcessor()); return null; } }, NotSerializableException.class); } checkKeys(clnCache, EXPECTED_VALUE); } finally { grid(0).destroyCache(ccfg.getName()); } } /** * @param cache Cache. * @param val Value. */ private void putKeys(IgniteCache cache, int val) { cache.put(KEYS, val); } /** * @param cache Cache. * @param expVal Expected value. */ private void checkKeys(IgniteCache cache, int expVal) { assertEquals(expVal, cache.get(KEYS)); } /** * @return Cache configuration. */ private CacheConfiguration cacheConfiguration(CacheWriteSynchronizationMode wrMode, int backup) { return new CacheConfiguration("test-cache-" + wrMode + "-" + backup) .setAtomicityMode(TRANSACTIONAL) .setWriteSynchronizationMode(FULL_SYNC) .setBackups(backup); } /** * */ private static class NonSerialazibleEntryProcessor implements EntryProcessor<Integer, Integer, Integer> { /** {@inheritDoc} */ @Override public Integer process(MutableEntry<Integer, Integer> entry, Object... arguments) throws EntryProcessorException { entry.setValue(42); return null; } } }
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel; import io.netty.util.Recycler; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.PromiseCombiner; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; /** * A queue of write operations which are pending for later execution. It also updates the * {@linkplain Channel#isWritable() writability} of the associated {@link Channel}, so that * the pending write operations are also considered to determine the writability. */ public final class PendingWriteQueue { private static final InternalLogger logger = InternalLoggerFactory.getInstance(PendingWriteQueue.class); private final ChannelHandlerContext ctx; private final ChannelOutboundBuffer buffer; private final MessageSizeEstimator.Handle estimatorHandle; // head and tail pointers for the linked-list structure. If empty head and tail are null. private PendingWrite head; private PendingWrite tail; private int size; private long bytes; public PendingWriteQueue(ChannelHandlerContext ctx) { if (ctx == null) { throw new NullPointerException("ctx"); } this.ctx = ctx; buffer = ctx.channel().unsafe().outboundBuffer(); estimatorHandle = ctx.channel().config().getMessageSizeEstimator().newHandle(); } /** * Returns {@code true} if there are no pending write operations left in this queue. */ public boolean isEmpty() { assert ctx.executor().inEventLoop(); return head == null; } /** * Returns the number of pending write operations. */ public int size() { assert ctx.executor().inEventLoop(); return size; } /** * Returns the total number of bytes that are pending because of pending messages. This is only an estimate so * it should only be treated as a hint. */ public long bytes() { assert ctx.executor().inEventLoop(); return bytes; } /** * Add the given {@code msg} and {@link ChannelPromise}. */ public void add(Object msg, ChannelPromise promise) { assert ctx.executor().inEventLoop(); if (msg == null) { throw new NullPointerException("msg"); } if (promise == null) { throw new NullPointerException("promise"); } // It is possible for writes to be triggered from removeAndFailAll(). To preserve ordering, // we should add them to the queue and let removeAndFailAll() fail them later. int messageSize = estimatorHandle.size(msg); if (messageSize < 0) { // Size may be unknow so just use 0 messageSize = 0; } PendingWrite write = PendingWrite.newInstance(msg, messageSize, promise); PendingWrite currentTail = tail; if (currentTail == null) { tail = head = write; } else { currentTail.next = write; tail = write; } size ++; bytes += messageSize; // We need to guard against null as channel.unsafe().outboundBuffer() may returned null // if the channel was already closed when constructing the PendingWriteQueue. // See https://github.com/netty/netty/issues/3967 if (buffer != null) { buffer.incrementPendingOutboundBytes(write.size); } } /** * Remove all pending write operation and fail them with the given {@link Throwable}. The message will be released * via {@link ReferenceCountUtil#safeRelease(Object)}. */ public void removeAndFailAll(Throwable cause) { assert ctx.executor().inEventLoop(); if (cause == null) { throw new NullPointerException("cause"); } // It is possible for some of the failed promises to trigger more writes. The new writes // will "revive" the queue, so we need to clean them up until the queue is empty. for (PendingWrite write = head; write != null; write = head) { head = tail = null; size = 0; bytes = 0; while (write != null) { PendingWrite next = write.next; ReferenceCountUtil.safeRelease(write.msg); ChannelPromise promise = write.promise; recycle(write, false); safeFail(promise, cause); write = next; } } assertEmpty(); } /** * Remove a pending write operation and fail it with the given {@link Throwable}. The message will be released via * {@link ReferenceCountUtil#safeRelease(Object)}. */ public void removeAndFail(Throwable cause) { assert ctx.executor().inEventLoop(); if (cause == null) { throw new NullPointerException("cause"); } PendingWrite write = head; if (write == null) { return; } ReferenceCountUtil.safeRelease(write.msg); ChannelPromise promise = write.promise; safeFail(promise, cause); recycle(write, true); } /** * Remove all pending write operation and performs them via * {@link ChannelHandlerContext#write(Object, ChannelPromise)}. * * @return {@link ChannelFuture} if something was written and {@code null} * if the {@link PendingWriteQueue} is empty. */ public ChannelFuture removeAndWriteAll() { assert ctx.executor().inEventLoop(); if (size == 1) { // No need to use ChannelPromiseAggregator for this case. return removeAndWrite(); } PendingWrite write = head; if (write == null) { // empty so just return null return null; } // Guard against re-entrance by directly reset head = tail = null; size = 0; bytes = 0; ChannelPromise p = ctx.newPromise(); PromiseCombiner combiner = new PromiseCombiner(); try { while (write != null) { PendingWrite next = write.next; Object msg = write.msg; ChannelPromise promise = write.promise; recycle(write, false); combiner.add(promise); ctx.write(msg, promise); write = next; } assertEmpty(); combiner.finish(p); } catch (Throwable cause) { p.setFailure(cause); } return p; } private void assertEmpty() { assert tail == null && head == null && size == 0; } /** * Removes a pending write operation and performs it via * {@link ChannelHandlerContext#write(Object, ChannelPromise)}. * * @return {@link ChannelFuture} if something was written and {@code null} * if the {@link PendingWriteQueue} is empty. */ public ChannelFuture removeAndWrite() { assert ctx.executor().inEventLoop(); PendingWrite write = head; if (write == null) { return null; } Object msg = write.msg; ChannelPromise promise = write.promise; recycle(write, true); return ctx.write(msg, promise); } /** * Removes a pending write operation and release it's message via {@link ReferenceCountUtil#safeRelease(Object)}. * * @return {@link ChannelPromise} of the pending write or {@code null} if the queue is empty. * */ public ChannelPromise remove() { assert ctx.executor().inEventLoop(); PendingWrite write = head; if (write == null) { return null; } ChannelPromise promise = write.promise; ReferenceCountUtil.safeRelease(write.msg); recycle(write, true); return promise; } /** * Return the current message or {@code null} if empty. */ public Object current() { assert ctx.executor().inEventLoop(); PendingWrite write = head; if (write == null) { return null; } return write.msg; } private void recycle(PendingWrite write, boolean update) { final PendingWrite next = write.next; final long writeSize = write.size; if (update) { if (next == null) { // Handled last PendingWrite so rest head and tail // Guard against re-entrance by directly reset head = tail = null; size = 0; bytes = 0; } else { head = next; size --; bytes -= writeSize; assert size > 0 && bytes >= 0; } } write.recycle(); // We need to guard against null as channel.unsafe().outboundBuffer() may returned null // if the channel was already closed when constructing the PendingWriteQueue. // See https://github.com/netty/netty/issues/3967 if (buffer != null) { buffer.decrementPendingOutboundBytes(writeSize); } } private static void safeFail(ChannelPromise promise, Throwable cause) { if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); } } /** * Holds all meta-data and construct the linked-list structure. */ static final class PendingWrite { private static final Recycler<PendingWrite> RECYCLER = new Recycler<PendingWrite>() { @Override protected PendingWrite newObject(Handle<PendingWrite> handle) { return new PendingWrite(handle); } }; private final Recycler.Handle<PendingWrite> handle; private PendingWrite next; private long size; private ChannelPromise promise; private Object msg; private PendingWrite(Recycler.Handle<PendingWrite> handle) { this.handle = handle; } static PendingWrite newInstance(Object msg, int size, ChannelPromise promise) { PendingWrite write = RECYCLER.get(); write.size = size; write.msg = msg; write.promise = promise; return write; } private void recycle() { size = 0; next = null; msg = null; promise = null; handle.recycle(this); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.impl.plan.OperatorKey; import org.apache.pig.impl.plan.VisitorException; import org.apache.pig.pen.Illustrator; /** * A base class for all types of expressions. All expression * operators must extend this class. * */ public abstract class ExpressionOperator extends PhysicalOperator { private static final Log log = LogFactory.getLog(ExpressionOperator.class); private static final long serialVersionUID = 1L; public ExpressionOperator(OperatorKey k) { this(k,-1); } public ExpressionOperator(OperatorKey k, int rp) { super(k, rp); } @Override public void setIllustrator(Illustrator illustrator) { this.illustrator = illustrator; } @Override public boolean supportsMultipleOutputs() { return false; } @Override public Result getNext(DataBag db) throws ExecException { return new Result(); } @Override public abstract void visit(PhyPlanVisitor v) throws VisitorException; /** * Make a deep copy of this operator. This is declared here to make it * possible to call clone on ExpressionOperators. * @throws CloneNotSupportedException */ @Override public ExpressionOperator clone() throws CloneNotSupportedException { String s = "This expression operator does not implement clone."; log.error(s); throw new CloneNotSupportedException(s); } /** * Get the sub-expressions of this expression. * This is called if reducer is run as accumulative mode, all the child * expression must be called if they have any UDF to drive the UDF.accumulate() */ protected abstract List<ExpressionOperator> getChildExpressions(); /** check whether this expression contains any UDF * this is called if reducer is run as accumulative mode * in this case, all UDFs must be called */ public boolean containUDF() { if (this instanceof POUserFunc) { return true; } List<ExpressionOperator> l = getChildExpressions(); if (l != null) { for(ExpressionOperator e: l) { if (e.containUDF()) { return true; } } } return false; } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Object o, byte dataType) throws ExecException { if (isAccumStarted()) { if (child == null) { child = getChildExpressions(); } Result res = null; if (child != null) { for(ExpressionOperator e: child) { if (e.containUDF()) { res = e.getNext(o, dataType); if (res.returnStatus != POStatus.STATUS_BATCH_OK) { return res; } } } } res = new Result(); res.returnStatus = POStatus.STATUS_BATCH_OK; return res; } return null; } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Double d) throws ExecException { return accumChild(child, d, DataType.DOUBLE); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Integer v) throws ExecException { return accumChild(child, v, DataType.INTEGER); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Long l) throws ExecException { return accumChild(child, l, DataType.LONG); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Float f) throws ExecException { return accumChild(child, f, DataType.FLOAT); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Boolean b) throws ExecException { return accumChild(child, b, DataType.BOOLEAN); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, DateTime dt) throws ExecException { return accumChild(child, dt, DataType.DATETIME); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, String s) throws ExecException { return accumChild(child, s, DataType.CHARARRAY); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, DataByteArray dba) throws ExecException { return accumChild(child, dba, DataType.BYTEARRAY); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Map map) throws ExecException { return accumChild(child, map, DataType.MAP); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, Tuple t) throws ExecException { return accumChild(child, t, DataType.TUPLE); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, DataBag db) throws ExecException { return accumChild(child, db, DataType.BAG); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, BigInteger bi) throws ExecException { return accumChild(child, bi, DataType.BIGINTEGER); } /** * Drive all the UDFs in accumulative mode */ protected Result accumChild(List<ExpressionOperator> child, BigDecimal bd) throws ExecException { return accumChild(child, bd, DataType.BIGDECIMAL); } @Override public String toString() { return "[" + this.getClass().getSimpleName() + " " + super.toString() + " children: " + getChildExpressions() + " at " + getOriginalLocations() + "]"; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.metrics; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import com.google.common.collect.Maps; import com.codahale.metrics.*; import com.codahale.metrics.Timer; import org.apache.cassandra.config.Schema; import org.apache.cassandra.config.SchemaConstants; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.Keyspace; import org.apache.cassandra.db.Memtable; import org.apache.cassandra.db.lifecycle.SSTableSet; import org.apache.cassandra.index.SecondaryIndexManager; import org.apache.cassandra.io.compress.CompressionMetadata; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.sstable.metadata.MetadataCollector; import org.apache.cassandra.utils.EstimatedHistogram; import org.apache.cassandra.utils.TopKSampler; import static org.apache.cassandra.metrics.CassandraMetricsRegistry.Metrics; /** * Metrics for {@link ColumnFamilyStore}. */ public class TableMetrics { public static final long[] EMPTY = new long[0]; /** Total amount of data stored in the memtable that resides on-heap, including column related overhead and partitions overwritten. */ public final Gauge<Long> memtableOnHeapSize; /** Total amount of data stored in the memtable that resides off-heap, including column related overhead and partitions overwritten. */ public final Gauge<Long> memtableOffHeapSize; /** Total amount of live data stored in the memtable, excluding any data structure overhead */ public final Gauge<Long> memtableLiveDataSize; /** Total amount of data stored in the memtables (2i and pending flush memtables included) that resides on-heap. */ public final Gauge<Long> allMemtablesOnHeapSize; /** Total amount of data stored in the memtables (2i and pending flush memtables included) that resides off-heap. */ public final Gauge<Long> allMemtablesOffHeapSize; /** Total amount of live data stored in the memtables (2i and pending flush memtables included) that resides off-heap, excluding any data structure overhead */ public final Gauge<Long> allMemtablesLiveDataSize; /** Total number of columns present in the memtable. */ public final Gauge<Long> memtableColumnsCount; /** Number of times flush has resulted in the memtable being switched out. */ public final Counter memtableSwitchCount; /** Current compression ratio for all SSTables */ public final Gauge<Double> compressionRatio; /** Histogram of estimated partition size (in bytes). */ public final Gauge<long[]> estimatedPartitionSizeHistogram; /** Approximate number of keys in table. */ public final Gauge<Long> estimatedPartitionCount; /** Histogram of estimated number of columns. */ public final Gauge<long[]> estimatedColumnCountHistogram; /** Histogram of the number of sstable data files accessed per read */ public final TableHistogram sstablesPerReadHistogram; /** (Local) read metrics */ public final LatencyMetrics readLatency; /** (Local) range slice metrics */ public final LatencyMetrics rangeLatency; /** (Local) write metrics */ public final LatencyMetrics writeLatency; /** Estimated number of tasks pending for this table */ public final Counter pendingFlushes; /** Total number of bytes flushed since server [re]start */ public final Counter bytesFlushed; /** Total number of bytes written by compaction since server [re]start */ public final Counter compactionBytesWritten; /** Estimate of number of pending compactios for this table */ public final Gauge<Integer> pendingCompactions; /** Number of SSTables on disk for this CF */ public final Gauge<Integer> liveSSTableCount; /** Disk space used by SSTables belonging to this table */ public final Counter liveDiskSpaceUsed; /** Total disk space used by SSTables belonging to this table, including obsolete ones waiting to be GC'd */ public final Counter totalDiskSpaceUsed; /** Size of the smallest compacted partition */ public final Gauge<Long> minPartitionSize; /** Size of the largest compacted partition */ public final Gauge<Long> maxPartitionSize; /** Size of the smallest compacted partition */ public final Gauge<Long> meanPartitionSize; /** Number of false positives in bloom filter */ public final Gauge<Long> bloomFilterFalsePositives; /** Number of false positives in bloom filter from last read */ public final Gauge<Long> recentBloomFilterFalsePositives; /** False positive ratio of bloom filter */ public final Gauge<Double> bloomFilterFalseRatio; /** False positive ratio of bloom filter from last read */ public final Gauge<Double> recentBloomFilterFalseRatio; /** Disk space used by bloom filter */ public final Gauge<Long> bloomFilterDiskSpaceUsed; /** Off heap memory used by bloom filter */ public final Gauge<Long> bloomFilterOffHeapMemoryUsed; /** Off heap memory used by index summary */ public final Gauge<Long> indexSummaryOffHeapMemoryUsed; /** Off heap memory used by compression meta data*/ public final Gauge<Long> compressionMetadataOffHeapMemoryUsed; /** Key cache hit rate for this CF */ public final Gauge<Double> keyCacheHitRate; /** Tombstones scanned in queries on this CF */ public final TableHistogram tombstoneScannedHistogram; /** Live cells scanned in queries on this CF */ public final TableHistogram liveScannedHistogram; /** Column update time delta on this CF */ public final TableHistogram colUpdateTimeDeltaHistogram; /** time taken acquiring the partition lock for materialized view updates for this table */ public final TableTimer viewLockAcquireTime; /** time taken during the local read of a materialized view update */ public final TableTimer viewReadTime; /** Disk space used by snapshot files which */ public final Gauge<Long> trueSnapshotsSize; /** Row cache hits, but result out of range */ public final Counter rowCacheHitOutOfRange; /** Number of row cache hits */ public final Counter rowCacheHit; /** Number of row cache misses */ public final Counter rowCacheMiss; /** CAS Prepare metrics */ public final LatencyMetrics casPrepare; /** CAS Propose metrics */ public final LatencyMetrics casPropose; /** CAS Commit metrics */ public final LatencyMetrics casCommit; /** percent of the data that is repaired */ public final Gauge<Double> percentRepaired; public final Timer coordinatorReadLatency; public final Timer coordinatorScanLatency; /** Time spent waiting for free memtable space, either on- or off-heap */ public final Histogram waitingOnFreeMemtableSpace; /** Dropped Mutations Count */ public final Counter droppedMutations; private final MetricNameFactory factory; private final MetricNameFactory aliasFactory; private static final MetricNameFactory globalFactory = new AllTableMetricNameFactory("Table"); private static final MetricNameFactory globalAliasFactory = new AllTableMetricNameFactory("ColumnFamily"); public final Counter speculativeRetries; public final static LatencyMetrics globalReadLatency = new LatencyMetrics(globalFactory, globalAliasFactory, "Read"); public final static LatencyMetrics globalWriteLatency = new LatencyMetrics(globalFactory, globalAliasFactory, "Write"); public final static LatencyMetrics globalRangeLatency = new LatencyMetrics(globalFactory, globalAliasFactory, "Range"); public final static Gauge<Double> globalPercentRepaired = Metrics.register(globalFactory.createMetricName("PercentRepaired"), new Gauge<Double>() { public Double getValue() { double repaired = 0; double total = 0; for (String keyspace : Schema.instance.getNonSystemKeyspaces()) { Keyspace k = Schema.instance.getKeyspaceInstance(keyspace); if (SchemaConstants.DISTRIBUTED_KEYSPACE_NAME.equals(k.getName())) continue; if (k.getReplicationStrategy().getReplicationFactor() < 2) continue; for (ColumnFamilyStore cf : k.getColumnFamilyStores()) { if (!SecondaryIndexManager.isIndexColumnFamily(cf.name)) { for (SSTableReader sstable : cf.getSSTables(SSTableSet.CANONICAL)) { if (sstable.isRepaired()) { repaired += sstable.uncompressedLength(); } total += sstable.uncompressedLength(); } } } } return total > 0 ? (repaired / total) * 100 : 100.0; } }); public final Map<Sampler, TopKSampler<ByteBuffer>> samplers; /** * stores metrics that will be rolled into a single global metric */ public final static ConcurrentMap<String, Set<Metric>> allTableMetrics = Maps.newConcurrentMap(); /** * Stores all metric names created that can be used when unregistering, optionally mapped to an alias name. */ public final static Map<String, String> all = Maps.newHashMap(); private interface GetHistogram { EstimatedHistogram getHistogram(SSTableReader reader); } private static long[] combineHistograms(Iterable<SSTableReader> sstables, GetHistogram getHistogram) { Iterator<SSTableReader> iterator = sstables.iterator(); if (!iterator.hasNext()) { return EMPTY; } long[] firstBucket = getHistogram.getHistogram(iterator.next()).getBuckets(false); long[] values = new long[firstBucket.length]; System.arraycopy(firstBucket, 0, values, 0, values.length); while (iterator.hasNext()) { long[] nextBucket = getHistogram.getHistogram(iterator.next()).getBuckets(false); if (nextBucket.length > values.length) { long[] newValues = new long[nextBucket.length]; System.arraycopy(firstBucket, 0, newValues, 0, firstBucket.length); for (int i = 0; i < newValues.length; i++) { newValues[i] += nextBucket[i]; } values = newValues; } else { for (int i = 0; i < values.length; i++) { values[i] += nextBucket[i]; } } } return values; } /** * Creates metrics for given {@link ColumnFamilyStore}. * * @param cfs ColumnFamilyStore to measure metrics */ public TableMetrics(final ColumnFamilyStore cfs) { factory = new TableMetricNameFactory(cfs, "Table"); aliasFactory = new TableMetricNameFactory(cfs, "ColumnFamily"); samplers = Maps.newHashMap(); for (Sampler sampler : Sampler.values()) { samplers.put(sampler, new TopKSampler<>()); } memtableColumnsCount = createTableGauge("MemtableColumnsCount", new Gauge<Long>() { public Long getValue() { return cfs.getTracker().getView().getCurrentMemtable().getOperations(); } }); memtableOnHeapSize = createTableGauge("MemtableOnHeapSize", new Gauge<Long>() { public Long getValue() { return cfs.getTracker().getView().getCurrentMemtable().getAllocator().onHeap().owns(); } }); memtableOffHeapSize = createTableGauge("MemtableOffHeapSize", new Gauge<Long>() { public Long getValue() { return cfs.getTracker().getView().getCurrentMemtable().getAllocator().offHeap().owns(); } }); memtableLiveDataSize = createTableGauge("MemtableLiveDataSize", new Gauge<Long>() { public Long getValue() { return cfs.getTracker().getView().getCurrentMemtable().getLiveDataSize(); } }); allMemtablesOnHeapSize = createTableGauge("AllMemtablesHeapSize", new Gauge<Long>() { public Long getValue() { long size = 0; for (ColumnFamilyStore cfs2 : cfs.concatWithIndexes()) size += cfs2.getTracker().getView().getCurrentMemtable().getAllocator().onHeap().owns(); return size; } }); allMemtablesOffHeapSize = createTableGauge("AllMemtablesOffHeapSize", new Gauge<Long>() { public Long getValue() { long size = 0; for (ColumnFamilyStore cfs2 : cfs.concatWithIndexes()) size += cfs2.getTracker().getView().getCurrentMemtable().getAllocator().offHeap().owns(); return size; } }); allMemtablesLiveDataSize = createTableGauge("AllMemtablesLiveDataSize", new Gauge<Long>() { public Long getValue() { long size = 0; for (ColumnFamilyStore cfs2 : cfs.concatWithIndexes()) size += cfs2.getTracker().getView().getCurrentMemtable().getLiveDataSize(); return size; } }); memtableSwitchCount = createTableCounter("MemtableSwitchCount"); estimatedPartitionSizeHistogram = Metrics.register(factory.createMetricName("EstimatedPartitionSizeHistogram"), aliasFactory.createMetricName("EstimatedRowSizeHistogram"), new Gauge<long[]>() { public long[] getValue() { return combineHistograms(cfs.getSSTables(SSTableSet.CANONICAL), new GetHistogram() { public EstimatedHistogram getHistogram(SSTableReader reader) { return reader.getEstimatedPartitionSize(); } }); } }); estimatedPartitionCount = Metrics.register(factory.createMetricName("EstimatedPartitionCount"), aliasFactory.createMetricName("EstimatedRowCount"), new Gauge<Long>() { public Long getValue() { long memtablePartitions = 0; for (Memtable memtable : cfs.getTracker().getView().getAllMemtables()) memtablePartitions += memtable.partitionCount(); return SSTableReader.getApproximateKeyCount(cfs.getSSTables(SSTableSet.CANONICAL)) + memtablePartitions; } }); estimatedColumnCountHistogram = Metrics.register(factory.createMetricName("EstimatedColumnCountHistogram"), aliasFactory.createMetricName("EstimatedColumnCountHistogram"), new Gauge<long[]>() { public long[] getValue() { return combineHistograms(cfs.getSSTables(SSTableSet.CANONICAL), new GetHistogram() { public EstimatedHistogram getHistogram(SSTableReader reader) { return reader.getEstimatedColumnCount(); } }); } }); sstablesPerReadHistogram = createTableHistogram("SSTablesPerReadHistogram", cfs.keyspace.metric.sstablesPerReadHistogram, true); compressionRatio = createTableGauge("CompressionRatio", new Gauge<Double>() { public Double getValue() { return computeCompressionRatio(cfs.getSSTables(SSTableSet.CANONICAL)); } }, new Gauge<Double>() // global gauge { public Double getValue() { List<SSTableReader> sstables = new ArrayList<>(); Keyspace.all().forEach(ks -> sstables.addAll(ks.getAllSSTables(SSTableSet.CANONICAL))); return computeCompressionRatio(sstables); } }); percentRepaired = createTableGauge("PercentRepaired", new Gauge<Double>() { public Double getValue() { double repaired = 0; double total = 0; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.CANONICAL)) { if (sstable.isRepaired()) { repaired += sstable.uncompressedLength(); } total += sstable.uncompressedLength(); } return total > 0 ? (repaired / total) * 100 : 100.0; } }); readLatency = new LatencyMetrics(factory, "Read", cfs.keyspace.metric.readLatency, globalReadLatency); writeLatency = new LatencyMetrics(factory, "Write", cfs.keyspace.metric.writeLatency, globalWriteLatency); rangeLatency = new LatencyMetrics(factory, "Range", cfs.keyspace.metric.rangeLatency, globalRangeLatency); pendingFlushes = createTableCounter("PendingFlushes"); bytesFlushed = createTableCounter("BytesFlushed"); compactionBytesWritten = createTableCounter("CompactionBytesWritten"); pendingCompactions = createTableGauge("PendingCompactions", new Gauge<Integer>() { public Integer getValue() { return cfs.getCompactionStrategyManager().getEstimatedRemainingTasks(); } }); liveSSTableCount = createTableGauge("LiveSSTableCount", new Gauge<Integer>() { public Integer getValue() { return cfs.getTracker().getView().liveSSTables().size(); } }); liveDiskSpaceUsed = createTableCounter("LiveDiskSpaceUsed"); totalDiskSpaceUsed = createTableCounter("TotalDiskSpaceUsed"); minPartitionSize = createTableGauge("MinPartitionSize", "MinRowSize", new Gauge<Long>() { public Long getValue() { long min = 0; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.CANONICAL)) { if (min == 0 || sstable.getEstimatedPartitionSize().min() < min) min = sstable.getEstimatedPartitionSize().min(); } return min; } }, new Gauge<Long>() // global gauge { public Long getValue() { long min = Long.MAX_VALUE; for (Metric cfGauge : allTableMetrics.get("MinPartitionSize")) { min = Math.min(min, ((Gauge<? extends Number>) cfGauge).getValue().longValue()); } return min; } }); maxPartitionSize = createTableGauge("MaxPartitionSize", "MaxRowSize", new Gauge<Long>() { public Long getValue() { long max = 0; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.CANONICAL)) { if (sstable.getEstimatedPartitionSize().max() > max) max = sstable.getEstimatedPartitionSize().max(); } return max; } }, new Gauge<Long>() // global gauge { public Long getValue() { long max = 0; for (Metric cfGauge : allTableMetrics.get("MaxPartitionSize")) { max = Math.max(max, ((Gauge<? extends Number>) cfGauge).getValue().longValue()); } return max; } }); meanPartitionSize = createTableGauge("MeanPartitionSize", "MeanRowSize", new Gauge<Long>() { public Long getValue() { long sum = 0; long count = 0; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.CANONICAL)) { long n = sstable.getEstimatedPartitionSize().count(); sum += sstable.getEstimatedPartitionSize().mean() * n; count += n; } return count > 0 ? sum / count : 0; } }, new Gauge<Long>() // global gauge { public Long getValue() { long sum = 0; long count = 0; for (Keyspace keyspace : Keyspace.all()) { for (SSTableReader sstable : keyspace.getAllSSTables(SSTableSet.CANONICAL)) { long n = sstable.getEstimatedPartitionSize().count(); sum += sstable.getEstimatedPartitionSize().mean() * n; count += n; } } return count > 0 ? sum / count : 0; } }); bloomFilterFalsePositives = createTableGauge("BloomFilterFalsePositives", new Gauge<Long>() { public Long getValue() { long count = 0L; for (SSTableReader sstable: cfs.getSSTables(SSTableSet.LIVE)) count += sstable.getBloomFilterFalsePositiveCount(); return count; } }); recentBloomFilterFalsePositives = createTableGauge("RecentBloomFilterFalsePositives", new Gauge<Long>() { public Long getValue() { long count = 0L; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.LIVE)) count += sstable.getRecentBloomFilterFalsePositiveCount(); return count; } }); bloomFilterFalseRatio = createTableGauge("BloomFilterFalseRatio", new Gauge<Double>() { public Double getValue() { long falseCount = 0L; long trueCount = 0L; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.LIVE)) { falseCount += sstable.getBloomFilterFalsePositiveCount(); trueCount += sstable.getBloomFilterTruePositiveCount(); } if (falseCount == 0L && trueCount == 0L) return 0d; return (double) falseCount / (trueCount + falseCount); } }, new Gauge<Double>() // global gauge { public Double getValue() { long falseCount = 0L; long trueCount = 0L; for (Keyspace keyspace : Keyspace.all()) { for (SSTableReader sstable : keyspace.getAllSSTables(SSTableSet.LIVE)) { falseCount += sstable.getBloomFilterFalsePositiveCount(); trueCount += sstable.getBloomFilterTruePositiveCount(); } } if (falseCount == 0L && trueCount == 0L) return 0d; return (double) falseCount / (trueCount + falseCount); } }); recentBloomFilterFalseRatio = createTableGauge("RecentBloomFilterFalseRatio", new Gauge<Double>() { public Double getValue() { long falseCount = 0L; long trueCount = 0L; for (SSTableReader sstable: cfs.getSSTables(SSTableSet.LIVE)) { falseCount += sstable.getRecentBloomFilterFalsePositiveCount(); trueCount += sstable.getRecentBloomFilterTruePositiveCount(); } if (falseCount == 0L && trueCount == 0L) return 0d; return (double) falseCount / (trueCount + falseCount); } }, new Gauge<Double>() // global gauge { public Double getValue() { long falseCount = 0L; long trueCount = 0L; for (Keyspace keyspace : Keyspace.all()) { for (SSTableReader sstable : keyspace.getAllSSTables(SSTableSet.LIVE)) { falseCount += sstable.getRecentBloomFilterFalsePositiveCount(); trueCount += sstable.getRecentBloomFilterTruePositiveCount(); } } if (falseCount == 0L && trueCount == 0L) return 0d; return (double) falseCount / (trueCount + falseCount); } }); bloomFilterDiskSpaceUsed = createTableGauge("BloomFilterDiskSpaceUsed", new Gauge<Long>() { public Long getValue() { long total = 0; for (SSTableReader sst : cfs.getSSTables(SSTableSet.CANONICAL)) total += sst.getBloomFilterSerializedSize(); return total; } }); bloomFilterOffHeapMemoryUsed = createTableGauge("BloomFilterOffHeapMemoryUsed", new Gauge<Long>() { public Long getValue() { long total = 0; for (SSTableReader sst : cfs.getSSTables(SSTableSet.LIVE)) total += sst.getBloomFilterOffHeapSize(); return total; } }); indexSummaryOffHeapMemoryUsed = createTableGauge("IndexSummaryOffHeapMemoryUsed", new Gauge<Long>() { public Long getValue() { long total = 0; for (SSTableReader sst : cfs.getSSTables(SSTableSet.LIVE)) total += sst.getIndexSummaryOffHeapSize(); return total; } }); compressionMetadataOffHeapMemoryUsed = createTableGauge("CompressionMetadataOffHeapMemoryUsed", new Gauge<Long>() { public Long getValue() { long total = 0; for (SSTableReader sst : cfs.getSSTables(SSTableSet.LIVE)) total += sst.getCompressionMetadataOffHeapSize(); return total; } }); speculativeRetries = createTableCounter("SpeculativeRetries"); keyCacheHitRate = Metrics.register(factory.createMetricName("KeyCacheHitRate"), aliasFactory.createMetricName("KeyCacheHitRate"), new RatioGauge() { @Override public Ratio getRatio() { return Ratio.of(getNumerator(), getDenominator()); } protected double getNumerator() { long hits = 0L; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.LIVE)) hits += sstable.getKeyCacheHit(); return hits; } protected double getDenominator() { long requests = 0L; for (SSTableReader sstable : cfs.getSSTables(SSTableSet.LIVE)) requests += sstable.getKeyCacheRequest(); return Math.max(requests, 1); // to avoid NaN. } }); tombstoneScannedHistogram = createTableHistogram("TombstoneScannedHistogram", cfs.keyspace.metric.tombstoneScannedHistogram, false); liveScannedHistogram = createTableHistogram("LiveScannedHistogram", cfs.keyspace.metric.liveScannedHistogram, false); colUpdateTimeDeltaHistogram = createTableHistogram("ColUpdateTimeDeltaHistogram", cfs.keyspace.metric.colUpdateTimeDeltaHistogram, false); coordinatorReadLatency = Metrics.timer(factory.createMetricName("CoordinatorReadLatency")); coordinatorScanLatency = Metrics.timer(factory.createMetricName("CoordinatorScanLatency")); waitingOnFreeMemtableSpace = Metrics.histogram(factory.createMetricName("WaitingOnFreeMemtableSpace"), false); // We do not want to capture view mutation specific metrics for a view // They only makes sense to capture on the base table if (cfs.metadata.isView()) { viewLockAcquireTime = null; viewReadTime = null; } else { viewLockAcquireTime = createTableTimer("ViewLockAcquireTime", cfs.keyspace.metric.viewLockAcquireTime); viewReadTime = createTableTimer("ViewReadTime", cfs.keyspace.metric.viewReadTime); } trueSnapshotsSize = createTableGauge("SnapshotsSize", new Gauge<Long>() { public Long getValue() { return cfs.trueSnapshotsSize(); } }); rowCacheHitOutOfRange = createTableCounter("RowCacheHitOutOfRange"); rowCacheHit = createTableCounter("RowCacheHit"); rowCacheMiss = createTableCounter("RowCacheMiss"); droppedMutations = createTableCounter("DroppedMutations"); casPrepare = new LatencyMetrics(factory, "CasPrepare", cfs.keyspace.metric.casPrepare); casPropose = new LatencyMetrics(factory, "CasPropose", cfs.keyspace.metric.casPropose); casCommit = new LatencyMetrics(factory, "CasCommit", cfs.keyspace.metric.casCommit); } public void updateSSTableIterated(int count) { sstablesPerReadHistogram.update(count); } /** * Release all associated metrics. */ public void release() { for(Map.Entry<String, String> entry : all.entrySet()) { CassandraMetricsRegistry.MetricName name = factory.createMetricName(entry.getKey()); CassandraMetricsRegistry.MetricName alias = aliasFactory.createMetricName(entry.getValue()); allTableMetrics.get(entry.getKey()).remove(Metrics.getMetrics().get(name.getMetricName())); Metrics.remove(name, alias); } readLatency.release(); writeLatency.release(); rangeLatency.release(); Metrics.remove(factory.createMetricName("EstimatedPartitionSizeHistogram"), aliasFactory.createMetricName("EstimatedRowSizeHistogram")); Metrics.remove(factory.createMetricName("EstimatedPartitionCount"), aliasFactory.createMetricName("EstimatedRowCount")); Metrics.remove(factory.createMetricName("EstimatedColumnCountHistogram"), aliasFactory.createMetricName("EstimatedColumnCountHistogram")); Metrics.remove(factory.createMetricName("KeyCacheHitRate"), aliasFactory.createMetricName("KeyCacheHitRate")); Metrics.remove(factory.createMetricName("CoordinatorReadLatency"), aliasFactory.createMetricName("CoordinatorReadLatency")); Metrics.remove(factory.createMetricName("CoordinatorScanLatency"), aliasFactory.createMetricName("CoordinatorScanLatency")); Metrics.remove(factory.createMetricName("WaitingOnFreeMemtableSpace"), aliasFactory.createMetricName("WaitingOnFreeMemtableSpace")); } /** * Create a gauge that will be part of a merged version of all column families. The global gauge * will merge each CF gauge by adding their values */ protected <T extends Number> Gauge<T> createTableGauge(final String name, Gauge<T> gauge) { return createTableGauge(name, gauge, new Gauge<Long>() { public Long getValue() { long total = 0; for (Metric cfGauge : allTableMetrics.get(name)) { total = total + ((Gauge<? extends Number>) cfGauge).getValue().longValue(); } return total; } }); } /** * Create a gauge that will be part of a merged version of all column families. The global gauge * is defined as the globalGauge parameter */ protected <G,T> Gauge<T> createTableGauge(String name, Gauge<T> gauge, Gauge<G> globalGauge) { return createTableGauge(name, name, gauge, globalGauge); } protected <G,T> Gauge<T> createTableGauge(String name, String alias, Gauge<T> gauge, Gauge<G> globalGauge) { Gauge<T> cfGauge = Metrics.register(factory.createMetricName(name), aliasFactory.createMetricName(alias), gauge); if (register(name, alias, cfGauge)) { Metrics.register(globalFactory.createMetricName(name), globalAliasFactory.createMetricName(alias), globalGauge); } return cfGauge; } /** * Creates a counter that will also have a global counter thats the sum of all counters across * different column families */ protected Counter createTableCounter(final String name) { return createTableCounter(name, name); } protected Counter createTableCounter(final String name, final String alias) { Counter cfCounter = Metrics.counter(factory.createMetricName(name), aliasFactory.createMetricName(alias)); if (register(name, alias, cfCounter)) { Metrics.register(globalFactory.createMetricName(name), globalAliasFactory.createMetricName(alias), new Gauge<Long>() { public Long getValue() { long total = 0; for (Metric cfGauge : allTableMetrics.get(name)) { total += ((Counter) cfGauge).getCount(); } return total; } }); } return cfCounter; } /** * Computes the compression ratio for the specified SSTables * * @param sstables the SSTables * @return the compression ratio for the specified SSTables */ private static Double computeCompressionRatio(Iterable<SSTableReader> sstables) { double compressedLengthSum = 0; double dataLengthSum = 0; for (SSTableReader sstable : sstables) { if (sstable.compression) { // We should not have any sstable which are in an open early mode as the sstable were selected // using SSTableSet.CANONICAL. assert sstable.openReason != SSTableReader.OpenReason.EARLY; CompressionMetadata compressionMetadata = sstable.getCompressionMetadata(); compressedLengthSum += compressionMetadata.compressedFileLength; dataLengthSum += compressionMetadata.dataLength; } } return dataLengthSum != 0 ? compressedLengthSum / dataLengthSum : MetadataCollector.NO_COMPRESSION_RATIO; } /** * Create a histogram-like interface that will register both a CF, keyspace and global level * histogram and forward any updates to both */ protected TableHistogram createTableHistogram(String name, Histogram keyspaceHistogram, boolean considerZeroes) { return createTableHistogram(name, name, keyspaceHistogram, considerZeroes); } protected TableHistogram createTableHistogram(String name, String alias, Histogram keyspaceHistogram, boolean considerZeroes) { Histogram cfHistogram = Metrics.histogram(factory.createMetricName(name), aliasFactory.createMetricName(alias), considerZeroes); register(name, alias, cfHistogram); return new TableHistogram(cfHistogram, keyspaceHistogram, Metrics.histogram(globalFactory.createMetricName(name), globalAliasFactory.createMetricName(alias), considerZeroes)); } protected TableTimer createTableTimer(String name, Timer keyspaceTimer) { return createTableTimer(name, name, keyspaceTimer); } protected TableTimer createTableTimer(String name, String alias, Timer keyspaceTimer) { Timer cfTimer = Metrics.timer(factory.createMetricName(name), aliasFactory.createMetricName(alias)); register(name, alias, cfTimer); return new TableTimer(cfTimer, keyspaceTimer, Metrics.timer(globalFactory.createMetricName(name), globalAliasFactory.createMetricName(alias))); } /** * Registers a metric to be removed when unloading CF. * @return true if first time metric with that name has been registered */ private boolean register(String name, String alias, Metric metric) { boolean ret = allTableMetrics.putIfAbsent(name, ConcurrentHashMap.newKeySet()) == null; allTableMetrics.get(name).add(metric); all.put(name, alias); return ret; } public static class TableHistogram { public final Histogram[] all; public final Histogram cf; private TableHistogram(Histogram cf, Histogram keyspace, Histogram global) { this.cf = cf; this.all = new Histogram[]{cf, keyspace, global}; } public void update(long i) { for(Histogram histo : all) { histo.update(i); } } } public static class TableTimer { public final Timer[] all; public final Timer cf; private TableTimer(Timer cf, Timer keyspace, Timer global) { this.cf = cf; this.all = new Timer[]{cf, keyspace, global}; } public void update(long i, TimeUnit unit) { for(Timer timer : all) { timer.update(i, unit); } } } static class TableMetricNameFactory implements MetricNameFactory { private final String keyspaceName; private final String tableName; private final boolean isIndex; private final String type; TableMetricNameFactory(ColumnFamilyStore cfs, String type) { this.keyspaceName = cfs.keyspace.getName(); this.tableName = cfs.name; this.isIndex = cfs.isIndex(); this.type = type; } public CassandraMetricsRegistry.MetricName createMetricName(String metricName) { String groupName = TableMetrics.class.getPackage().getName(); String type = isIndex ? "Index" + this.type : this.type; StringBuilder mbeanName = new StringBuilder(); mbeanName.append(groupName).append(":"); mbeanName.append("type=").append(type); mbeanName.append(",keyspace=").append(keyspaceName); mbeanName.append(",scope=").append(tableName); mbeanName.append(",name=").append(metricName); return new CassandraMetricsRegistry.MetricName(groupName, type, metricName, keyspaceName + "." + tableName, mbeanName.toString()); } } static class AllTableMetricNameFactory implements MetricNameFactory { private final String type; public AllTableMetricNameFactory(String type) { this.type = type; } public CassandraMetricsRegistry.MetricName createMetricName(String metricName) { String groupName = TableMetrics.class.getPackage().getName(); StringBuilder mbeanName = new StringBuilder(); mbeanName.append(groupName).append(":"); mbeanName.append("type=").append(type); mbeanName.append(",name=").append(metricName); return new CassandraMetricsRegistry.MetricName(groupName, type, metricName, "all", mbeanName.toString()); } } public enum Sampler { READS, WRITES } }
package main.subtitle.util; import java.util.ArrayList; import java.util.List; import java.util.Set; import main.util.regex.RegexEnum; import main.util.regex.RegexUtil; /** * Subtitle utilities. * * @author budi */ public class SubtitleUtil { /** * Get most balanced line out of list of {@link StringBuilder}. * * @param list list of {@link StringBuilder} containing lines. * @return most balanced line. */ public static StringBuilder mostBalanced(List<StringBuilder> list) { StringBuilder balanced = null; int bestDifference = Integer.MAX_VALUE; for (StringBuilder builder : list) { String[] split = RegexUtil.split(RegexEnum.NEWLINE, builder.toString()); if (split.length == 2) { int difference = Math.abs(split[0].length() - split[1].length()); if (difference < bestDifference) { balanced = builder; bestDifference = difference; } } } return balanced; } /** * Determines if sentence contains at least one word in the set. * * @param sentence sentence to check * @param words set of words to check for * @return True if sentence contains at least one word in the set, otherwise * false. */ public static boolean sentenceContainsWords(String sentence, Set<String> words) { sentence = sentence.toLowerCase(); for (String word : words) { word = word.toLowerCase(); if (sentence.contains(word)) { String[] split = sentence.replace('\n', ' ').split(" "); for (String sentenceWord : split) { if (sentenceWord.equals(word)) { return true; } } split = sentence.replaceAll("\\p{P}", " ").split(" "); for (String sentenceWord : split) { if (sentenceWord.equals(word)) { return true; } } } } return false; } /** * Split sentence into two most balanced lines. * * @param line line to balance * @param delimiter split by delimiter if possible * @return most balanced @{link StringBuilder} */ public static StringBuilder splitClosestToMiddle(String line, char delimiter) { if (line == null || line.isEmpty()) { return null; } StringBuilder builder = new StringBuilder(); int indexClosestToMiddle = -1; int index = 0; int midIndex = line.length() / 2; line = line.replace("\n", " ").trim(); for (char c : line.toCharArray()) { ++index; if (c == delimiter) { if (indexClosestToMiddle == -1 || (Math.abs(index - midIndex) < Math.abs(indexClosestToMiddle - midIndex))) { indexClosestToMiddle = index; } } } builder.append(line.substring(0, indexClosestToMiddle).trim()); builder.append('\n'); builder.append(line.substring(indexClosestToMiddle, line.length()).trim()); return builder; } /** * Get list of most balanced strings split by regex. * * @param line line to balance * @param regex regex to split by * @return list of {@link StringBuilder} of most balanced strings */ public static List<StringBuilder> balanceString(String line, String regex) { List<StringBuilder> list = new ArrayList<StringBuilder>(); StringBuilder builder; char delimiter = regex.replace("\\", "").charAt(0); String[] split = line.split(regex); String first, second, third; if (split.length == 2) { first = split[0]; second = split[1]; if (!Character.isDigit(first.charAt(first.length() - 1)) && !Character.isDigit(second.charAt(second.length() - 1))) { builder = new StringBuilder(); builder.append(first.trim()); builder.append(delimiter); builder.append('\n'); builder.append(second.trim()); if (line.endsWith(String.valueOf(delimiter))) { builder.append(delimiter); } list.add(builder); } } else if (split.length == 3) { first = split[0]; second = split[1]; third = split[2]; builder = new StringBuilder(); builder.append(first.trim()); builder.append(delimiter); builder.append(' '); builder.append(second.trim()); builder.append(delimiter); builder.append('\n'); builder.append(third.trim()); if (line.endsWith(String.valueOf(delimiter))) { builder.append(delimiter); } list.add(builder); builder = new StringBuilder(); builder.append(split[0].trim()); builder.append(delimiter); builder.append('\n'); builder.append(split[1].trim()); builder.append(delimiter); builder.append(' '); builder.append(split[2].trim()); if (line.endsWith(String.valueOf(delimiter))) { builder.append(delimiter); } list.add(builder); } else if (split.length > 3) { list.add(splitClosestToMiddle(line, delimiter)); } return list; } /** * Determines if two strings are approximately equal. * * @param result first string to check * @param text second string to check * @return True if strings are approximately equal, otherwise false. */ public static boolean isApproximatelyEqual(String result, String text) { // TODO: this is confusing boolean dotSpace = false, spaceDot = false; if (result.length() == text.length()) { result = result.replace("\n", " "); text = text.replace("\n", " "); char r, t; for (int i = 0; i < result.length(); ++i) { r = result.charAt(i); t = text.charAt(i); if ((r == ' ' && t == '\n') || (r == '\n' && t == ' ')) { // pass } else if (r != t) { if (dotSpace) { if (r == ' ' && t == '.') { dotSpace = false; continue; } else { return false; } } else if (spaceDot) { if (r == '.' && t == ' ') { spaceDot = false; continue; } else { return false; } } else if (r == '.' && t == ' ') { dotSpace = true; } else if (r == ' ' && t == '.') { spaceDot = true; } else { return false; } } else if (dotSpace || spaceDot) { return false; } } } else { return false; } if (dotSpace || spaceDot) { return false; } return true; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.wan; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.apache.logging.log4j.Logger; import org.apache.geode.CancelException; import org.apache.geode.DataSerializer; import org.apache.geode.cache.asyncqueue.AsyncEventListener; import org.apache.geode.cache.util.Gateway; import org.apache.geode.cache.wan.GatewaySender.OrderPolicy; import org.apache.geode.cache.wan.GatewayTransportFilter; import org.apache.geode.distributed.DistributedLockService; import org.apache.geode.distributed.internal.ClusterDistributionManager; import org.apache.geode.distributed.internal.DistributionAdvisee; import org.apache.geode.distributed.internal.DistributionAdvisor; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.ServerLocation; import org.apache.geode.distributed.internal.locks.DLockService; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.Assert; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.UpdateAttributesProcessor; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.LoggingThread; public class GatewaySenderAdvisor extends DistributionAdvisor { private static final Logger logger = LogService.getLogger(); private DistributedLockService lockService; private volatile boolean isPrimary; private final Object primaryLock = new Object(); private final String lockToken; private Thread lockObtainingThread; private AbstractGatewaySender sender; private GatewaySenderAdvisor(DistributionAdvisee sender) { super(sender); this.sender = (AbstractGatewaySender) sender; this.lockToken = getDLockServiceName() + "-token"; } public static GatewaySenderAdvisor createGatewaySenderAdvisor(DistributionAdvisee sender) { GatewaySenderAdvisor advisor = new GatewaySenderAdvisor(sender); advisor.initialize(); return advisor; } public String getDLockServiceName() { return getClass().getName() + "_" + this.sender.getId(); } public Thread getLockObtainingThread() { return this.lockObtainingThread; } /** Instantiate new Sender profile for this member */ @Override protected Profile instantiateProfile(InternalDistributedMember memberId, int version) { return new GatewaySenderProfile(memberId, version); } /** * The profile will be created when the sender is added to the cache. here we are not starting the * sender. so we should not release or acquire any lock for the sender to become primary based on * creation only. */ @Override public void profileCreated(Profile profile) { if (profile instanceof GatewaySenderProfile) { GatewaySenderProfile sp = (GatewaySenderProfile) profile; checkCompatibility(sp); } } private void checkCompatibility(GatewaySenderProfile sp) { if (sp.remoteDSId != sender.getRemoteDSId()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with remote ds id %s because another cache has the same Gateway Sender defined with remote ds id %s.", sp.Id, sp.remoteDSId, sender.remoteDSId)); } if (sp.isParallel && !sender.isParallel()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s as parallel gateway sender because another cache has the same sender as serial gateway sender", sp.Id)); } if (!sp.isParallel && sender.isParallel()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s as serial gateway sender because another cache has the same sender as parallel gateway sender", sp.Id)); } if (sp.isBatchConflationEnabled != sender.isBatchConflationEnabled()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with isBatchConflationEnabled %s because another cache has the same Gateway Sender defined with isBatchConflationEnabled %s", sp.Id, sp.isBatchConflationEnabled, sender.isBatchConflationEnabled())); } if (sp.isPersistenceEnabled != sender.isPersistenceEnabled()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with isPersistentEnabled %s because another cache has the same Gateway Sender defined with isPersistentEnabled %s", sp.Id, sp.isPersistenceEnabled, sender.isPersistenceEnabled())); } if (sp.alertThreshold != sender.getAlertThreshold()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with alertThreshold %s because another cache has the same Gateway Sender defined with alertThreshold %s", sp.Id, sp.alertThreshold, sender.getAlertThreshold())); } if (!sender.isParallel()) { if (sp.manualStart != sender.isManualStart()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with manual start %s because another cache has the same Gateway Sender defined with manual start %s", sp.Id, sp.manualStart, sender.isManualStart())); } } if (!sp.isParallel) { if (sp.orderPolicy != sender.getOrderPolicy()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with orderPolicy %s because another cache has the same Gateway Sender defined with orderPolicy %s", sp.Id, sp.orderPolicy, sender.getOrderPolicy())); } } List<String> senderEventFilterClassNames = new ArrayList<String>(); for (org.apache.geode.cache.wan.GatewayEventFilter filter : sender.getGatewayEventFilters()) { senderEventFilterClassNames.add(filter.getClass().getName()); } if (sp.eventFiltersClassNames.size() != senderEventFilterClassNames.size()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with GatewayEventFilters %s because another cache has the same Gateway Sender defined with GatewayEventFilters %s", sp.Id, sp.eventFiltersClassNames, senderEventFilterClassNames)); } else { for (String filterName : senderEventFilterClassNames) { if (!sp.eventFiltersClassNames.contains(filterName)) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with GatewayEventFilters %s because another cache has the same Gateway Sender defined with GatewayEventFilters %s", sp.Id, sp.eventFiltersClassNames, senderEventFilterClassNames)); } } } Set<String> senderTransportFilterClassNames = new LinkedHashSet<String>(); for (GatewayTransportFilter filter : sender.getGatewayTransportFilters()) { senderTransportFilterClassNames.add(filter.getClass().getName()); } if (sp.transFiltersClassNames.size() != senderTransportFilterClassNames.size()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with GatewayTransportFilters %s because another cache has the same Gateway Sender defined with GatewayTransportFilters %s", sp.Id, sp.transFiltersClassNames, senderTransportFilterClassNames)); } else { Iterator<String> i1 = sp.transFiltersClassNames.iterator(); Iterator<String> i2 = senderTransportFilterClassNames.iterator(); while (i1.hasNext() && i2.hasNext()) { if (!i1.next().equals(i2.next())) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with GatewayTransportFilters %s because another cache has the same Gateway Sender defined with GatewayTransportFilters %s", sp.Id, sp.transFiltersClassNames, senderTransportFilterClassNames)); } } } List<String> senderEventListenerClassNames = new ArrayList<String>(); for (AsyncEventListener listener : sender.getAsyncEventListeners()) { senderEventListenerClassNames.add(listener.getClass().getName()); } if (sp.senderEventListenerClassNames.size() != senderEventListenerClassNames.size()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with AsyncEventListeners %s because another cache has the same Gateway Sender defined with AsyncEventListener %s", sp.Id, sp.senderEventListenerClassNames, senderEventListenerClassNames)); } else { for (String listenerName : senderEventListenerClassNames) { if (!sp.senderEventListenerClassNames.contains(listenerName)) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with AsyncEventListeners %s because another cache has the same Gateway Sender defined with AsyncEventListener %s", sp.Id, sp.senderEventListenerClassNames, senderEventListenerClassNames)); } } } if (sp.isDiskSynchronous != sender.isDiskSynchronous()) { throw new IllegalStateException( String.format( "Cannot create Gateway Sender %s with isDiskSynchronous %s because another cache has the same Gateway Sender defined with isDiskSynchronous %s", sp.Id, sp.isDiskSynchronous, sender.isDiskSynchronous())); } } /** * If there is change in sender which having policy as primary. 1. If that sender is stopped then * if there are no other primary senders then this sender should volunteer for primary. 2. If this * sender is primary and its policy is secondary then this sender should release the lock so that * other primary sender which s waiting on lock will get the lock. */ @Override public void profileUpdated(Profile profile) { if (profile instanceof GatewaySenderProfile) { GatewaySenderProfile sp = (GatewaySenderProfile) profile; if (!sp.isParallel) { // SerialGatewaySender if (!sp.isRunning) { if (advisePrimaryGatewaySender() != null) { return; } // IF this sender is not primary if (!this.sender.isPrimary()) { if (!adviseEldestGatewaySender()) {// AND this is not the eldest // sender if (logger.isDebugEnabled()) { logger.debug( "Sender {} is not the eldest in the system. Giving preference to eldest sender to become primary...", this.sender); } return; } launchLockObtainingVolunteerThread(); } } else { if (sp.serverLocation != null) { this.sender.setServerLocation(sp.serverLocation); } } } } } /** * When the sender profile is removed, then check for the primary members if they are not * available then this secondary sender should volunteer for primary */ @Override protected void profileRemoved(Profile profile) { if (profile instanceof GatewaySenderProfile) { GatewaySenderProfile sp = (GatewaySenderProfile) profile; if (!sp.isParallel) {// SerialGatewaySender // if there is a primary sender, then don't volunteer for primary if (advisePrimaryGatewaySender() != null) { return; } if (!this.sender.isPrimary()) {// IF this sender is not primary if (!adviseEldestGatewaySender()) {// AND this is not the eldest sender if (logger.isDebugEnabled()) { logger.debug( "Sender {} is not the eldest in the system. Giving preference to eldest sender to become primary...", this.sender); } return; } launchLockObtainingVolunteerThread(); } } } } public boolean isPrimary() { return sender.isParallel() || this.isPrimary; } public void initDLockService() { InternalDistributedSystem ds = this.sender.getCache().getInternalDistributedSystem(); String dlsName = getDLockServiceName(); this.lockService = DistributedLockService.getServiceNamed(dlsName); if (this.lockService == null) { this.lockService = DLockService.create(dlsName, ds, true, true, true); } Assert.assertTrue(this.lockService != null); if (logger.isDebugEnabled()) { logger.debug("{}: Obtained DistributedLockService: {}", this, this.lockService); } } public boolean volunteerForPrimary() { if (logger.isDebugEnabled()) { logger.debug("Sender : {} is volunteering for Primary ", this.sender.getId()); } if (advisePrimaryGatewaySender() == null) { if (!adviseEldestGatewaySender()) { if (logger.isDebugEnabled()) { logger.debug( "Sender {} is not the eldest in the system. Giving preference to eldest sender to become primary...", this.sender); } return false; } if (logger.isDebugEnabled()) { logger.debug("Sender : {} no Primary available. So going to acquire distributed lock", this.sender); } this.lockService.lock(this.lockToken, 10000, -1); return this.lockService.isHeldByCurrentThread(this.lockToken); } return false; } /** * Find out if this sender is the eldest in the DS. Returns true if: 1. No other sender is running * 2. At least one sender is running in the system apart from this sender AND this sender's start * time is lesser of all (i.e. this sender is oldest) * * @return boolean true if this eldest sender; false otherwise */ private boolean adviseEldestGatewaySender() { Profile[] snapshot = this.profiles; // sender with minimum startTime is eldest. Find out the minimum start time // of remote senders. TreeSet<Long> senderStartTimes = new TreeSet<Long>(); for (Profile profile : snapshot) { GatewaySenderProfile sp = (GatewaySenderProfile) profile; if (!sp.isParallel && sp.isRunning) { senderStartTimes.add(sp.startTime); } } // if none of the remote senders is running, then this sender should // volunteer for primary // if there are remote senders running and this sender is not running then // it should give up // and allow existing running senders to volunteer return (senderStartTimes.isEmpty()) || (this.sender.isRunning() && (this.sender.startTime <= senderStartTimes.first())); } private InternalDistributedMember adviseEldestGatewaySenderNode() { Profile[] snapshot = this.profiles; // sender with minimum startTime is eldest. Find out the minimum start time // of remote senders. InternalDistributedMember node = null; GatewaySenderProfile eldestProfile = null; for (Profile profile : snapshot) { GatewaySenderProfile sp = (GatewaySenderProfile) profile; if (!sp.isParallel && sp.isRunning) { if (eldestProfile == null) { eldestProfile = sp; } if (sp.startTime < eldestProfile.startTime) { eldestProfile = sp; } } } if (eldestProfile != null) { node = eldestProfile.getDistributedMember(); } return node; } public void makePrimary() { logger.info("{} : Starting as primary", this.sender); AbstractGatewaySenderEventProcessor eventProcessor = this.sender.getEventProcessor(); if (eventProcessor != null) { eventProcessor.removeCacheListener(); } logger.info("{} : Becoming primary gateway sender", this.sender); notifyAndBecomePrimary(); new UpdateAttributesProcessor(this.sender).distribute(false); } public void notifyAndBecomePrimary() { synchronized (this.primaryLock) { setIsPrimary(true); notifyPrimaryLock(); } } public void notifyPrimaryLock() { synchronized (this.primaryLock) { this.primaryLock.notifyAll(); } } public void makeSecondary() { if (logger.isDebugEnabled()) { logger.debug("{}: Did not obtain the lock on {}. Starting as secondary gateway sender.", this.sender, this.lockToken); } // Set primary flag to false logger.info( "{} starting as secondary because primary gateway sender is available on member :{}", new Object[] {this.sender.getId(), advisePrimaryGatewaySender()}); this.isPrimary = false; new UpdateAttributesProcessor(this.sender).distribute(false); } public void launchLockObtainingVolunteerThread() { String threadName = "Gateway Sender Primary Lock Acquisition Thread Volunteer"; this.lockObtainingThread = new LoggingThread(threadName, () -> { GatewaySenderAdvisor.this.sender.getLifeCycleLock().readLock().lock(); try { // Attempt to obtain the lock if (!(GatewaySenderAdvisor.this.sender.isRunning())) { return; } if (logger.isDebugEnabled()) { logger.debug("{}: Obtaining the lock on {}", this, GatewaySenderAdvisor.this.lockToken); } if (volunteerForPrimary()) { if (logger.isDebugEnabled()) { logger.debug("{}: Obtained the lock on {}", this, GatewaySenderAdvisor.this.lockToken); } logger.info("{} is becoming primary gateway Sender.", GatewaySenderAdvisor.this); // As soon as the lock is obtained, set primary GatewaySenderAdvisor.this.makePrimary(); } } catch (CancelException e) { // no action necessary } catch (Exception e) { if (!sender.getStopper().isCancelInProgress()) { logger.fatal(String.format( "%s: The thread to obtain the failover lock was interrupted. This gateway sender will never become the primary.", GatewaySenderAdvisor.this), e); } } finally { GatewaySenderAdvisor.this.sender.getLifeCycleLock().readLock().unlock(); } }); this.lockObtainingThread.start(); } public void waitToBecomePrimary(AbstractGatewaySenderEventProcessor callingProcessor) throws InterruptedException { if (isPrimary()) { return; } synchronized (this.primaryLock) { logger.info("{} : Waiting to become primary gateway", this.sender.getId()); while (!isPrimary()) { this.primaryLock.wait(1000); if (sender.getEventProcessor() != null && callingProcessor.isStopped()) { logger.info("The event processor is stopped, not to wait for being primary any more."); return; } } } } /** * Profile information for a remote counterpart. */ public static class GatewaySenderProfile extends DistributionAdvisor.Profile { public String Id; public long startTime; public int remoteDSId; /** * I need this boolean to make sure the sender which is volunteer for primary is running. not * running sender should not become primary. */ public boolean isRunning; public boolean isPrimary; public boolean isParallel; public boolean isBatchConflationEnabled; public boolean isPersistenceEnabled; public int alertThreshold; public boolean manualStart; public ArrayList<String> eventFiltersClassNames = new ArrayList<String>(); public ArrayList<String> transFiltersClassNames = new ArrayList<String>(); public ArrayList<String> senderEventListenerClassNames = new ArrayList<String>(); public boolean isDiskSynchronous; public int dispatcherThreads; public OrderPolicy orderPolicy; public ServerLocation serverLocation; public GatewaySenderProfile(InternalDistributedMember memberId, int version) { super(memberId, version); } public GatewaySenderProfile() {} @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.Id = DataSerializer.readString(in); this.startTime = in.readLong(); this.remoteDSId = in.readInt(); this.isRunning = in.readBoolean(); this.isPrimary = in.readBoolean(); this.isParallel = in.readBoolean(); this.isBatchConflationEnabled = in.readBoolean(); this.isPersistenceEnabled = in.readBoolean(); this.alertThreshold = in.readInt(); this.manualStart = in.readBoolean(); this.eventFiltersClassNames = DataSerializer.readArrayList(in); this.transFiltersClassNames = DataSerializer.readArrayList(in); this.senderEventListenerClassNames = DataSerializer.readArrayList(in); this.isDiskSynchronous = in.readBoolean(); this.dispatcherThreads = in.readInt(); if (InternalDataSerializer.getVersionForDataStream(in).compareTo(Version.GFE_90) < 0) { Gateway.OrderPolicy oldOrderPolicy = DataSerializer.readObject(in); if (oldOrderPolicy != null) { if (oldOrderPolicy.name().equals(OrderPolicy.KEY.name())) { this.orderPolicy = OrderPolicy.KEY; } else if (oldOrderPolicy.name().equals(OrderPolicy.THREAD.name())) { this.orderPolicy = OrderPolicy.THREAD; } else { this.orderPolicy = OrderPolicy.PARTITION; } } else { this.orderPolicy = null; } } else { this.orderPolicy = DataSerializer.readObject(in); } boolean serverLocationFound = DataSerializer.readPrimitiveBoolean(in); if (serverLocationFound) { this.serverLocation = new ServerLocation(); InternalDataSerializer.invokeFromData(this.serverLocation, in); } } @Override public void toData(DataOutput out) throws IOException { super.toData(out); DataSerializer.writeString(Id, out); out.writeLong(startTime); out.writeInt(remoteDSId); out.writeBoolean(isRunning); out.writeBoolean(isPrimary); out.writeBoolean(isParallel); out.writeBoolean(isBatchConflationEnabled); out.writeBoolean(isPersistenceEnabled); out.writeInt(alertThreshold); out.writeBoolean(manualStart); DataSerializer.writeArrayList(eventFiltersClassNames, out); DataSerializer.writeArrayList(transFiltersClassNames, out); DataSerializer.writeArrayList(senderEventListenerClassNames, out); out.writeBoolean(isDiskSynchronous); out.writeInt(dispatcherThreads); if (InternalDataSerializer.getVersionForDataStream(out).compareTo(Version.GFE_90) < 0 && this.orderPolicy != null) { String orderPolicyName = this.orderPolicy.name(); if (orderPolicyName.equals(Gateway.OrderPolicy.KEY.name())) { DataSerializer.writeObject(Gateway.OrderPolicy.KEY, out); } else if (orderPolicyName.equals(Gateway.OrderPolicy.THREAD.name())) { DataSerializer.writeObject(Gateway.OrderPolicy.THREAD, out); } else { DataSerializer.writeObject(Gateway.OrderPolicy.PARTITION, out); } } else { DataSerializer.writeObject(orderPolicy, out); } boolean serverLocationFound = (this.serverLocation != null); DataSerializer.writePrimitiveBoolean(serverLocationFound, out); if (serverLocationFound) { InternalDataSerializer.invokeToData(serverLocation, out); } } public void fromDataPre_GFE_8_0_0_0(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.Id = DataSerializer.readString(in); this.startTime = in.readLong(); this.remoteDSId = in.readInt(); this.isRunning = in.readBoolean(); this.isPrimary = in.readBoolean(); this.isParallel = in.readBoolean(); this.isBatchConflationEnabled = in.readBoolean(); this.isPersistenceEnabled = in.readBoolean(); this.alertThreshold = in.readInt(); this.manualStart = in.readBoolean(); this.eventFiltersClassNames = DataSerializer.readArrayList(in); this.transFiltersClassNames = DataSerializer.readArrayList(in); this.senderEventListenerClassNames = DataSerializer.readArrayList(in); this.isDiskSynchronous = in.readBoolean(); this.dispatcherThreads = in.readInt(); this.orderPolicy = DataSerializer.readObject(in); boolean serverLocationFound = DataSerializer.readPrimitiveBoolean(in); if (serverLocationFound) { this.serverLocation = new ServerLocation(); InternalDataSerializer.invokeFromData(this.serverLocation, in); } } public void toDataPre_GFE_8_0_0_0(DataOutput out) throws IOException { super.toData(out); DataSerializer.writeString(Id, out); out.writeLong(startTime); out.writeInt(remoteDSId); out.writeBoolean(isRunning); out.writeBoolean(isPrimary); out.writeBoolean(isParallel); out.writeBoolean(isBatchConflationEnabled); out.writeBoolean(isPersistenceEnabled); out.writeInt(alertThreshold); out.writeBoolean(manualStart); DataSerializer.writeArrayList(eventFiltersClassNames, out); DataSerializer.writeArrayList(transFiltersClassNames, out); DataSerializer.writeArrayList(senderEventListenerClassNames, out); out.writeBoolean(isDiskSynchronous); // out.writeInt(dispatcherThreads); if (isParallel) out.writeInt(1);// it was 1 on previous version of gemfire else if (orderPolicy == null) out.writeInt(1);// it was 1 on previous version of gemfire else out.writeInt(dispatcherThreads); if (isParallel) DataSerializer.writeObject(null, out); else DataSerializer.writeObject(orderPolicy, out); boolean serverLocationFound = (this.serverLocation != null); DataSerializer.writePrimitiveBoolean(serverLocationFound, out); if (serverLocationFound) { InternalDataSerializer.invokeToData(serverLocation, out); } } private static final Version[] serializationVersions = new Version[] {Version.GFE_80}; @Override public Version[] getSerializationVersions() { return serializationVersions; } @Override public int getDSFID() { return GATEWAY_SENDER_PROFILE; } @Override public void processIncoming(ClusterDistributionManager dm, String adviseePath, boolean removeProfile, boolean exchangeProfiles, final List<Profile> replyProfiles) { InternalCache cache = dm.getCache(); if (cache != null) { AbstractGatewaySender sender = (AbstractGatewaySender) cache.getGatewaySender(adviseePath); handleDistributionAdvisee(sender, removeProfile, exchangeProfiles, replyProfiles); } } @Override public void fillInToString(StringBuilder sb) { super.fillInToString(sb); sb.append("; id=" + this.Id); sb.append("; remoteDSName=" + this.remoteDSId); sb.append("; isRunning=" + this.isRunning); sb.append("; isPrimary=" + this.isPrimary); } } public InternalDistributedMember advisePrimaryGatewaySender() { Profile[] snapshot = this.profiles; for (Profile profile : snapshot) { GatewaySenderProfile sp = (GatewaySenderProfile) profile; if (!sp.isParallel && sp.isPrimary) { return sp.getDistributedMember(); } } return null; } public void setIsPrimary(boolean isPrimary) { this.isPrimary = isPrimary; } @Override public void close() { new UpdateAttributesProcessor(this.getAdvisee(), true).distribute(false); super.close(); } }
package mrsim.generic; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.WritableComparator; public class CloudJoinWindowGrouper implements RawComparator<CloudJoinKey>, Configurable{ private Configuration conf; @Override public int compare(CloudJoinKey key1, CloudJoinKey key2) { long part1 = key1.getPartitionID(); long win1 = key1.getWindowID(); long part2 = key2.getPartitionID(); long win2 = key2.getWindowID(); if( (win1==-1) && (win2==-1) )//p-p { if(part1==part2) { return 0; } else { return (part1<part2? -1:1); } } else if( (win1==-1) && (win2!=-1) ) //p-w { return -1; } else if ((win1!=-1) && (win2==-1)) //w-p { return 1; } else { long min1 = Math.min(part1, win1); long max1 = Math.max(part1, win1); long min2 = Math.min(part2, win2); long max2 = Math.max(part2, win2); if ( !((min1==min2) && (max1==max2)) ) { if(min1==min2) return (max1<max2 ? -1:1); else return (min1<min2 ? -1:1); } else { long prevPart1 = key1.getPrevItrPartion(); long prevPart2 = key2.getPrevItrPartion(); //we should perform a check here and make sure we get values back long W = Long.parseLong(conf.get("W")); long V = Long.parseLong(conf.get("V")); if ( (part1==part2) && (prevPart1==prevPart2) ) return 0; else if (part1==part2) { if (part1<win1) { if( (prevPart1==V) && (prevPart2==W) ) return -1; else return 1; } else { if( (prevPart1==V) && (prevPart2==W) ) return 1; else return -1; } } else if (prevPart1==prevPart2) { if (prevPart1==V) { if (part1<win1) return -1; else return 1; } else { if (part1<win1) return 1; else return -1; } } else return 0; } } }// end compare public int compare( byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { //this is going to be needing some optimization but this is the easiest way to code this right now. long part1 = WritableComparator.readLong(b1, s1); long win1 = WritableComparator.readLong(b1, s1 + (Long.SIZE / 8)); long part2 = WritableComparator.readLong(b2, s2); long win2 = WritableComparator.readLong(b2, s2 + (Long.SIZE / 8)); if( (win1==-1) && (win2==-1) )//p-p { if(part1==part2) { return 0; } else { return (part1<part2? -1:1); } } else if( (win1==-1) && (win2!=-1) ) //p-w { return -1; } else if ((win1!=-1) && (win2==-1)) //w-p { return 1; } else { long min1 = Math.min(part1, win1); long max1 = Math.max(part1, win1); long min2 = Math.min(part2, win2); long max2 = Math.max(part2, win2); if ( !((min1==min2) && (max1==max2)) ) { if(min1==min2) return (max1<max2 ? -1:1); else return (min1<min2 ? -1:1); } else { long prevPart1 = WritableComparator.readLong(b1, s1 + (Long.SIZE + Long.SIZE) / 8); long prevPart2 = WritableComparator.readLong(b2, s2 + (Long.SIZE + Long.SIZE) / 8); //we should perform a check here and make sure we get values back long W = Long.parseLong(conf.get("W")); long V = Long.parseLong(conf.get("V")); if ( (part1==part2) && (prevPart1==prevPart2) ) return 0; else if (part1==part2) { if (part1<win1) { if( (prevPart1==V) && (prevPart2==W) ) return -1; else return 1; } else { if( (prevPart1==V) && (prevPart2==W) ) return 1; else return -1; } } else if (prevPart1==prevPart2) { if (prevPart1==V) { if (part1<win1) return -1; else return 1; } else { if (part1<win1) return 1; else return -1; } } else return 0; } } } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mnemonic.mapreduce; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.zip.CRC32; import java.util.zip.Checksum; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.apache.mnemonic.DurableChunk; import org.apache.mnemonic.DurableType; import org.apache.mnemonic.Utils; import org.apache.mnemonic.hadoop.MneConfigHelper; import org.apache.mnemonic.hadoop.MneDurableInputSession; import org.apache.mnemonic.hadoop.MneDurableInputValue; import org.apache.mnemonic.hadoop.MneDurableOutputSession; import org.apache.mnemonic.hadoop.MneDurableOutputValue; import org.apache.mnemonic.hadoop.mapreduce.MneInputFormat; import org.apache.mnemonic.hadoop.mapreduce.MneOutputFormat; import org.apache.mnemonic.sessions.SessionIterator; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @SuppressWarnings("restriction") public class MneMapreduceChunkDataTest { private static final String DEFAULT_BASE_WORK_DIR = "target" + File.separator + "test" + File.separator + "tmp"; private static final String DEFAULT_WORK_DIR = DEFAULT_BASE_WORK_DIR + File.separator + "chunk-data"; private static final String SERVICE_NAME = "pmalloc"; private static final long SLOT_KEY_ID = 5L; private Path m_workdir; private JobConf m_conf; private FileSystem m_fs; private Random m_rand; private TaskAttemptID m_taid; private TaskAttemptContext m_tacontext; private long m_reccnt = 5000L; private volatile long m_checksum; private volatile long m_totalsize = 0L; @SuppressWarnings({"restriction", "UseOfSunClasses"}) private sun.misc.Unsafe unsafe; @BeforeClass public void setUp() throws Exception { m_workdir = new Path( System.getProperty("test.tmp.dir", DEFAULT_WORK_DIR)); m_conf = new JobConf(); m_rand = Utils.createRandom(); unsafe = Utils.getUnsafe(); try { m_fs = FileSystem.getLocal(m_conf).getRaw(); m_fs.delete(m_workdir, true); m_fs.mkdirs(m_workdir); } catch (IOException e) { throw new IllegalStateException("bad fs init", e); } m_taid = new TaskAttemptID("jt", 0, TaskType.MAP, 0, 0); m_tacontext = new TaskAttemptContextImpl(m_conf, m_taid); MneConfigHelper.setDir(m_conf, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX, m_workdir.toString()); MneConfigHelper.setBaseOutputName(m_conf, null, "chunk-data"); MneConfigHelper.setMemServiceName(m_conf, MneConfigHelper.DEFAULT_INPUT_CONFIG_PREFIX, SERVICE_NAME); MneConfigHelper.setSlotKeyId(m_conf, MneConfigHelper.DEFAULT_INPUT_CONFIG_PREFIX, SLOT_KEY_ID); MneConfigHelper.setDurableTypes(m_conf, MneConfigHelper.DEFAULT_INPUT_CONFIG_PREFIX, new DurableType[] {DurableType.CHUNK}); MneConfigHelper.setEntityFactoryProxies(m_conf, MneConfigHelper.DEFAULT_INPUT_CONFIG_PREFIX, new Class<?>[] {}); MneConfigHelper.setMemServiceName(m_conf, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX, SERVICE_NAME); MneConfigHelper.setSlotKeyId(m_conf, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX, SLOT_KEY_ID); MneConfigHelper.setMemPoolSize(m_conf, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX, 1024L * 1024 * 1024 * 4); MneConfigHelper.setDurableTypes(m_conf, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX, new DurableType[] {DurableType.CHUNK}); MneConfigHelper.setEntityFactoryProxies(m_conf, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX, new Class<?>[] {}); } @AfterClass public void tearDown() { } protected DurableChunk<?> genupdDurableChunk( MneDurableOutputSession<DurableChunk<?>> s, Checksum cs) { DurableChunk<?> ret = null; int sz = m_rand.nextInt(1024 * 1024) + 1024 * 1024; ret = s.newDurableObjectRecord(sz); byte b; if (null != ret) { for (int i = 0; i < ret.getSize(); ++i) { b = (byte) m_rand.nextInt(255); unsafe.putByte(ret.get() + i, b); cs.update(b); } m_totalsize += sz; } return ret; } @Test(enabled = true) public void testWriteChunkData() throws Exception { NullWritable nada = NullWritable.get(); MneDurableOutputSession<DurableChunk<?>> sess = new MneDurableOutputSession<DurableChunk<?>>(m_tacontext, null, MneConfigHelper.DEFAULT_OUTPUT_CONFIG_PREFIX); MneDurableOutputValue<DurableChunk<?>> mdvalue = new MneDurableOutputValue<DurableChunk<?>>(sess); OutputFormat<NullWritable, MneDurableOutputValue<DurableChunk<?>>> outputFormat = new MneOutputFormat<MneDurableOutputValue<DurableChunk<?>>>(); RecordWriter<NullWritable, MneDurableOutputValue<DurableChunk<?>>> writer = outputFormat.getRecordWriter(m_tacontext); DurableChunk<?> dchunk = null; Checksum cs = new CRC32(); cs.reset(); for (int i = 0; i < m_reccnt; ++i) { dchunk = genupdDurableChunk(sess, cs); Assert.assertNotNull(dchunk); writer.write(nada, mdvalue.of(dchunk)); } m_checksum = cs.getValue(); writer.close(m_tacontext); sess.close(); } @Test(enabled = true, dependsOnMethods = { "testWriteChunkData" }) public void testReadChunkData() throws Exception { List<String> partfns = new ArrayList<String>(); long reccnt = 0L; long tsize = 0L; Checksum cs = new CRC32(); cs.reset(); File folder = new File(m_workdir.toString()); File[] listfiles = folder.listFiles(); for (int idx = 0; idx < listfiles.length; ++idx) { if (listfiles[idx].isFile() && listfiles[idx].getName().startsWith(MneConfigHelper.getBaseOutputName(m_conf, null)) && listfiles[idx].getName().endsWith(MneConfigHelper.DEFAULT_FILE_EXTENSION)) { partfns.add(listfiles[idx].getName()); } } Collections.sort(partfns); // keep the order for checksum for (int idx = 0; idx < partfns.size(); ++idx) { System.out.println(String.format("Verifying : %s", partfns.get(idx))); FileSplit split = new FileSplit( new Path(m_workdir, partfns.get(idx)), 0, 0L, new String[0]); InputFormat<NullWritable, MneDurableInputValue<DurableChunk<?>>> inputFormat = new MneInputFormat<MneDurableInputValue<DurableChunk<?>>, DurableChunk<?>>(); RecordReader<NullWritable, MneDurableInputValue<DurableChunk<?>>> reader = inputFormat.createRecordReader(split, m_tacontext); MneDurableInputValue<DurableChunk<?>> dchkval = null; while (reader.nextKeyValue()) { dchkval = reader.getCurrentValue(); byte b; for (int j = 0; j < dchkval.getValue().getSize(); ++j) { b = unsafe.getByte(dchkval.getValue().get() + j); cs.update(b); } tsize += dchkval.getValue().getSize(); ++reccnt; } reader.close(); } AssertJUnit.assertEquals(m_reccnt, reccnt); AssertJUnit.assertEquals(m_totalsize, tsize); AssertJUnit.assertEquals(m_checksum, cs.getValue()); System.out.println(String.format("The checksum of chunk is %d", m_checksum)); } @Test(enabled = true, dependsOnMethods = { "testWriteChunkData" }) public void testBatchReadChunkDataUsingInputSession() throws Exception { List<String> partfns = new ArrayList<String>(); long reccnt = 0L; long tsize = 0L; Checksum cs = new CRC32(); cs.reset(); File folder = new File(m_workdir.toString()); File[] listfiles = folder.listFiles(); for (int idx = 0; idx < listfiles.length; ++idx) { if (listfiles[idx].isFile() && listfiles[idx].getName().startsWith(MneConfigHelper.getBaseOutputName(m_conf, null)) && listfiles[idx].getName().endsWith(MneConfigHelper.DEFAULT_FILE_EXTENSION)) { partfns.add(listfiles[idx].getName()); } } Collections.sort(partfns); // keep the order for checksum List<Path> paths = new ArrayList<Path>(); for (String fns : partfns) { paths.add(new Path(m_workdir, fns)); System.out.println(String.format("[Batch Mode] Added : %s", fns)); } MneDurableInputSession<DurableChunk<?>> m_session = new MneDurableInputSession<DurableChunk<?>>(m_tacontext, null, paths.toArray(new Path[0]), MneConfigHelper.DEFAULT_INPUT_CONFIG_PREFIX); SessionIterator<DurableChunk<?>, ?, Void, Void> m_iter = m_session.iterator(); DurableChunk<?> val = null; while (m_iter.hasNext()) { val = m_iter.next(); byte b; for (int j = 0; j < val.getSize(); ++j) { b = unsafe.getByte(val.get() + j); cs.update(b); } tsize += val.getSize(); ++reccnt; } AssertJUnit.assertEquals(m_reccnt, reccnt); AssertJUnit.assertEquals(m_totalsize, tsize); AssertJUnit.assertEquals(m_checksum, cs.getValue()); System.out.println(String.format("The checksum of chunk is %d [Batch Mode]", m_checksum)); } }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetDeployablePatchSnapshotForInstance" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetDeployablePatchSnapshotForInstanceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The ID of the instance. * </p> */ private String instanceId; /** * <p> * The user-defined snapshot ID. * </p> */ private String snapshotId; /** * <p> * A pre-signed Amazon S3 URL that can be used to download the patch snapshot. * </p> */ private String snapshotDownloadUrl; /** * <p> * The ID of the instance. * </p> * * @param instanceId * The ID of the instance. */ public void setInstanceId(String instanceId) { this.instanceId = instanceId; } /** * <p> * The ID of the instance. * </p> * * @return The ID of the instance. */ public String getInstanceId() { return this.instanceId; } /** * <p> * The ID of the instance. * </p> * * @param instanceId * The ID of the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDeployablePatchSnapshotForInstanceResult withInstanceId(String instanceId) { setInstanceId(instanceId); return this; } /** * <p> * The user-defined snapshot ID. * </p> * * @param snapshotId * The user-defined snapshot ID. */ public void setSnapshotId(String snapshotId) { this.snapshotId = snapshotId; } /** * <p> * The user-defined snapshot ID. * </p> * * @return The user-defined snapshot ID. */ public String getSnapshotId() { return this.snapshotId; } /** * <p> * The user-defined snapshot ID. * </p> * * @param snapshotId * The user-defined snapshot ID. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDeployablePatchSnapshotForInstanceResult withSnapshotId(String snapshotId) { setSnapshotId(snapshotId); return this; } /** * <p> * A pre-signed Amazon S3 URL that can be used to download the patch snapshot. * </p> * * @param snapshotDownloadUrl * A pre-signed Amazon S3 URL that can be used to download the patch snapshot. */ public void setSnapshotDownloadUrl(String snapshotDownloadUrl) { this.snapshotDownloadUrl = snapshotDownloadUrl; } /** * <p> * A pre-signed Amazon S3 URL that can be used to download the patch snapshot. * </p> * * @return A pre-signed Amazon S3 URL that can be used to download the patch snapshot. */ public String getSnapshotDownloadUrl() { return this.snapshotDownloadUrl; } /** * <p> * A pre-signed Amazon S3 URL that can be used to download the patch snapshot. * </p> * * @param snapshotDownloadUrl * A pre-signed Amazon S3 URL that can be used to download the patch snapshot. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDeployablePatchSnapshotForInstanceResult withSnapshotDownloadUrl(String snapshotDownloadUrl) { setSnapshotDownloadUrl(snapshotDownloadUrl); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInstanceId() != null) sb.append("InstanceId: ").append(getInstanceId()).append(","); if (getSnapshotId() != null) sb.append("SnapshotId: ").append(getSnapshotId()).append(","); if (getSnapshotDownloadUrl() != null) sb.append("SnapshotDownloadUrl: ").append(getSnapshotDownloadUrl()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetDeployablePatchSnapshotForInstanceResult == false) return false; GetDeployablePatchSnapshotForInstanceResult other = (GetDeployablePatchSnapshotForInstanceResult) obj; if (other.getInstanceId() == null ^ this.getInstanceId() == null) return false; if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false) return false; if (other.getSnapshotId() == null ^ this.getSnapshotId() == null) return false; if (other.getSnapshotId() != null && other.getSnapshotId().equals(this.getSnapshotId()) == false) return false; if (other.getSnapshotDownloadUrl() == null ^ this.getSnapshotDownloadUrl() == null) return false; if (other.getSnapshotDownloadUrl() != null && other.getSnapshotDownloadUrl().equals(this.getSnapshotDownloadUrl()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode()); hashCode = prime * hashCode + ((getSnapshotId() == null) ? 0 : getSnapshotId().hashCode()); hashCode = prime * hashCode + ((getSnapshotDownloadUrl() == null) ? 0 : getSnapshotDownloadUrl().hashCode()); return hashCode; } @Override public GetDeployablePatchSnapshotForInstanceResult clone() { try { return (GetDeployablePatchSnapshotForInstanceResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package fr.desaintsteban.liste.envies.util; import fr.desaintsteban.liste.envies.dto.WishDto; import fr.desaintsteban.liste.envies.dto.WishListDto; import fr.desaintsteban.liste.envies.enums.*; import fr.desaintsteban.liste.envies.model.*; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.extractProperty; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class WishRulesTest { @Test public void cleanWishAnonyme() { WishDto wish = createDefaultWish(); WishDto cleaned = WishRules.cleanWish(wish, WishOptionType.ANONYMOUS); assertThat(extractProperty("name").from(cleaned.getUserTake())).hasSize(1).contains("anonyme"); assertThat(extractProperty("text").from(cleaned.getComments())).hasSize(1).contains("Public"); } @Test public void cleanWishHidden() { WishDto wish = createDefaultWish(); WishDto cleaned = WishRules.cleanWish(wish, WishOptionType.HIDDEN); assertThat(cleaned.getUserTake()).isNull(); assertThat(extractProperty("text").from(cleaned.getComments())).hasSize(2).contains("Public", "Owner"); } @Test public void cleanWishAll() { WishDto wish = createDefaultWish(); WishDto cleaned = WishRules.cleanWish(wish, WishOptionType.ALL); assertThat(extractProperty("email").from(cleaned.getUserTake())).hasSize(1).contains("patrice@desaintsteban.fr"); assertThat(extractProperty("text").from(cleaned.getComments())).hasSize(3).contains("Public", "Owner", "Private"); } @org.junit.jupiter.api.Test public void filterWishAll() { List<WishDto> wishList = createDefaultListOfWish(); List<WishDto> cleaned = WishRules.filterWishList(wishList, WishOptionType.ALL); assertThat(cleaned).isNotNull().hasSize(1); } @Test public void filterWishAllSuggest() { List<WishDto> wishList = createDefaultListOfWish(); List<WishDto> cleaned = WishRules.filterWishList(wishList, WishOptionType.ALL_SUGGEST); assertThat(cleaned).isNotNull().hasSize(2); } @Test public void filterWishNone() { List<WishDto> wishList = createDefaultListOfWish(); List<WishDto> cleaned = WishRules.filterWishList(wishList, WishOptionType.NONE); assertThat(cleaned).isNotNull().hasSize(0); } @Test public void testComputeWishListState() { WishList wishlist = createDefaultWishList(); assertEquals(WishListState.OWNER, WishRules.computeWishListState(new AppUser("patrice@desaintsteban.fr"), wishlist)); assertEquals(WishListState.SHARED, WishRules.computeWishListState(new AppUser("emmanuel@desaintsteban.fr"), wishlist)); assertEquals(WishListState.LOGGED, WishRules.computeWishListState(new AppUser("emeline@desaintsteban.fr"), wishlist)); assertEquals(WishListState.ANONYMOUS, WishRules.computeWishListState(new AppUser(null, "Anonyme"), wishlist)); assertEquals(WishListState.ANONYMOUS, WishRules.computeWishListState(null, wishlist)); } @Test public void testComputeWishOptionType() { WishList wishlist = createDefaultWishList(); assertEquals(WishOptionType.HIDDEN, WishRules.computeWishOptionsType(new AppUser("patrice@desaintsteban.fr"), wishlist)); assertEquals(WishOptionType.ALL_SUGGEST, WishRules.computeWishOptionsType(new AppUser("emmanuel@desaintsteban.fr"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(new AppUser("emeline@desaintsteban.fr"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(new AppUser(null, "Anonyme"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(null, wishlist)); wishlist.setPrivacy(SharingPrivacyType.PRIVATE); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(new AppUser("emeline@desaintsteban.fr"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(new AppUser(null, "Anonyme"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(null, wishlist)); wishlist.setPrivacy(SharingPrivacyType.OPEN); assertEquals(WishOptionType.ANONYMOUS, WishRules.computeWishOptionsType(new AppUser("emeline@desaintsteban.fr"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(new AppUser(null, "Anonyme"), wishlist)); assertEquals(WishOptionType.NONE, WishRules.computeWishOptionsType(null, wishlist)); wishlist.setPrivacy(SharingPrivacyType.PUBLIC); assertEquals(WishOptionType.ALL_SUGGEST, WishRules.computeWishOptionsType(new AppUser("emeline@desaintsteban.fr"), wishlist)); assertEquals(WishOptionType.ANONYMOUS, WishRules.computeWishOptionsType(new AppUser(null, "Anonyme"), wishlist)); assertEquals(WishOptionType.ANONYMOUS, WishRules.computeWishOptionsType(null, wishlist)); } @Test public void testComputePermissionWishList() { WishList wishlist = createDefaultWishList(); WishListDto dto = new WishListDto(); WishRules.computePermissions(dto, wishlist, new AppUser("patrice@desaintsteban.fr")); assertTrue(dto.getOwner()); assertFalse(dto.getCanSuggest()); WishRules.computePermissions(dto, wishlist, new AppUser("emmanuel@desaintsteban.fr")); assertFalse(dto.getOwner()); assertTrue(dto.getCanSuggest()); WishRules.computePermissions(dto, wishlist, new AppUser("emeline@desaintsteban.fr")); assertFalse(dto.getOwner()); assertTrue(dto.getCanSuggest()); WishRules.computePermissions(dto, wishlist, new AppUser(null, "Anonyme")); assertFalse(dto.getOwner()); assertFalse(dto.getCanSuggest()); } @Test public void testCanGive() { WishList wishlist; AppUser owner = new AppUser("patrice@desaintsteban.fr"); AppUser participant = new AppUser("emmanuel@desaintsteban.fr"); AppUser other = new AppUser("emeline@desaintsteban.fr"); AppUser anonyme = new AppUser(null, "Anonyme"); //Private wishlist = createDefaultWishList(SharingPrivacyType.PRIVATE); assertFalse(WishRules.canGive(wishlist, owner)); assertTrue(WishRules.canGive(wishlist, participant)); assertFalse(WishRules.canGive(wishlist, other)); assertFalse(WishRules.canGive(wishlist, anonyme)); //Open wishlist = createDefaultWishList(SharingPrivacyType.OPEN); assertFalse(WishRules.canGive(wishlist, owner)); assertTrue(WishRules.canGive(wishlist, participant)); assertTrue(WishRules.canGive(wishlist, other, false)); assertFalse(WishRules.canGive(wishlist, anonyme)); //Public wishlist = createDefaultWishList(SharingPrivacyType.PUBLIC); assertFalse(WishRules.canGive(wishlist, owner)); assertTrue(WishRules.canGive(wishlist, participant)); assertTrue(WishRules.canGive(wishlist, other)); assertFalse(WishRules.canGive(wishlist, anonyme)); } @Test public void testCanAddWish() { WishList wishlist; AppUser owner = new AppUser("patrice@desaintsteban.fr"); AppUser participant = new AppUser("emmanuel@desaintsteban.fr"); AppUser other = new AppUser("emeline@desaintsteban.fr"); AppUser anonyme = new AppUser(null, "Anonyme"); Wish wish = new Wish(); //Private wishlist = createDefaultWishList(SharingPrivacyType.PRIVATE); assertTrue(WishRules.canAddWish(wishlist, wish, owner)); assertTrue(WishRules.canAddWish(wishlist, wish, participant)); assertFalse(WishRules.canAddWish(wishlist, wish, other)); assertFalse(WishRules.canAddWish(wishlist, wish, anonyme)); //Open wishlist = createDefaultWishList(SharingPrivacyType.OPEN); assertTrue(WishRules.canAddWish(wishlist, wish, owner)); assertTrue(WishRules.canAddWish(wishlist, wish, participant)); assertTrue(WishRules.canAddWish(wishlist, wish, other, false)); assertFalse(WishRules.canAddWish(wishlist, wish, anonyme)); //Public wishlist = createDefaultWishList(SharingPrivacyType.PUBLIC); assertTrue(WishRules.canAddWish(wishlist, wish, owner)); assertTrue(WishRules.canAddWish(wishlist, wish, participant)); assertTrue(WishRules.canAddWish(wishlist, wish, other)); assertFalse(WishRules.canAddWish(wishlist, wish, anonyme)); } private WishList createDefaultWishList() { WishList list = new WishList(); List<UserShare> users = new ArrayList<>(); users.add(new UserShare("patrice@desaintsteban.fr", UserShareType.OWNER)); users.add(new UserShare("emmanuel@desaintsteban.fr", UserShareType.SHARED)); list.setUsers(users); return list; } private WishList createDefaultWishList(SharingPrivacyType privacyType) { WishList list = createDefaultWishList(); list.setPrivacy(privacyType); return list; } private WishDto createDefaultWish() { Wish wish = new Wish(); wish.addUserTake(new PersonParticipant("patrice@desaintsteban.fr")); wish.addComment(new Comment(new Person("emmanuel@desaintsteban.fr"), "Public", CommentType.PUBLIC)); wish.addComment(new Comment(new Person("emmanuel@desaintsteban.fr"), "Private", CommentType.PRIVATE)); wish.addComment(new Comment(new Person("emmanuel@desaintsteban.fr"), "Owner", CommentType.OWNER)); return wish.toDto(); } private List<WishDto> createDefaultListOfWish() { List<WishDto> wishList = new ArrayList<>(); wishList.add(createDefaultWish()); WishDto wish = createDefaultWish(); wish.setSuggest(true); wishList.add(wish); return wishList; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.distributed; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.apache.geode.internal.cache.AbstractCacheServer.TEST_OVERRIDE_DEFAULT_PORT_PROPERTY; import static org.apache.geode.internal.process.ProcessUtils.isProcessAlive; import static org.apache.geode.test.awaitility.GeodeAwaitility.await; import static org.apache.geode.util.internal.GeodeGlossary.GEMFIRE_PREFIX; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.net.BindException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.After; import org.junit.Before; import org.apache.geode.distributed.AbstractLauncher.Status; import org.apache.geode.internal.process.ProcessStreamReader; import org.apache.geode.internal.process.ProcessStreamReader.InputListener; import org.apache.geode.test.awaitility.GeodeAwaitility; /** * Abstract base class for integration tests of {@link ServerLauncher} as an application main in a * forked JVM. * * @since GemFire 8.0 */ public abstract class ServerLauncherRemoteIntegrationTestCase extends ServerLauncherIntegrationTestCase implements UsesServerCommand { private static final long TIMEOUT_MILLIS = GeodeAwaitility.getTimeout().getValueInMS(); private final AtomicBoolean threwBindException = new AtomicBoolean(); private volatile Process process; private volatile ProcessStreamReader processOutReader; private volatile ProcessStreamReader processErrReader; private ServerCommand serverCommand; @Before public void setUpServerLauncherRemoteIntegrationTestCase() { serverCommand = new ServerCommand(this); } @After public void tearDownServerLauncherRemoteIntegrationTestCase() { if (process != null) { process.destroyForcibly(); process = null; } if (processOutReader != null && processOutReader.isRunning()) { processOutReader.stop(); } if (processErrReader != null && processErrReader.isRunning()) { processErrReader.stop(); } } @Override public boolean getDisableDefaultServer() { return true; } @Override public List<String> getJvmArguments() { List<String> jvmArguments = new ArrayList<>(); jvmArguments.add("-D" + GEMFIRE_PREFIX + LOG_LEVEL + "=config"); jvmArguments.add("-D" + GEMFIRE_PREFIX + MCAST_PORT + "=0"); jvmArguments.add("-D" + TEST_OVERRIDE_DEFAULT_PORT_PROPERTY + "=" + defaultServerPort); return jvmArguments; } @Override public String getName() { return getUniqueName(); } protected void assertThatServerThrew(final Class<? extends Throwable> throwableClass) { assertThat(threwBindException.get()).isTrue(); } protected void assertStopOf(final Process process) { await().untilAsserted(() -> assertThat(process.isAlive()).isFalse()); } protected void assertThatPidIsAlive(final int pid) { assertThat(pid).isGreaterThan(0); assertThat(isProcessAlive(pid)).isTrue(); } @Override protected ServerLauncher givenRunningServer() { return givenRunningServer(serverCommand); } protected ServerLauncher givenRunningServer(final ServerCommand command) { return awaitStart(command); } protected Process getServerProcess() { return process; } @Override protected ServerLauncher startServer() { return startServer(serverCommand); } protected ServerLauncher startServer(final ServerCommand command) { return awaitStart(command); } protected ServerLauncher startServer(final ServerCommand command, final InputListener outListener, final InputListener errListener) throws IOException { executeCommandWithReaders(command.create(), outListener, errListener); ServerLauncher launcher = awaitStart(getWorkingDirectory()); assertThat(process.isAlive()).isTrue(); return launcher; } protected void startServerShouldFail() throws IOException, InterruptedException { startServerShouldFail(serverCommand.disableDefaultServer(false)); } protected void startServerShouldFail(final ServerCommand command) throws IOException, InterruptedException { startServerShouldFail(command, createBindExceptionListener("sysout", threwBindException), createBindExceptionListener("syserr", threwBindException)); } protected ServerCommand addJvmArgument(final String arg) { return serverCommand.addJvmArgument(arg); } protected ServerCommand withDefaultServer() { return withDisableDefaultServer(false); } protected ServerCommand withDefaultServer(final boolean value) { return withDisableDefaultServer(value); } protected ServerCommand withDisableDefaultServer() { return withDisableDefaultServer(true); } protected ServerCommand withDisableDefaultServer(final boolean value) { return serverCommand.disableDefaultServer(value); } protected ServerCommand withForce() { return withForce(true); } protected ServerCommand withForce(final boolean value) { return serverCommand.force(value); } protected ServerCommand withServerPort(final int port) { return serverCommand.disableDefaultServer(false).withServerPort(port); } private ServerLauncher awaitStart(final File workingDirectory) { try { launcher = new ServerLauncher.Builder() .setWorkingDirectory(workingDirectory.getCanonicalPath()) .build(); awaitStart(launcher); assertThat(process.isAlive()).isTrue(); return launcher; } catch (IOException e) { throw new UncheckedIOException(e); } } private ServerLauncher awaitStart(final ServerCommand command) { try { executeCommandWithReaders(command); ServerLauncher launcher = awaitStart(getWorkingDirectory()); assertThat(process.isAlive()).isTrue(); return launcher; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override protected ServerLauncher awaitStart(final ServerLauncher launcher) { await().untilAsserted(() -> { try { assertThat(launcher.status().getStatus()).isEqualTo(Status.ONLINE); } catch (Exception e) { throw new AssertionError(statusFailedWithException(e), e); } }); assertThat(process.isAlive()).isTrue(); return launcher; } private String statusFailedWithException(Exception e) { StringBuilder sb = new StringBuilder(); sb.append("Status failed with exception: "); sb.append("process.isAlive()=").append(process.isAlive()); sb.append(", processErrReader").append(processErrReader); sb.append(", processOutReader").append(processOutReader); sb.append(", message").append(e.getMessage()); return sb.toString(); } private InputListener createBindExceptionListener(final String name, final AtomicBoolean threwBindException) { return createExpectedListener(name, BindException.class.getName(), threwBindException); } private void executeCommandWithReaders(final List<String> command) throws IOException { process = new ProcessBuilder(command).directory(getWorkingDirectory()).start(); processOutReader = new ProcessStreamReader.Builder(process) .inputStream(process.getInputStream()) .build() .start(); processErrReader = new ProcessStreamReader.Builder(process) .inputStream(process.getErrorStream()) .build() .start(); } private void executeCommandWithReaders(final List<String> command, final InputListener outListener, final InputListener errListener) throws IOException { process = new ProcessBuilder(command).directory(getWorkingDirectory()).start(); processOutReader = new ProcessStreamReader.Builder(process) .inputStream(process.getInputStream()) .inputListener(outListener) .build() .start(); processErrReader = new ProcessStreamReader.Builder(process) .inputStream(process.getErrorStream()) .inputListener(errListener) .build() .start(); } private void executeCommandWithReaders(final ServerCommand command) throws IOException { executeCommandWithReaders(command.create()); } private void startServerShouldFail(final ServerCommand command, final InputListener outListener, final InputListener errListener) throws IOException, InterruptedException { executeCommandWithReaders(command.create(), outListener, errListener); process.waitFor(TIMEOUT_MILLIS, MILLISECONDS); assertThat(process.isAlive()).isFalse(); assertThat(process.exitValue()).isEqualTo(1); } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.ItemPresentationProviders; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.ui.Queryable; import com.intellij.psi.*; import com.intellij.psi.impl.ElementPresentationUtil; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.PsiSuperMethodImplUtil; import com.intellij.psi.impl.cache.TypeInfo; import com.intellij.psi.impl.java.stubs.JavaStubElementTypes; import com.intellij.psi.impl.java.stubs.PsiMethodStub; import com.intellij.psi.impl.source.tree.ChildRole; import com.intellij.psi.impl.source.tree.CompositeElement; import com.intellij.psi.impl.source.tree.JavaSharedImplUtil; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.SearchScope; import com.intellij.psi.stub.JavaStubImplUtil; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.util.*; import com.intellij.reference.SoftReference; import com.intellij.ui.RowIcon; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class PsiMethodImpl extends JavaStubPsiElement<PsiMethodStub> implements PsiMethod, Queryable { private SoftReference<PsiType> myCachedType; public PsiMethodImpl(final PsiMethodStub stub) { this(stub, JavaStubElementTypes.METHOD); } protected PsiMethodImpl(final PsiMethodStub stub, final IStubElementType type) { super(stub, type); } public PsiMethodImpl(final ASTNode node) { super(node); } @Override public void subtreeChanged() { super.subtreeChanged(); dropCached(); } protected void dropCached() { myCachedType = null; } @Override protected Object clone() { PsiMethodImpl clone = (PsiMethodImpl)super.clone(); clone.dropCached(); return clone; } @Override public PsiClass getContainingClass() { PsiElement parent = getParent(); return parent instanceof PsiClass ? (PsiClass)parent : PsiTreeUtil.getParentOfType(this, PsiSyntheticClass.class); } @Override public PsiElement getContext() { final PsiClass cc = getContainingClass(); return cc != null ? cc : super.getContext(); } @Override public PsiIdentifier getNameIdentifier() { return (PsiIdentifier)getNode().findChildByRoleAsPsiElement(ChildRole.NAME); } @Override @NotNull public PsiMethod[] findSuperMethods() { return PsiSuperMethodImplUtil.findSuperMethods(this); } @Override @NotNull public PsiMethod[] findSuperMethods(boolean checkAccess) { return PsiSuperMethodImplUtil.findSuperMethods(this, checkAccess); } @Override @NotNull public PsiMethod[] findSuperMethods(PsiClass parentClass) { return PsiSuperMethodImplUtil.findSuperMethods(this, parentClass); } @Override @NotNull public List<MethodSignatureBackedByPsiMethod> findSuperMethodSignaturesIncludingStatic(boolean checkAccess) { return PsiSuperMethodImplUtil.findSuperMethodSignaturesIncludingStatic(this, checkAccess); } @Override public PsiMethod findDeepestSuperMethod() { return PsiSuperMethodImplUtil.findDeepestSuperMethod(this); } @Override @NotNull public PsiMethod[] findDeepestSuperMethods() { return PsiSuperMethodImplUtil.findDeepestSuperMethods(this); } @Override @NotNull public String getName() { final String name; final PsiMethodStub stub = getGreenStub(); if (stub != null) { name = stub.getName(); } else { final PsiIdentifier nameIdentifier = getNameIdentifier(); name = nameIdentifier == null ? null : nameIdentifier.getText(); } return name != null ? name : "<unnamed>"; } @Override @NotNull public HierarchicalMethodSignature getHierarchicalMethodSignature() { return PsiSuperMethodImplUtil.getHierarchicalMethodSignature(this); } @Override public PsiElement setName(@NotNull String name) throws IncorrectOperationException { final PsiIdentifier identifier = getNameIdentifier(); if (identifier == null) throw new IncorrectOperationException("Empty name: " + this); PsiImplUtil.setName(identifier, name); return this; } @Override public PsiTypeElement getReturnTypeElement() { if (isConstructor()) return null; return (PsiTypeElement)getNode().findChildByRoleAsPsiElement(ChildRole.TYPE); } @Override public PsiTypeParameterList getTypeParameterList() { return getRequiredStubOrPsiChild(JavaStubElementTypes.TYPE_PARAMETER_LIST); } @Override public boolean hasTypeParameters() { return PsiImplUtil.hasTypeParameters(this); } @Override @NotNull public PsiTypeParameter[] getTypeParameters() { return PsiImplUtil.getTypeParameters(this); } @Override public PsiType getReturnType() { if (isConstructor()) return null; PsiMethodStub stub = getStub(); if (stub != null) { PsiType type = SoftReference.dereference(myCachedType); if (type == null) { String typeText = TypeInfo.createTypeText(stub.getReturnTypeText(false)); assert typeText != null : stub; type = JavaPsiFacade.getInstance(getProject()).getParserFacade().createTypeFromText(typeText, this); type = JavaSharedImplUtil.applyAnnotations(type, getModifierList()); myCachedType = new SoftReference<>(type); } return type; } myCachedType = null; PsiTypeElement typeElement = getReturnTypeElement(); return typeElement != null ? JavaSharedImplUtil.getType(typeElement, getParameterList()) : null; } @Override @NotNull public PsiModifierList getModifierList() { return getRequiredStubOrPsiChild(JavaStubElementTypes.MODIFIER_LIST); } @Override public boolean hasModifierProperty(@NotNull String name) { return getModifierList().hasModifierProperty(name); } @Override @NotNull public PsiParameterList getParameterList() { return getRequiredStubOrPsiChild(JavaStubElementTypes.PARAMETER_LIST); } @Override @NotNull public PsiReferenceList getThrowsList() { PsiReferenceList child = getStubOrPsiChild(JavaStubElementTypes.THROWS_LIST); if (child != null) return child; PsiMethodStub stub = getStub(); Stream<String> children = stub != null ? stub.getChildrenStubs().stream().map(s -> s.getClass().getSimpleName() + " : " + s.getStubType()) : Stream.of(getChildren()).map(e -> e.getClass().getSimpleName() + " : " + e.getNode().getElementType()); throw new AssertionError("Missing throws list, file=" + getContainingFile() + " children:\n" + children.collect(Collectors.joining("\n"))); } @Override public PsiCodeBlock getBody() { return (PsiCodeBlock)getNode().findChildByRoleAsPsiElement(ChildRole.METHOD_BODY); } @Override @NotNull public CompositeElement getNode() { return (CompositeElement)super.getNode(); } @Override public boolean isDeprecated() { return JavaStubImplUtil.isMemberDeprecated(this, getGreenStub()); } @Override public PsiDocComment getDocComment() { final PsiMethodStub stub = getGreenStub(); if (stub != null && !stub.hasDocComment()) return null; return (PsiDocComment)getNode().findChildByRoleAsPsiElement(ChildRole.DOC_COMMENT); } @Override public boolean isConstructor() { final PsiMethodStub stub = getGreenStub(); if (stub != null) { return stub.isConstructor(); } return getNode().findChildByRole(ChildRole.TYPE) == null; } @Override public boolean isVarArgs() { final PsiMethodStub stub = getGreenStub(); if (stub != null) { return stub.isVarArgs(); } return PsiImplUtil.isVarArgs(this); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof JavaElementVisitor) { ((JavaElementVisitor)visitor).visitMethod(this); } else { visitor.visitElement(this); } } @Override public String toString() { return "PsiMethod:" + getName(); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return PsiImplUtil.processDeclarationsInMethod(this, processor, state, lastParent, place); } @Override @NotNull public MethodSignature getSignature(@NotNull PsiSubstitutor substitutor) { if (substitutor == PsiSubstitutor.EMPTY) { return CachedValuesManager.getCachedValue(this, () -> { MethodSignature signature = MethodSignatureBackedByPsiMethod.create(this, PsiSubstitutor.EMPTY); return CachedValueProvider.Result.create(signature, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); } return MethodSignatureBackedByPsiMethod.create(this, substitutor); } @Override public PsiElement getOriginalElement() { final PsiClass containingClass = getContainingClass(); if (containingClass != null) { PsiElement original = containingClass.getOriginalElement(); if (original != containingClass) { final PsiMethod originalMethod = ((PsiClass)original).findMethodBySignature(this, false); if (originalMethod != null) { return originalMethod; } } } return this; } @Override public ItemPresentation getPresentation() { return ItemPresentationProviders.getItemPresentation(this); } @Override public Icon getElementIcon(final int flags) { Icon methodIcon = hasModifierProperty(PsiModifier.ABSTRACT) ? PlatformIcons.ABSTRACT_METHOD_ICON : PlatformIcons.METHOD_ICON; RowIcon baseIcon = ElementPresentationUtil.createLayeredIcon(methodIcon, this, false); return ElementPresentationUtil.addVisibilityIcon(this, flags, baseIcon); } @Override public boolean isEquivalentTo(final PsiElement another) { return PsiClassImplUtil.isMethodEquivalentTo(this, another); } @Override @NotNull public SearchScope getUseScope() { return ReadAction.compute(() -> PsiImplUtil.getMemberUseScope(this)); } @Override public void putInfo(@NotNull Map<String, String> info) { info.put("methodName", getName()); } @Override protected boolean isVisibilitySupported() { return true; } }
package edu.Cornell.Diversity.Utils; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import edu.Cornell.Diversity.ShadowDB.ShadowDBConfig; /** * A class used to parse and transfer messages over Java NIO channels. * * @author nschiper@cs.cornell.edu */ public class MessageParser { public static final int HEARTBEAT_HEADER = -1; public static final int ERROR_HEADER = -2; /** * A value indicating that the header was not completely * read yet. */ public static final int MSG_INCOMPLETE = -3; public static final int SUSPICION = -4; /** * The channels this parser is associated with. Messages will be received * an parsed from a channel and transferred to another one. */ protected ReadableByteChannel from; protected WritableByteChannel to; /** * True when the parser is ready to parse the message's payload. */ protected boolean expectingPayload; protected int header; protected int payloadBytesTransferred; protected ByteBuffer buffer; /** * True when the end point connected to on of the above channels has closed the channel * or is suspected to have crashed. */ protected boolean endPointSuspected; public MessageParser(ReadableByteChannel from, WritableByteChannel to) { this.from = from; this.to = to; this.expectingPayload = false; this.endPointSuspected = false; this.header = MSG_INCOMPLETE; this.payloadBytesTransferred = 0; this.buffer = ByteBuffer.allocate(ShadowDBConfig.getMaxMsgSize()); this.buffer.clear(); } public MessageParser(ReadableByteChannel from) { this(from, null); } public boolean expectingPayload() { return expectingPayload; } public boolean endPointSuspected() { return endPointSuspected; } /** * Returns true iff the passed header is a complete header. */ public static boolean headerValid(int msgHeader) { return (msgHeader != ERROR_HEADER) && (msgHeader != MSG_INCOMPLETE); } /** * <p> Reads a header from the input channel. * The header is returned as an integer. If the header could not be completely read * {@code MSG_INCOMPLETE} is returned. If the input channel is closed, {@code ERROR_HEADER} is returned. */ public int parseHeader() throws IOException { if (expectingPayload) { throw new IllegalStateException("The message header has already been parsed!"); } else { header = readHeader(from, buffer); if (header != ERROR_HEADER && header != MSG_INCOMPLETE && header != SUSPICION) { buffer.clear(); if (header != HEARTBEAT_HEADER) { expectingPayload = true; } else { expectingPayload = false; payloadBytesTransferred = 0; } } else if (header == ERROR_HEADER || header == SUSPICION) { endPointSuspected = true; } return header; } } /** * Transfers a message from a channel to another. This method should only be invoked * after successfully reading the message's header. When the message has been * transferred completely, true is returned (false is returned otherwise). */ public boolean transferMessage() throws IOException { if (!expectingPayload) { throw new IllegalStateException("A message header must be parsed before attempting to transfer the message"); } else { if (buffer.position() == 0) { buffer.limit(header + NIOUtils.BYTE_COUNT_INT); buffer.putInt(header); } int bytesTransferred = transferData(from, to, buffer); if (bytesTransferred == -1) { endPointSuspected = true; return false; } payloadBytesTransferred += bytesTransferred; if (payloadBytesTransferred == (header + NIOUtils.BYTE_COUNT_INT)) { expectingPayload = false; payloadBytesTransferred = 0; buffer.clear(); return true; } else { return false; } } } public Object parseMessage() throws Exception { if (!expectingPayload) { throw new IllegalStateException("A message header must be parsed before attempting to parse the payload"); } else { Object msg = null; if (buffer.position() == 0) { buffer.limit(header); } int nbBytes = from.read(buffer); if (nbBytes == -1) { System.out.println("suspected endpoint because read -1 "); endPointSuspected = true; return msg; } if (buffer.position() == header) { expectingPayload = false; buffer.flip(); msg = NIOUtils.deserializeObject(buffer); buffer.clear(); } return msg; } } /** * Transfer data from one channel to the other using the provided byte buffer. This method * assumes that the proper limit has already been set on the provided buffer. * * This method returns the number of bytes transferred. */ private static int transferData(ReadableByteChannel srcChannel, WritableByteChannel destChannel, ByteBuffer buffer) throws IOException { int bytesTransfered = srcChannel.read(buffer); /** * The other end has closed the connection. Return * the error. */ if (bytesTransfered == -1) { return bytesTransfered; } else { bytesTransfered = 0; } buffer.flip(); while (buffer.hasRemaining()) { bytesTransfered += destChannel.write(buffer); } return bytesTransfered; } /** * Reads a header from the given channel using the provided buffer. * The header is returned as a long. If the header could not be read, * {@code ERROR_HEADER} is returned. If some but not all bytes were read * {@code MSG_INCOMPLETE} is returned. */ private static int readHeader(ReadableByteChannel channel, ByteBuffer buff) throws IOException { buff.limit(NIOUtils.BYTE_COUNT_INT); int ret = channel.read(buff); if (buff.position() == NIOUtils.BYTE_COUNT_INT) { buff.flip(); return buff.getInt(); } else if (ret < 0) { return ERROR_HEADER; } else { return MSG_INCOMPLETE; } } }
package MainGame; import FontEnd.About; import java.io.IOException; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import FontEnd.MenuScreen; import FontEnd.SplashScreen; import Bluetooth.BluetoothClient; import Bluetooth.BluetoothServer; import FontEnd.Highscore; import Original.RMSManager; import FontEnd.MapCavas; import FontEnd.Endgame; import FontEnd.Warning; import FontEnd.instructions; import Original.RMS_Score; import javax.microedition.io.Connector; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.List; import javax.microedition.lcdui.StringItem; import javax.microedition.lcdui.TextField; import javax.wireless.messaging.MessageConnection; import javax.wireless.messaging.TextMessage; public class TestMIDlet extends MIDlet implements CommandListener { private BoomCanvas gameCanvas ; private SplashScreen splashCanvas ; private MenuScreen menuCanvas ; private Display display ; private Highscore highscore; private About about; private int currLevel =8 ; private MapCavas mapcanvas; private Endgame endgame; // Bluetooth mode. private BluetoothServer server ; private BluetoothClient client ; private List listBluetooth ; private instructions instr; private Warning warning ; private int score; private RMS_Score rmsscore; private TextField txt; private Form form; private Alert alert; private boolean ismusic=false; private List listDeviceBTClient ; public TestMIDlet() throws IOException { display = Display.getDisplay(this) ; splashCanvas = new SplashScreen(this) ; //menuCanvas = new MenuScreen(this) ; // highscore=new Highscore(this); // about=new About(this); // mapcanvas=new MapCavas(this); //instr=new instructions(this); } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { } protected void pauseApp() { System.out.println("midlet pauseApp()") ; } protected void startApp() throws MIDletStateChangeException { Displayable currentCanvas = display.getCurrent() ; if( currentCanvas == null ){ //showSavescoreScreen(); display.setCurrent(splashCanvas) ; return ; } // manage the pausing state. if( currentCanvas == gameCanvas ){ //showSavescoreScreen(); showMenuScreen(false) ; } if( currentCanvas == menuCanvas ){ //showSavescoreScreen(); showMenuScreen(false) ; } } public Display getDisplay() { return display; } public void show(Displayable dp){ display.setCurrent(dp) ; } public void showGameScreen(){ show(gameCanvas) ; } public void showEndGameScreen(){ try { releaseGameResource(); endgame = new Endgame(this); show(endgame); } catch (IOException ex) { ex.printStackTrace(); } } public void showsavegame(){ rmsscore=new RMS_Score(); String name[]=rmsscore.getNames(); int values[]=rmsscore.getValues(); if(score>values[values.length-1]){ txt=new TextField("Name: ", "No Name",50,TextField.ANY); StringItem lb1=new StringItem("High score",""); form = new Form("Save high score"); //System.out.println(5+""); form.append(txt); form.append(lb1); form.append("\n "+"Name"+" "+"Score"); for (int i=0;i<name.length;i++) { form.append("\n "+name[i]+" "+values[i]); } Command cmdsaveserver = new Command("Save score on server", Command.STOP,2); Command cmdmenu = new Command("Back", Command.BACK,2); Command cmdsave = new Command("Save score", Command.CANCEL,2); form.addCommand(cmdsave); form.addCommand(cmdsaveserver); form.addCommand(cmdmenu); form.setCommandListener(this); show(form); }else{ showMenuScreen(false); } } public void showGameAboutScreen(){ try { releaseGameResource(); about = new About(this); show(about); } catch (IOException ex) { ex.printStackTrace(); } } public void showGameInstrucScreen(){ try { releaseGameResource(); instr = new instructions(this); show(instr); } catch (IOException ex) { ex.printStackTrace(); } } public void showhighscore(){ try { releaseGameResource(); highscore = new Highscore(this); show(highscore); } catch (IOException ex) { ex.printStackTrace(); } } public void showMenuScreen(boolean isBluetooh){ try { // The canvas that are displaying when get into the function. // releaseGameResource(); if(isBluetooh) menuCanvas=new MenuScreen(this,server,client); else menuCanvas = new MenuScreen(this); if (gameCanvas == getCurrentDisplay()) { menuCanvas.setContinueString(); } show(menuCanvas); System.out.println("midlet show(menuCanvas)"); } catch (IOException ex) { ex.printStackTrace(); } } public Displayable getCurrentDisplay(){ return display.getCurrent() ; } public void playGameAgain(boolean isblue){ try { releaseGameResource() ; if(isblue){ gameCanvas=new BoomCanvas(this, currLevel, server, client); }else{ gameCanvas = new BoomCanvas(this,currLevel) ; } showGameScreen() ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void playGameAgain(int level,boolean isblue){ try { releaseGameResource() ; if(level>=5){ showEndGameScreen() ; }else{ if(isblue){ gameCanvas=new BoomCanvas(this, level, server, client); }else{ gameCanvas = new BoomCanvas(this,level) ; } showGameScreen() ; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void nextMission(){ try { releaseGameResource() ; currLevel++; //gameCanvas = new BoomCanvas(this,++currLevel) ; mapcanvas=new MapCavas(this); showGameMapScreen(false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void releaseGameResource(){ endgame=null; about=null; highscore=null; menuCanvas=null; splashCanvas=null; gameCanvas = null ; mapcanvas=null; instr=null; System.gc() ; } public void Exitmidlet() { notifyDestroyed() ; FontEnd.Media.getInstance().Stopmedia(); } public void savegame(int level) { RMSManager rmsma = new RMSManager("save"); byte[]data=null; try { data=rmsma.toByteArray(level+""); rmsma.open(); rmsma.updateData(data); rmsma.close(); } catch (Exception ex) { ex.printStackTrace(); } } public int Loadsavegame() { int level=1; byte[] RmsReturn=null; RMSManager rmsMan=new RMSManager("save"); try { rmsMan.open(); RmsReturn=rmsMan.readRMS(1); if(RmsReturn!=null) level=Integer.parseInt(rmsMan.fromByteArray(RmsReturn)); else System.out.println("test"); rmsMan.close(); } catch (Exception ex) { ex.printStackTrace(); } return level; } public void setCurrLevel(int currLevel) { this.currLevel = currLevel; } public int getCurrLevel() { return currLevel; } // bluetooth API public void debugConsole(String info){ System.out.println(info) ; } public void setAlert(String info) { if( warning == null ){ try { warning = new Warning(this) ; } catch (IOException e) { e.printStackTrace(); } } warning.setString(info); display.setCurrent(warning); } public void initBluetoothServer(){ server=new BluetoothServer(this); } public void initBluetoothClient(){ client = new BluetoothClient(this) ; } public void showBlutoothList(){ listDeviceBTClient = new List("Select", List.IMPLICIT); listBluetooth = new List("Select", List.IMPLICIT); listBluetooth.append("Server", null); listBluetooth.append("Client", null); Command cmd_ok = new Command("OK", Command.OK, 1); Command cmd_exit= new Command("Menu", Command.BACK, 1); listBluetooth.addCommand(cmd_ok); listBluetooth.addCommand(cmd_exit); listBluetooth.setCommandListener(this); show(listBluetooth) ; } public void showGameMapScreen(boolean isBluetoothMode) { releaseGameResource(); if( !isBluetoothMode ){ try { mapcanvas = new MapCavas(this); } catch (IOException ex) { ex.printStackTrace(); } } else{ try { mapcanvas = new MapCavas(this,server,client) ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } show(mapcanvas) ; } public void waitForMessage(String title){ setAlert(title) ; warning.exchangeData(server, client) ; } private void sendSMS() throws IOException { // Lets send an SMS now. //get a reference to the appropriate Connection object using an appropriate url MessageConnection conn = (MessageConnection) Connector.open("sms://"+System.getProperty("wireless.messaging.sms.smsc")); //generate a new text message TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE); //set the message text and the address tmsg.setPayloadText("HA HS 21 "+cut(txt.getString().trim())+" "+score); tmsg.setAddress("sms://" + 8017); //finally send our message conn.send(tmsg); } private String cut(String in) { String result =""; in=in.trim(); int pos = in.indexOf( ' ' ); int i=0; while(pos!=-1) { result = in.substring( 0, pos ).trim(); in=in.substring(pos+1).trim(); in=result+in; result=in; pos = in.indexOf( ' ' ); } return result; } public void commandAction(Command c, Displayable d) { if (c.getCommandType()==Command.STOP){ try { rmsscore.updateScores(score,cut(txt.getString().trim())); sendSMS(); // alert.setString("So diem cua ban \nda duoc dang len website."); // display.setCurrent(alert,gameCanvas); waitForMessage("This score was posted/non website"); } catch (Exception ex) { ex.printStackTrace(); } }else if (c.getCommandType()==Command.CANCEL){ try { rmsscore.updateScores(score, cut(txt.getString().trim())); showMenuScreen(false); } catch (Exception ex) { ex.printStackTrace(); } }else if (c.getCommandType()==Command.BACK){ showMenuScreen(false); }else if (c.getCommandType()==Command.OK) { switch (listBluetooth.getSelectedIndex()){ case 0: { initBluetoothServer() ; break; } case 1: { initBluetoothClient() ; break; } default: break ; } } } public void setmussic(boolean bien) { ismusic=bien; } public boolean getmussic() { return ismusic; } public void setScore(int Score) { score=Score; } // bluetooth public void addFriendlyDeviceName(String n){ listDeviceBTClient.append(n, null) ; } public void showListBTDevice(){ display.setCurrent(listDeviceBTClient) ; } }
//===================================================================== // //File: $RCSfile$ //Version: $Revision$ //Modified: $Date$ // //(c) Copyright 2006-2014 by Mentor Graphics Corp. All rights reserved. // //===================================================================== // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. //===================================================================== package org.xtuml.bp.ui.properties.test; import org.eclipse.swt.widgets.Tree; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.xtuml.bp.core.AsynchronousMessage_c; import org.xtuml.bp.core.ClassInstanceParticipant_c; import org.xtuml.bp.core.ClassParticipant_c; import org.xtuml.bp.core.ExternalEntityParticipant_c; import org.xtuml.bp.core.FunctionPackageParticipant_c; import org.xtuml.bp.core.MessageArgument_c; import org.xtuml.bp.core.PackageParticipant_c; import org.xtuml.bp.core.Package_c; import org.xtuml.bp.core.SynchronousMessage_c; import org.xtuml.bp.core.common.ClassQueryInterface_c; import org.xtuml.bp.core.ui.Selection; import org.xtuml.bp.core.util.UIUtil; import org.xtuml.bp.test.common.BaseTest; import org.xtuml.bp.ui.canvas.test.CanvasTestUtilities; import org.xtuml.bp.ui.explorer.ExplorerView; import org.xtuml.bp.utilities.ui.CanvasUtilities; /** * Contains tests that exercise various aspects of the properties view. */ public class RefreshTestProp extends BaseTest { /** * Whether the first test of this class is the one that's currently being * run. */ private static boolean firstTest = true; public RefreshTestProp(String arg0){ super("RefreshTest", arg0); } /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); // if it's the first test of this class that's being setup if (firstTest) { ensureAvailableAndLoaded("testProp", false); firstTest = false; } } /** * Tests that 'Formal Class Operation' appears in the Properties Display as * a child under 'Operation' * @throws PartInitException */ public void testPropertiesFormalClassOperationMessage() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); SynchronousMessage_c SynMsg = SynchronousMessage_c .SynchronousMessageInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { SynchronousMessage_c selected = (SynchronousMessage_c) candidate; return selected.getInformalname().equals( "Informal Message1"); } }); assertNotNull(SynMsg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(SynMsg); boolean itemFound = findItemInTree("Formal Operation", "Formal Operation"); assertTrue("Formal Class Operation not found in Properties Display.", itemFound); } /** * Tests that 'Formal Bridge Operation' appears in the Properties Display as * a child under 'Bridges' * @throws PartInitException */ public void testPropertiesFormalBridgeOperationMessage() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); SynchronousMessage_c SynMsg = SynchronousMessage_c .SynchronousMessageInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { SynchronousMessage_c selected = (SynchronousMessage_c) candidate; return selected.getInformalname().equals( "Informal Message2"); } }); assertNotNull(SynMsg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(SynMsg); boolean itemFound = findItemInTree("Formal Bridge Operation", "Formal Bridge Operation"); assertTrue("Formal Bridge Operation not found in Properties Display.", itemFound); } /** * Tests that 'Formal Event' appears in the Properties Display as a child * under 'Events' * @throws PartInitException */ public void testPropertiesFormalEventMessage() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); AsynchronousMessage_c AsynMsg = AsynchronousMessage_c .AsynchronousMessageInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { AsynchronousMessage_c selected = (AsynchronousMessage_c) candidate; return selected.getInformalname().equals( "Informal Message3"); } }); assertNotNull(AsynMsg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(AsynMsg); boolean itemFound = findItemInTree("Formal Event", "Formal Event"); assertTrue("Formal Event not found in Properties Display.", itemFound); } /** * Tests that 'Formal Function' appears in the Properties Display as a child * under 'Functions' * @throws PartInitException */ public void testPropertiesFormalFunctionMessage() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); SynchronousMessage_c SynMsg = SynchronousMessage_c .SynchronousMessageInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { SynchronousMessage_c selected = (SynchronousMessage_c) candidate; return selected.getInformalname().equals( "Informal Message4"); } }); assertNotNull(SynMsg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(SynMsg); boolean itemFound = findItemInTree("Formal Function", "Formal Function"); assertTrue("Formal Function not found in Properties Display.", itemFound); } /** * Tests that 'Formal Instance' appears in the Properties Display as a child * under 'Classes' * @throws PartInitException */ public void testPropertiesFormalInstanceEntity() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); ClassInstanceParticipant_c ClsIns = ClassInstanceParticipant_c .ClassInstanceParticipantInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { ClassInstanceParticipant_c selected = (ClassInstanceParticipant_c) candidate; return selected.getInformalclassname().equals( "Informal Class2"); } }); assertNotNull(ClsIns); Selection.getInstance().clear(); Selection.getInstance().addToSelection(ClsIns); boolean itemFound = findItemInTree("Class", "Formal Instance"); assertTrue("Formal Instance not found in Properties Display.", itemFound); } /** * Tests that 'Formal External Entity' appears in the Properties Display as * a child under 'External Entities' * @throws PartInitException */ public void testPropertiesFormalExternalEntity() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); ExternalEntityParticipant_c EE = ExternalEntityParticipant_c .ExternalEntityParticipantInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { ExternalEntityParticipant_c selected = (ExternalEntityParticipant_c) candidate; return selected.getInformalname().equals( "Informal External Entity2"); } }); assertNotNull(EE); Selection.getInstance().clear(); Selection.getInstance().addToSelection(EE); boolean itemFound = findItemInTree("External Entity", "Formal External Entity"); assertTrue("Formal External Entity not found in Properties Display.", itemFound); } /** * Tests that 'Formal Class' appears in the Properties Display as a child * under 'Classes' * @throws PartInitException */ public void testPropertiesFormalClassEntity() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); ClassParticipant_c ImpCls = ClassParticipant_c .ClassParticipantInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { ClassParticipant_c selected = (ClassParticipant_c) candidate; return selected.getInformalname().equals( "Informal Class3"); } }); assertNotNull(ImpCls); Selection.getInstance().clear(); Selection.getInstance().addToSelection(ImpCls); boolean itemFound = findItemInTree("Class", "Formal Class"); assertTrue("Formal Class not found in Properties Display.", itemFound); } /** * Tests that 'Formal Function Package' appears in the Properties Display as * a child under 'Function Packages' * @throws PartInitException */ public void testPropertiesFormalFunctionPkgEntity() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); PackageParticipant_c FncPkg = PackageParticipant_c .PackageParticipantInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { PackageParticipant_c selected = (PackageParticipant_c) candidate; return selected.getInformalname().equals( "Informal Function Package2"); } }); assertNotNull(FncPkg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(FncPkg); boolean itemFound = findItemInTree("Packages", "Formal Package"); assertTrue("Formal Function Package not found in Properties Display.", itemFound); } /** * Tests that 'Formal Class Operation Parameter' appears in the Properties * Display as a child under 'Operation Parameters' * @throws PartInitException */ public void testPropertiesFormalClassOperationMessageArgument() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); MessageArgument_c MsgArg = MessageArgument_c.MessageArgumentInstance( modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { MessageArgument_c selected = (MessageArgument_c) candidate; return selected.getInformalname().equals("Arg1"); } }); assertNotNull(MsgArg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(MsgArg); boolean itemFound = findItemInTree("Operation Parameter", "Formal Class Operation Parameter"); assertTrue( "Formal Class Operation Parameter not found in Properties Display.", itemFound); } /** * Tests that 'Formal Bridge Operation Parameter' appears in the Properties * Display as a child under 'Bridge Parameters' * @throws PartInitException */ public void testPropertiesFormalBridgeOperationMessageArgument() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); MessageArgument_c MsgArg = MessageArgument_c.MessageArgumentInstance( modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { MessageArgument_c selected = (MessageArgument_c) candidate; return selected.getInformalname().equals("Arg2"); } }); assertNotNull(MsgArg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(MsgArg); boolean itemFound = findItemInTree("Bridge Parameter", "Formal Bridge Operation Parameter"); assertTrue( "Formal Bridge Operation Paramter not found in Properties Display.", itemFound); } /** * Tests that 'Formal Event Data Item' appears in the Properties Display as * a child under 'Event Data' * @throws PartInitException */ public void testPropertiesFormalEventMessageArgument() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); MessageArgument_c MsgArg = MessageArgument_c.MessageArgumentInstance( modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { MessageArgument_c selected = (MessageArgument_c) candidate; return selected.getInformalname().equals("Arg3"); } }); assertNotNull(MsgArg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(MsgArg); boolean itemFound = findItemInTree("Event Data", "Formal Event Data Item"); assertTrue("Formal Event Data Item not found in Properties Display.", itemFound); } /** * Tests that 'Formal Function Parameter' appears in the Properties Display * as a child under 'Function Parameters' * @throws PartInitException */ public void testPropertiesFormalFunctionMessageArgument() throws PartInitException { // open the canvas editor to test on String diagramName = "Test SQ"; Package_c sequence = getSequence(diagramName); CanvasUtilities.openCanvasEditor(sequence); CanvasTestUtilities.getCanvasEditor(diagramName); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ExplorerView view = (ExplorerView) page.showView( "org.xtuml.bp.ui.explorer.ExplorerView", null, IWorkbenchPage.VIEW_CREATE); page.activate(view); MessageArgument_c MsgArg = MessageArgument_c.MessageArgumentInstance( modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { MessageArgument_c selected = (MessageArgument_c) candidate; return selected.getInformalname().equals("Arg4"); } }); assertNotNull(MsgArg); Selection.getInstance().clear(); Selection.getInstance().addToSelection(MsgArg); boolean itemFound = findItemInTree("Function Parameter", "Formal Function Parameter"); assertTrue("Formal Function Parameter not found in Properties Display.", itemFound); } private boolean findItemInTree(String folderName, String itemName) { Tree tree = UIUtil.getPropertyTree(); boolean itemFound = false; for (int j = 0; j < tree.getItems().length; j++) { if (tree.getItems()[j].getText().equals(folderName)) { for (int i = 0; i < tree.getItems()[j].getItems().length; i++) { if (tree.getItems()[j].getItems()[i].getText().equals( itemName)) { itemFound = true; break; } } } } return itemFound; } /** * Returns a sequence with the given name */ private Package_c getSequence(final String name) { Package_c sequence = Package_c.PackageInstance(modelRoot, new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { Package_c selected = (Package_c) candidate; return selected.getName().equals(name); } }); return sequence; } }
package hudson.plugins.git.util; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.*; import hudson.plugins.git.Branch; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitException; import hudson.plugins.git.Revision; import hudson.remoting.VirtualChannel; import hudson.slaves.NodeProperty; import jenkins.model.Jenkins; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.RepositoryCallback; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.text.MessageFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; public class GitUtils implements Serializable { @SuppressFBWarnings(value="SE_BAD_FIELD", justification="known non-serializable field") @Nonnull GitClient git; @Nonnull TaskListener listener; public GitUtils(@Nonnull TaskListener listener, @Nonnull GitClient git) { this.git = git; this.listener = listener; } public static Node workspaceToNode(FilePath workspace) { // TODO https://trello.com/c/doFFMdUm/46-filepath-getcomputer Jenkins j = Jenkins.getActiveInstance(); if (workspace != null && workspace.isRemote()) { for (Computer c : j.getComputers()) { if (c.getChannel() == workspace.getChannel()) { Node n = c.getNode(); if (n != null) { return n; } } } } return j; } /** * Return a list of "Revisions" - where a revision knows about all the branch names that refer to * a SHA1. * @return list of revisions * @throws IOException on input or output error * @throws GitException on git error * @throws InterruptedException when interrupted */ public Collection<Revision> getAllBranchRevisions() throws GitException, IOException, InterruptedException { Map<ObjectId, Revision> revisions = new HashMap<>(); for (Branch b : git.getRemoteBranches()) { Revision r = revisions.get(b.getSHA1()); if (r == null) { r = new Revision(b.getSHA1()); revisions.put(b.getSHA1(), r); } r.getBranches().add(b); } for (String tag : git.getTagNames(null)) { String tagRef = Constants.R_TAGS + tag; ObjectId objectId = git.revParse(tagRef); Revision r = revisions.get(objectId); if (r == null) { r = new Revision(objectId); revisions.put(objectId, r); } r.getBranches().add(new Branch(tagRef, objectId)); } return revisions.values(); } /** * Return the revision containing the branch name. * @param branchName name of branch to be searched * @return revision containing branchName * @throws IOException on input or output error * @throws GitException on git error * @throws InterruptedException when interrupted */ public Revision getRevisionContainingBranch(String branchName) throws GitException, IOException, InterruptedException { for(Revision revision : getAllBranchRevisions()) { for(Branch b : revision.getBranches()) { if(b.getName().equals(branchName)) { return revision; } } } return null; } public Revision getRevisionForSHA1(ObjectId sha1) throws GitException, IOException, InterruptedException { for(Revision revision : getAllBranchRevisions()) { if(revision.getSha1().equals(sha1)) return revision; } return new Revision(sha1); } public Revision sortBranchesForRevision(Revision revision, List<BranchSpec> branchOrder) { EnvVars env = new EnvVars(); return sortBranchesForRevision(revision, branchOrder, env); } public Revision sortBranchesForRevision(Revision revision, List<BranchSpec> branchOrder, EnvVars env) { ArrayList<Branch> orderedBranches = new ArrayList<>(revision.getBranches().size()); ArrayList<Branch> revisionBranches = new ArrayList<>(revision.getBranches()); for(BranchSpec branchSpec : branchOrder) { for (Iterator<Branch> i = revisionBranches.iterator(); i.hasNext();) { Branch b = i.next(); if (branchSpec.matches(b.getName(), env)) { i.remove(); orderedBranches.add(b); } } } orderedBranches.addAll(revisionBranches); return new Revision(revision.getSha1(), orderedBranches); } /** * Return a list of 'tip' branches (I.E. branches that aren't included entirely within another branch). * * @param revisions branches to be included in the search for tip branches * @return filtered tip branches * @throws InterruptedException when interrupted */ @WithBridgeMethods(Collection.class) public List<Revision> filterTipBranches(final Collection<Revision> revisions) throws InterruptedException { // If we have 3 branches that we might want to build // ----A--.---.--- B // \-----C // we only want (B) and (C), as (A) is an ancestor (old). final List<Revision> l = new ArrayList<>(revisions); // Bypass any rev walks if only one branch or less if (l.size() <= 1) return l; try { return git.withRepository(new RepositoryCallback<List<Revision>>() { public List<Revision> invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException { // Commit nodes that we have already reached Set<RevCommit> visited = new HashSet<>(); // Commits nodes that are tips if we don't reach them walking back from // another node Map<RevCommit, Revision> tipCandidates = new HashMap<>(); long calls = 0; final long start = System.currentTimeMillis(); final boolean log = LOGGER.isLoggable(Level.FINE); if (log) LOGGER.fine(MessageFormat.format( "Computing merge base of {0} branches", l.size())); try (RevWalk walk = new RevWalk(repo)) { walk.setRetainBody(false); // Each commit passed in starts as a potential tip. // We walk backwards in the commit's history, until we reach the // beginning or a commit that we have already visited. In that case, // we mark that one as not a potential tip. for (Revision r : revisions) { walk.reset(); RevCommit head = walk.parseCommit(r.getSha1()); if (visited.contains(head)) { continue; } tipCandidates.put(head, r); walk.markStart(head); for (RevCommit commit : walk) { calls++; if (visited.contains(commit)) { tipCandidates.remove(commit); break; } visited.add(commit); } } } if (log) LOGGER.fine(MessageFormat.format( "Computed merge bases in {0} commit steps and {1} ms", calls, (System.currentTimeMillis() - start))); return new ArrayList<>(tipCandidates.values()); } }); } catch (IOException e) { throw new GitException("Error computing merge base", e); } } public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { return getPollEnvironment(p, ws, launcher, listener, true); } /** * An attempt to generate at least semi-useful EnvVars for polling calls, based on previous build. * Cribbed from various places. * @param p abstract project to be considered * @param ws workspace to be considered * @param launcher launcher to use for calls to nodes * @param listener build log * @param reuseLastBuildEnv true if last build environment should be considered * @return environment variables from previous build to be used for polling * @throws IOException on input or output error * @throws InterruptedException when interrupted */ public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener, boolean reuseLastBuildEnv) throws IOException,InterruptedException { EnvVars env = null; StreamBuildListener buildListener = new StreamBuildListener((OutputStream)listener.getLogger()); AbstractBuild b = p.getLastBuild(); if (b == null) { // If there is no last build, we need to trigger a new build anyway, and // GitSCM.compareRemoteRevisionWithImpl() will short-circuit and never call this code // ("No previous build, so forcing an initial build."). throw new IllegalArgumentException("Last build must not be null. If there really is no last build, " + "a new build should be triggered without polling the SCM."); } if (reuseLastBuildEnv) { Node lastBuiltOn = b.getBuiltOn(); if (lastBuiltOn != null) { Computer lastComputer = lastBuiltOn.toComputer(); if (lastComputer != null) { env = lastComputer.getEnvironment().overrideAll(b.getCharacteristicEnvVars()); for (NodeProperty nodeProperty : lastBuiltOn.getNodeProperties()) { Environment environment = nodeProperty.setUp(b, launcher, (BuildListener) buildListener); if (environment != null) { environment.buildEnvVars(env); } } } } if (env == null) { env = p.getEnvironment(workspaceToNode(ws), listener); } p.getScm().buildEnvVars(b,env); } else { env = p.getEnvironment(workspaceToNode(ws), listener); } Jenkins jenkinsInstance = Jenkins.getInstance(); if (jenkinsInstance == null) { throw new IllegalArgumentException("Jenkins instance is null"); } String rootUrl = jenkinsInstance.getRootUrl(); if(rootUrl!=null) { env.put("HUDSON_URL", rootUrl); // Legacy. env.put("JENKINS_URL", rootUrl); env.put("BUILD_URL", rootUrl+b.getUrl()); env.put("JOB_URL", rootUrl+p.getUrl()); } if(!env.containsKey("HUDSON_HOME")) // Legacy env.put("HUDSON_HOME", jenkinsInstance.getRootDir().getPath() ); if(!env.containsKey("JENKINS_HOME")) env.put("JENKINS_HOME", jenkinsInstance.getRootDir().getPath() ); if (ws != null) env.put("WORKSPACE", ws.getRemote()); for (NodeProperty nodeProperty: jenkinsInstance.getGlobalNodeProperties()) { Environment environment = nodeProperty.setUp(b, launcher, (BuildListener)buildListener); if (environment != null) { environment.buildEnvVars(env); } } // add env contributing actions' values from last build to environment - fixes JENKINS-22009 addEnvironmentContributingActionsValues(env, b); EnvVars.resolve(env); return env; } private static void addEnvironmentContributingActionsValues(EnvVars env, AbstractBuild b) { List<? extends Action> buildActions = b.getAllActions(); if (buildActions != null) { for (Action action : buildActions) { // most importantly, ParametersAction will be processed here (for parameterized builds) if (action instanceof ParametersAction) { ParametersAction envAction = (ParametersAction) action; envAction.buildEnvVars(b, env); } } } // Use the default parameter values (if any) instead of the ones from the last build ParametersDefinitionProperty paramDefProp = (ParametersDefinitionProperty) b.getProject().getProperty(ParametersDefinitionProperty.class); if (paramDefProp != null) { for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) { ParameterValue defaultValue = paramDefinition.getDefaultParameterValue(); if (defaultValue != null) { defaultValue.buildEnvironment(b, env); } } } } public static String[] fixupNames(String[] names, String[] urls) { String[] returnNames = new String[urls.length]; Set<String> usedNames = new HashSet<>(); for(int i=0; i<urls.length; i++) { String name = names[i]; if(name == null || name.trim().length() == 0) { name = "origin"; } String baseName = name; int j=1; while(usedNames.contains(name)) { name = baseName + (j++); } usedNames.add(name); returnNames[i] = name; } return returnNames; } private static final Logger LOGGER = Logger.getLogger(GitUtils.class.getName()); private static final long serialVersionUID = 1L; }
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.common.contacts; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Data; import android.text.TextUtils; import android.text.util.Rfc822Token; import android.text.util.Rfc822Tokenizer; import android.util.Log; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Convenient class for updating usage statistics in ContactsProvider. * * Applications like Email, Sms, etc. can promote recipients for better sorting with this class * * @see ContactsContract.Contacts */ public class DataUsageStatUpdater { private static final String TAG = DataUsageStatUpdater.class.getSimpleName(); /** * Copied from API in ICS (not available before it). You can use values here if you are sure * it is supported by the device. */ public static final class DataUsageFeedback { static final Uri FEEDBACK_URI = Uri.withAppendedPath(Data.CONTENT_URI, "usagefeedback"); static final String USAGE_TYPE = "type"; public static final String USAGE_TYPE_CALL = "call"; public static final String USAGE_TYPE_LONG_TEXT = "long_text"; public static final String USAGE_TYPE_SHORT_TEXT = "short_text"; } private final ContentResolver mResolver; public DataUsageStatUpdater(Context context) { mResolver = context.getContentResolver(); } /** * Updates usage statistics using comma-separated RFC822 address like * "Joe <joe@example.com>, Due <due@example.com>". * * This will cause Disk access so should be called in a background thread. * * @return true when update request is correctly sent. False when the request fails, * input has no valid entities. */ public boolean updateWithRfc822Address(Collection<CharSequence> texts){ if (texts == null) { return false; } else { final Set<String> addresses = new HashSet<String>(); for (CharSequence text : texts) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(text.toString().trim()); for (Rfc822Token token : tokens) { addresses.add(token.getAddress()); } } return updateWithAddress(addresses); } } /** * Update usage statistics information using a list of email addresses. * * This will cause Disk access so should be called in a background thread. * * @see #update(Collection, Collection, String) * * @return true when update request is correctly sent. False when the request fails, * input has no valid entities. */ public boolean updateWithAddress(Collection<String> addresses) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "updateWithAddress: " + Arrays.toString(addresses.toArray())); } if (addresses != null && !addresses.isEmpty()) { final ArrayList<String> whereArgs = new ArrayList<String>(); final StringBuilder whereBuilder = new StringBuilder(); final String[] questionMarks = new String[addresses.size()]; whereArgs.addAll(addresses); Arrays.fill(questionMarks, "?"); // Email.ADDRESS == Email.DATA1. Email.ADDRESS can be available from API Level 11. whereBuilder.append(Email.DATA1 + " IN (") .append(TextUtils.join(",", questionMarks)) .append(")"); final Cursor cursor = mResolver.query(Email.CONTENT_URI, new String[] {Email.CONTACT_ID, Email._ID}, whereBuilder.toString(), whereArgs.toArray(new String[0]), null); if (cursor == null) { Log.w(TAG, "Cursor for Email.CONTENT_URI became null."); } else { final Set<Long> contactIds = new HashSet<Long>(cursor.getCount()); final Set<Long> dataIds = new HashSet<Long>(cursor.getCount()); try { cursor.move(-1); while(cursor.moveToNext()) { contactIds.add(cursor.getLong(0)); dataIds.add(cursor.getLong(1)); } } finally { cursor.close(); } return update(contactIds, dataIds, DataUsageFeedback.USAGE_TYPE_LONG_TEXT); } } return false; } /** * Update usage statistics information using a list of phone numbers. * * This will cause Disk access so should be called in a background thread. * * @see #update(Collection, Collection, String) * * @return true when update request is correctly sent. False when the request fails, * input has no valid entities. */ public boolean updateWithPhoneNumber(Collection<String> numbers) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "updateWithPhoneNumber: " + Arrays.toString(numbers.toArray())); } if (numbers != null && !numbers.isEmpty()) { final ArrayList<String> whereArgs = new ArrayList<String>(); final StringBuilder whereBuilder = new StringBuilder(); final String[] questionMarks = new String[numbers.size()]; whereArgs.addAll(numbers); Arrays.fill(questionMarks, "?"); // Phone.NUMBER == Phone.DATA1. NUMBER can be available from API Level 11. whereBuilder.append(Phone.DATA1 + " IN (") .append(TextUtils.join(",", questionMarks)) .append(")"); final Cursor cursor = mResolver.query(Phone.CONTENT_URI, new String[] {Phone.CONTACT_ID, Phone._ID}, whereBuilder.toString(), whereArgs.toArray(new String[0]), null); if (cursor == null) { Log.w(TAG, "Cursor for Phone.CONTENT_URI became null."); } else { final Set<Long> contactIds = new HashSet<Long>(cursor.getCount()); final Set<Long> dataIds = new HashSet<Long>(cursor.getCount()); try { cursor.move(-1); while(cursor.moveToNext()) { contactIds.add(cursor.getLong(0)); dataIds.add(cursor.getLong(1)); } } finally { cursor.close(); } return update(contactIds, dataIds, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT); } } return false; } /** * @return true when one or more of update requests are correctly sent. * False when all the requests fail. */ private boolean update(Collection<Long> contactIds, Collection<Long> dataIds, String type) { final long currentTimeMillis = System.currentTimeMillis(); boolean successful = false; // From ICS (SDK_INT 14) we can use per-contact-method structure. We'll check if the device // supports it and call the API. if (Build.VERSION.SDK_INT >= 14) { if (dataIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for data IDs is null. Ignoring."); } } else { final Uri uri = DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(TextUtils.join(",", dataIds)) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, type) .build(); if (mResolver.update(uri, new ContentValues(), null, null) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward data rows " + dataIds + " failed"); } } } } else { // Use older API. if (contactIds.isEmpty()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Given list for contact IDs is null. Ignoring."); } } else { final StringBuilder whereBuilder = new StringBuilder(); final ArrayList<String> whereArgs = new ArrayList<String>(); final String[] questionMarks = new String[contactIds.size()]; for (long contactId : contactIds) { whereArgs.add(String.valueOf(contactId)); } Arrays.fill(questionMarks, "?"); whereBuilder.append(ContactsContract.Contacts._ID + " IN ("). append(TextUtils.join(",", questionMarks)). append(")"); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "contactId where: " + whereBuilder.toString()); Log.d(TAG, "contactId selection: " + whereArgs); } final ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.LAST_TIME_CONTACTED, currentTimeMillis); if (mResolver.update(ContactsContract.Contacts.CONTENT_URI, values, whereBuilder.toString(), whereArgs.toArray(new String[0])) > 0) { successful = true; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "update toward raw contacts " + contactIds + " failed"); } } } } return successful; } }
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.webapi.controller.event.webrequest.tracker; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.springframework.http.HttpStatus.BAD_REQUEST; import org.hisp.dhis.dxf2.webmessage.WebMessageException; import org.hisp.dhis.program.ProgramInstance; import org.hisp.dhis.program.ProgramStageInstance; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.junit.jupiter.api.Test; class TrackerRelationshipCriteriaTest { @Test void getIdentifierParamIfTrackedEntityIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); assertEquals( "Hq3Kc6HK4OZ", criteria.getIdentifierParam() ); assertEquals( "Hq3Kc6HK4OZ", criteria.getIdentifierParam(), "should return cached identifier" ); } @Test void getIdentifierParamIfTeiIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTei( "Hq3Kc6HK4OZ" ); assertEquals( "Hq3Kc6HK4OZ", criteria.getIdentifierParam() ); } @Test void getIdentifierNameIfTrackedEntityIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); assertEquals( "trackedEntity", criteria.getIdentifierName() ); } @Test void getIdentifierNameIfTeiIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTei( "Hq3Kc6HK4OZ" ); assertEquals( "trackedEntity", criteria.getIdentifierName() ); } @Test void getIdentifierClassIfTrackedEntityIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); assertEquals( TrackedEntityInstance.class, criteria.getIdentifierClass() ); } @Test void getIdentifierClassIfTeiIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTei( "Hq3Kc6HK4OZ" ); assertEquals( TrackedEntityInstance.class, criteria.getIdentifierClass() ); } @Test void getIdentifierParamIfEnrollmentIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); assertEquals( "Hq3Kc6HK4OZ", criteria.getIdentifierParam() ); } @Test void getIdentifierNameIfEnrollmentIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); assertEquals( "enrollment", criteria.getIdentifierName() ); } @Test void getIdentifierClassIfEnrollmentIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); assertEquals( ProgramInstance.class, criteria.getIdentifierClass() ); } @Test void getIdentifierParamIfEventIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEvent( "Hq3Kc6HK4OZ" ); assertEquals( "Hq3Kc6HK4OZ", criteria.getIdentifierParam() ); } @Test void getIdentifierNameIfEventIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEvent( "Hq3Kc6HK4OZ" ); assertEquals( "event", criteria.getIdentifierName() ); } @Test void getIdentifierClassIfEventIsSet() throws WebMessageException { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEvent( "Hq3Kc6HK4OZ" ); assertEquals( ProgramStageInstance.class, criteria.getIdentifierClass() ); } @Test void getIdentifierParamThrowsIfNoParamsIsSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierParam ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Missing required parameter 'trackedEntity', 'enrollment' or 'event'.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierNameThrowsIfNoParamsIsSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierName ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Missing required parameter 'trackedEntity', 'enrollment' or 'event'.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierParamThrowsIfAllParamsAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); criteria.setTei( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); criteria.setEvent( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierParam ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierNameThrowsIfAllParamsAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); criteria.setTei( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); criteria.setEvent( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierName ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierClassThrowsIfAllParamsAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); criteria.setTei( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); criteria.setEvent( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierClass ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierParamThrowsIfTrackedEntityAndEnrollmentAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierParam ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierParamThrowsIfTeiAndEnrollmentAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTei( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierParam ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierClassThrowsIfTrackedEntityAndEnrollmentAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTrackedEntity( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierClass ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierClassThrowsIfTeiAndEnrollmentAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setTei( "Hq3Kc6HK4OZ" ); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierClass ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } @Test void getIdentifierParamThrowsIfEnrollmentAndEventAreSet() { TrackerRelationshipCriteria criteria = new TrackerRelationshipCriteria(); criteria.setEnrollment( "Hq3Kc6HK4OZ" ); criteria.setEvent( "Hq3Kc6HK4OZ" ); WebMessageException exception = assertThrows( WebMessageException.class, criteria::getIdentifierParam ); assertEquals( BAD_REQUEST.value(), exception.getWebMessage().getHttpStatusCode() ); assertEquals( "Only one of parameters 'trackedEntity', 'enrollment' or 'event' is allowed.", exception.getWebMessage().getMessage() ); } }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.util.ArrayList; import java.util.Date; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.BlockDeviceMapping; import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest; import com.amazonaws.services.ec2.model.CreateTagsRequest; import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest; import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult; import com.amazonaws.services.ec2.model.EbsBlockDevice; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.LaunchSpecification; import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest; import com.amazonaws.services.ec2.model.RequestSpotInstancesResult; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.SpotInstanceRequest; import com.amazonaws.services.ec2.model.SpotPlacement; import com.amazonaws.services.ec2.model.Tag; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; public class Requests { private AmazonEC2 ec2; private ArrayList<String> instanceIds; private ArrayList<String> spotInstanceRequestIds; private String instanceType; private String amiID; private String bidPrice; private String securityGroup; private String placementGroupName; private boolean deleteOnTermination; private String availabilityZoneName; private String availabilityZoneGroupName; private String launchGroupName; private Date validFrom; private Date validTo; private String requestType; /** * Public constructor. * @throws Exception */ public Requests (String instanceType, String amiID, String bidPrice, String securityGroup) throws Exception { init(instanceType, amiID, bidPrice,securityGroup); } /** * The only information needed to create a client are security credentials * consisting of the AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints, are performed * automatically. Client parameters, such as proxies, can be specified in an * optional ClientConfiguration object when constructing a client. * * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private void init(String instanceType, String amiID, String bidPrice, String securityGroup) throws Exception { /* * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (~/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { throw new AmazonClientException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); ec2.setRegion(usWest2); this.instanceType = instanceType; this.amiID = amiID; this.bidPrice = bidPrice; this.securityGroup = securityGroup; this.deleteOnTermination = true; this.placementGroupName = null; } /** * The submit method will create 1 x one-time t1.micro request with a maximum bid * price of $0.03 using the Amazon Linux AMI. * * Note the AMI id may change after the release of this code sample, and it is important * to use the latest. You can find the latest version by logging into the AWS Management * console, and attempting to perform a launch. You will be presented with AMI options, * one of which will be Amazon Linux. Simply use that AMI id. */ public void submitRequests() { //==========================================================================// //================= Submit a Spot Instance Request =====================// //==========================================================================// // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice(bidPrice); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId(amiID); launchSpecification.setInstanceType(instanceType); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add(securityGroup); launchSpecification.setSecurityGroups(securityGroups); // If a placement group has been set, then we will use it in the request. if (placementGroupName != null && !placementGroupName.equals("")) { // Setup the placement group to use with whatever name you desire. SpotPlacement placement = new SpotPlacement(); placement.setGroupName(placementGroupName); launchSpecification.setPlacement(placement); } // Check to see if we need to set the availability zone name. if (availabilityZoneName != null && !availabilityZoneName.equals("")) { // Setup the availability zone to use. Note we could retrieve the availability // zones using the ec2.describeAvailabilityZones() API. SpotPlacement placement = new SpotPlacement(availabilityZoneName); launchSpecification.setPlacement(placement); } if (availabilityZoneGroupName != null && !availabilityZoneGroupName.equals("")) { // Set the availability zone group. requestRequest.setAvailabilityZoneGroup(availabilityZoneGroupName); } // Check to see if we need to set the launch group. if (launchGroupName != null && !launchGroupName.equals("")) { // Set the availability launch group. requestRequest.setLaunchGroup(launchGroupName); } // Check to see if we need to set the valid from option. if (validFrom != null) { requestRequest.setValidFrom(validFrom); } // Check to see if we need to set the valid until option. if (validTo != null) { requestRequest.setValidUntil(validFrom); } // Check to see if we need to set the request type. if (requestType != null && !requestType.equals("")) { // Set the type of the bid. requestRequest.setType(requestType); } // If we should delete the EBS boot partition on termination. if (!deleteOnTermination) { // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); } // Add the launch specifications to the request. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: "+requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } } public void launchOnDemand () { //============================================================================================// //====================================== Launch an On-Demand Instance ========================// //====================================== If we Didn't Get a Spot Instance ====================// //============================================================================================// // Setup the request for 1 x t1.micro using the same security group and // AMI id as the Spot request. RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.setInstanceType(instanceType); runInstancesRequest.setImageId(amiID); runInstancesRequest.setMinCount(Integer.valueOf(1)); runInstancesRequest.setMaxCount(Integer.valueOf(1)); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add(securityGroup); runInstancesRequest.setSecurityGroups(securityGroups); // Launch the instance. RunInstancesResult runResult = ec2.runInstances(runInstancesRequest); // Add the instance id into the instance id list, so we can potentially later // terminate that list. for (Instance instance: runResult.getReservation().getInstances()) { System.out.println("Launched On-Demand Instace: "+instance.getInstanceId()); instanceIds.add(instance.getInstanceId()); } } /** * The areOpen method will determine if any of the requests that were started are still * in the open state. If all of them have transitioned to either active, cancelled, or * closed, then this will return false. * @return */ public boolean areAnyOpen() { //==========================================================================// //============== Describe Spot Instance Requests to determine =============// //==========================================================================// // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); System.out.println("Checking to determine if Spot Bids have reached the active state..."); // Initialize variables. instanceIds = new ArrayList<String>(); try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // Look through each request and determine if they are all in the active state. for (SpotInstanceRequest describeResponse : describeResponses) { System.out.println(" " +describeResponse.getSpotInstanceRequestId() + " is in the "+describeResponse.getState() + " state."); // If the state is open, it hasn't changed since we attempted to request it. // There is the potential for it to transition almost immediately to closed or // cancelled so we compare against open instead of active. if (describeResponse.getState().equals("open")) { return true; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // Print out the error. System.out.println("Error when calling describeSpotInstances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. return true; } return false; } /** * Tag any of the resources we specify. * @param resources * @param tags */ private void tagResources(List<String> resources, List<Tag> tags) { // Create a tag request. CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.setResources(resources); createTagsRequest.setTags(tags); // Try to tag the Spot request submitted. try { ec2.createTags(createTagsRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } } /** * Tags all of the instances started with this object with the tags specified. * @param tags */ public void tagInstances(List<Tag> tags) { tagResources(instanceIds, tags); } /** * Tags all of the requests started with this object with the tags specified. * @param tags */ public void tagRequests(List<Tag> tags) { tagResources(spotInstanceRequestIds, tags); } /** * The cleanup method will cancel and active requests and terminate any running instances * that were created using this object. */ public void cleanup () { //==========================================================================// //================= Cancel/Terminate Your Spot Request =====================// //==========================================================================// try { // Cancel requests. System.out.println("Cancelling requests."); CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } try { // Terminate instances. System.out.println("Terminate instances"); TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } // Delete all requests and instances that we have terminated. instanceIds.clear(); spotInstanceRequestIds.clear(); } /** * Sets the request type to either persistent or one-time. */ public void setRequestType(String type) { this.requestType = type; } /** * Sets the valid to and from time. If you set either value to null * or "" then the period will not be set. * @param from * @param to */ public void setValidPeriod(Date from, Date to) { this.validFrom = from; this.validTo = to; } /** * Sets the launch group to be used. If you set this to null * or "" then launch group will be used. * @param az */ public void setLaunchGroup(String launchGroup) { this.launchGroupName = launchGroup; } /** * Sets the availability zone group to be used. If you set this to null * or "" then availability zone group will be used. * @param az */ public void setAvailabilityZoneGroup(String azGroup) { this.availabilityZoneGroupName = azGroup; } /** * Sets the availability zone to be used. If you set this to null * or "" then availability zone will be used. * @param az */ public void setAvailabilityZone(String az) { this.availabilityZoneName = az; } /** * Sets the placementGroupName to be used. If you set this to null * or "" then no placementgroup will be used. * @param pg */ public void setPlacementGroup(String pg) { this.placementGroupName = pg; } /** * This sets the deleteOnTermination flag, so that we can determine whether or not * we should delete the root partition if the instance is interrupted or terminated. * @param terminate */ public void setDeleteOnTermination(boolean terminate) { this.deleteOnTermination = terminate; } }
package com.radirius.mercury.input; import com.radirius.mercury.framework.Core; import com.radirius.mercury.graphics.Camera; import com.radirius.mercury.math.MathUtil; import com.radirius.mercury.math.geometry.Vector2f; import org.lwjgl.LWJGLException; import org.lwjgl.input.*; import org.lwjgl.opengl.Display; import java.util.ArrayList; /** * An object form of input. * * @author wessles * @author Jeviny */ public class Input { public static final int KEY_ESCAPE = 0x01; public static final int KEY_1 = 0x02; public static final int KEY_2 = 0x03; public static final int KEY_3 = 0x04; public static final int KEY_4 = 0x05; public static final int KEY_5 = 0x06; public static final int KEY_6 = 0x07; public static final int KEY_7 = 0x08; public static final int KEY_8 = 0x09; public static final int KEY_9 = 0x0A; public static final int KEY_0 = 0x0B; public static final int KEY_MINUS = 0x0C; public static final int KEY_EQUALS = 0x0D; public static final int KEY_BACK = 0x0E; public static final int KEY_TAB = 0x0F; public static final int KEY_Q = 0x10; public static final int KEY_W = 0x11; public static final int KEY_E = 0x12; public static final int KEY_R = 0x13; public static final int KEY_T = 0x14; public static final int KEY_Y = 0x15; public static final int KEY_U = 0x16; public static final int KEY_I = 0x17; public static final int KEY_O = 0x18; public static final int KEY_P = 0x19; public static final int KEY_LBRACKET = 0x1A; public static final int KEY_RBRACKET = 0x1B; public static final int KEY_RETURN = 0x1C; public static final int KEY_ENTER = 0x1C; public static final int KEY_LCONTROL = 0x1D; public static final int KEY_A = 0x1E; public static final int KEY_S = 0x1F; public static final int KEY_D = 0x20; public static final int KEY_F = 0x21; public static final int KEY_G = 0x22; public static final int KEY_H = 0x23; public static final int KEY_J = 0x24; public static final int KEY_K = 0x25; public static final int KEY_L = 0x26; public static final int KEY_SEMICOLON = 0x27; public static final int KEY_APOSTROPHE = 0x28; public static final int KEY_GRAVE = 0x29; public static final int KEY_LSHIFT = 0x2A; public static final int KEY_BACKSLASH = 0x2B; public static final int KEY_Z = 0x2C; public static final int KEY_X = 0x2D; public static final int KEY_C = 0x2E; public static final int KEY_V = 0x2F; public static final int KEY_B = 0x30; public static final int KEY_N = 0x31; public static final int KEY_M = 0x32; public static final int KEY_COMMA = 0x33; public static final int KEY_PERIOD = 0x34; public static final int KEY_SLASH = 0x35; public static final int KEY_RSHIFT = 0x36; public static final int KEY_MULTIPLY = 0x37; public static final int KEY_LMENU = 0x38; public static final int KEY_LALT = KEY_LMENU; public static final int KEY_SPACE = 0x39; public static final int KEY_CAPITAL = 0x3A; public static final int KEY_F1 = 0x3B; public static final int KEY_F2 = 0x3C; public static final int KEY_F3 = 0x3D; public static final int KEY_F4 = 0x3E; public static final int KEY_F5 = 0x3F; public static final int KEY_F6 = 0x40; public static final int KEY_F7 = 0x41; public static final int KEY_F8 = 0x42; public static final int KEY_F9 = 0x43; public static final int KEY_F10 = 0x44; public static final int KEY_NUMLOCK = 0x45; public static final int KEY_SCROLL = 0x46; public static final int KEY_NUMPAD7 = 0x47; public static final int KEY_NUMPAD8 = 0x48; public static final int KEY_NUMPAD9 = 0x49; public static final int KEY_SUBTRACT = 0x4A; public static final int KEY_NUMPAD4 = 0x4B; public static final int KEY_NUMPAD5 = 0x4C; public static final int KEY_NUMPAD6 = 0x4D; public static final int KEY_ADD = 0x4E; public static final int KEY_NUMPAD1 = 0x4F; public static final int KEY_NUMPAD2 = 0x50; public static final int KEY_NUMPAD3 = 0x51; public static final int KEY_NUMPAD0 = 0x52; public static final int KEY_DECIMAL = 0x53; public static final int KEY_F11 = 0x57; public static final int KEY_F12 = 0x58; public static final int KEY_F13 = 0x64; public static final int KEY_F14 = 0x65; public static final int KEY_F15 = 0x66; public static final int KEY_KANA = 0x70; public static final int KEY_CONVERT = 0x79; public static final int KEY_NOCONVERT = 0x7B; public static final int KEY_YEN = 0x7D; public static final int KEY_NUMPADEQUALS = 0x8D; public static final int KEY_CIRCUMFLEX = 0x90; public static final int KEY_AT = 0x91; public static final int KEY_COLON = 0x92; public static final int KEY_UNDERLINE = 0x93; public static final int KEY_KANJI = 0x94; public static final int KEY_STOP = 0x95; public static final int KEY_AX = 0x96; public static final int KEY_UNLABELED = 0x97; public static final int KEY_NUMPADENTER = 0x9C; public static final int KEY_RCONTROL = 0x9D; public static final int KEY_NUMPADCOMMA = 0xB3; public static final int KEY_DIVIDE = 0xB5; public static final int KEY_SYSRQ = 0xB7; public static final int KEY_RMENU = 0xB8; public static final int KEY_RALT = KEY_RMENU; public static final int KEY_PAUSE = 0xC5; public static final int KEY_HOME = 0xC7; public static final int KEY_UP = 0xC8; public static final int KEY_PRIOR = 0xC9; public static final int KEY_LEFT = 0xCB; public static final int KEY_RIGHT = 0xCD; public static final int KEY_END = 0xCF; public static final int KEY_DOWN = 0xD0; public static final int KEY_NEXT = 0xD1; public static final int KEY_INSERT = 0xD2; public static final int KEY_DELETE = 0xD3; public static final int KEY_LWIN = 0xDB; public static final int KEY_RWIN = 0xDC; public static final int KEY_APPS = 0xDD; public static final int KEY_POWER = 0xDE; public static final int KEY_SLEEP = 0xDF; public static final int MOUSE_LEFT = 0; public static final int MOUSE_RIGHT = 1; public static final int MOUSE_MID = 2; private static ArrayList<Integer> eventKeyStates = new ArrayList<Integer>(); private static ArrayList<Integer> eventMouseButtonStates = new ArrayList<Integer>(); private static ArrayList<ControllerEvent> eventControllerButtonStates = new ArrayList<ControllerEvent>(); private static int mousedWheel = 0; private static char nextCharacter = 0; private static boolean keyboardPolling = true; private static boolean mousePolling = true; private static boolean controllerPolling = true; /** * Creates the input things. */ public static void init() { try { Mouse.create(); Keyboard.create(); } catch (LWJGLException e) { e.printStackTrace(); } setRepeatEventsEnabled(true); } /** * Updates a list of things that happened every frame. */ public static void pollKeyboard() { if (!keyboardPolling) return; while (Keyboard.next()) { if (Keyboard.getEventKeyState()) { eventKeyStates.add(Keyboard.getEventKey()); nextCharacter = Keyboard.getEventCharacter(); } } } /** * Updates a list of things that happened every frame. */ public static void pollMouse() { if (!mousePolling) return; while (Mouse.next()) { if (Mouse.getEventButtonState()) eventMouseButtonStates.add(Mouse.getEventButton()); } mousedWheel = Mouse.getDWheel(); } /** * Updates a list of things that happened every frame. */ public static void pollControllers() { if (!controllerPolling) return; if (!Controllers.isCreated()) return; int controllerId = 0; while (Controllers.next()) { if (Controllers.isEventButton()) { int button = Controllers.getEventControlIndex(); boolean state = Controllers.getEventButtonState(); if (!state) eventControllerButtonStates.add(new ControllerEvent(button, controllerId)); } controllerId++; } } /** * Polls keyboard and mouse. */ public static void poll() { purgeBuffers(); pollKeyboard(); pollMouse(); pollControllers(); } public static void purgeBuffers() { eventKeyStates.clear(); nextCharacter = 0; eventMouseButtonStates.clear(); eventControllerButtonStates.clear(); } /** * Returns If key was clicked. */ public static boolean keyClicked(int key) { for (Integer eventkey : eventKeyStates) if (eventkey == key) return true; return false; } /** * Returns If any key was clicked. */ public static boolean wasKeyClicked() { return eventKeyStates.size() != 0; } /** * Returns If key is down. */ public static boolean keyDown(int key) { if (Keyboard.isKeyDown(key)) return true; return false; } /** * Returns If key is up. */ public static boolean keyUp(int key) { return !keyDown(key); } /** * Returns The last character pressed. */ public static char getNextCharacter() { return nextCharacter; } /** * Sets whether or not to accept repeating events. */ public static void setRepeatEventsEnabled(boolean repeatevents) { Keyboard.enableRepeatEvents(repeatevents); } /** * Returns If mousebutton was clicked. */ public static boolean mouseClicked(int mousebutton) { for (Integer eventmousebutton : eventMouseButtonStates) if (eventmousebutton == mousebutton) return true; return false; } /** * Returns If mousebutton is down. */ public static boolean mouseDown(int mousebutton) { return Mouse.isButtonDown(mousebutton); } /** * Returns If mousebutton is up. */ public static boolean mouseUp(int mousebutton) { return !mouseDown(mousebutton); } /** * Returns If mouse wheel is going up. */ public static boolean mouseWheelUp() { return mousedWheel > 0; } /** * Returns If mouse wheel is going down. */ public static boolean mouseWheelDown() { return mousedWheel < 0; } /** * Returns The mouse 'correct' position (Has to do with the opengl origin being bottom left, and ours being top * left). */ public static Vector2f getMousePosition() { return new Vector2f(Mouse.getX(), Display.getHeight() - 1 - Mouse.getY()); } /** * Returns The mouse position's 'correct' x (Has to do with the opengl origin being bottom left, and ours being top * left). */ public static int getMouseX() { return (int) getMousePosition().x; } /** * Returns The mouse position's 'correct' y (Has to do with the opengl origin being bottom left, and ours being top * left). */ public static int getMouseY() { return (int) getMousePosition().y; } /** * Returns The global mouse position based on the displacement of the game's camera and the scaling of the * graphics. */ public static Vector2f getGlobalMousePosition() { Vector2f globalmousepos = getMousePosition(); Camera cam = Core.getCurrentCore().getCamera(); // Scale the mouse position globalmousepos.div(cam.getScaleDimensions()); // Move the mouse position to the camera globalmousepos.add(new Vector2f(cam.getPositionX() - cam.getOrigin().x / cam.getScaleDimensions().x, cam.getPositionY() - cam.getOrigin().y / cam.getScaleDimensions().y)); // Rotate to alignment float origx = cam.getPositionX(); float origy = cam.getPositionY(); float s = MathUtil.sin(-cam.getRotation()); float c = MathUtil.cos(-cam.getRotation()); globalmousepos.x -= origx; globalmousepos.y -= origy; float xnew = globalmousepos.x * c - globalmousepos.y * s; float ynew = globalmousepos.x * s + globalmousepos.y * c; globalmousepos.x = xnew + origx; globalmousepos.y = ynew + origy; return globalmousepos; } /** * Returns The global mouse x position based on the displacement of the game's camera and the scaling of the * graphics. */ public static float getGlobalMouseX() { return getGlobalMousePosition().x; } /** * Returns The global mouse y position based on the displacement of the game's camera and the scaling of the * graphics. */ public static float getGlobalMouseY() { return getGlobalMousePosition().y; } public static void initControllers() { if (Controllers.isCreated()) return; try { Controllers.create(); } catch (LWJGLException e) { e.printStackTrace(); } } public static boolean controllerButtonClicked(int button, int controller) { if (!Controllers.isCreated()) return false; for (ControllerEvent cevent : eventControllerButtonStates) if (cevent.button == button && cevent.controller == controller) return true; return false; } /** * Returns Whether or not the button on controller is down; null if controllers have not been initialized. */ public static boolean controllerButtonDown(int button, int controller) { if (!Controllers.isCreated()) return false; return Controllers.getController(controller).isButtonPressed(button); } /** * Returns Whether or not the button on controller is up; null if controllers have not been initialized. */ public static boolean controllerButtonUp(int button, int controller) { return !controllerButtonDown(button, controller); } /** * Returns A vector containing the x and y value of the left analog stick. null if controllers have not been * initialized. */ public static Vector2f getLeftAnalogStick(int controller) { if (!Controllers.isCreated()) return null; Vector2f result = new Vector2f(0, 0); Controller control = Controllers.getController(controller); result.x = control.getXAxisValue(); result.y = control.getYAxisValue(); return result; } /** * Returns A vector containing the x and y value of the right analog stick. null if controllers have not been * initialized. */ public static Vector2f getRightAnalogStick(int controller) { if (!Controllers.isCreated()) return null; Vector2f result = new Vector2f(0, 0); Controller control = Controllers.getController(controller); result.x = control.getRXAxisValue(); result.y = control.getRZAxisValue(); return result; } /** * Returns A vector containing the x and y value of the dpad. null if controllers have not been initialized. */ public static Vector2f getDPad(int controller) { if (!Controllers.isCreated()) return null; Vector2f result = new Vector2f(0, 0); Controller control = Controllers.getController(controller); result.x = control.getPovX(); result.y = control.getPovY(); return result; } /** * Returns The amount of controllers. -1 if controllers have not been initialized. */ public static int getControllerCount() { if (!Controllers.isCreated()) return -1; return Controllers.getControllerCount(); } /** * Enables event polling. * * @param keyboard Enable keyboard polling? */ public static void setKeyboardPollingEnabled(boolean keyboard) { keyboardPolling = keyboard; } /** * Enables event polling. * * @param mouse Enable mouse polling? */ public static void setMousePollingEnabled(boolean mouse) { mousePolling = mouse; } /** * Enables event polling. * * @param controller Enable controller polling? */ public static void setControllerPollingEnabled(boolean controller) { controllerPolling = controller; } /** * Enables event polling. * * @param keyboard Enable keyboard polling? * @param mouse Enable mouse polling? * @param controller Enable controller polling? */ public static void setPollingEnabled(boolean keyboard, boolean mouse, boolean controller) { keyboardPolling = keyboard; mousePolling = mouse; controllerPolling = controller; } /** * Holds data for a controller event. */ private static class ControllerEvent { public final int button, controller; public ControllerEvent(int button, int controller) { this.button = button; this.controller = controller; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.apache.hadoop.hbase.util; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.reflect.Constructor; import java.net.InetAddress; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.cli.CommandLine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.crypto.Cipher; import org.apache.hadoop.hbase.io.crypto.Encryption; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.regionserver.BloomType; import org.apache.hadoop.hbase.security.EncryptionUtil; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.security.access.AccessControlClient; import org.apache.hadoop.hbase.security.access.Permission; import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator; import org.apache.hadoop.hbase.util.test.LoadTestDataGeneratorWithACL; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.ToolRunner; /** * A command-line utility that reads, writes, and verifies data. Unlike * {@link PerformanceEvaluation}, this tool validates the data written, * and supports simultaneously writing and reading the same set of keys. */ public class LoadTestTool extends AbstractHBaseTool { private static final Log LOG = LogFactory.getLog(LoadTestTool.class); private static final String COLON = ":"; /** Table name for the test */ private TableName tableName; /** Table name to use of not overridden on the command line */ protected static final String DEFAULT_TABLE_NAME = "cluster_test"; /** Column family used by the test */ public static byte[] COLUMN_FAMILY = Bytes.toBytes("test_cf"); /** Column families used by the test */ protected static final byte[][] COLUMN_FAMILIES = { COLUMN_FAMILY }; /** The default data size if not specified */ protected static final int DEFAULT_DATA_SIZE = 64; /** The number of reader/writer threads if not specified */ protected static final int DEFAULT_NUM_THREADS = 20; /** Usage string for the load option */ protected static final String OPT_USAGE_LOAD = "<avg_cols_per_key>:<avg_data_size>" + "[:<#threads=" + DEFAULT_NUM_THREADS + ">]"; /** Usage string for the read option */ protected static final String OPT_USAGE_READ = "<verify_percent>[:<#threads=" + DEFAULT_NUM_THREADS + ">]"; /** Usage string for the update option */ protected static final String OPT_USAGE_UPDATE = "<update_percent>[:<#threads=" + DEFAULT_NUM_THREADS + ">][:<#whether to ignore nonce collisions=0>]"; protected static final String OPT_USAGE_BLOOM = "Bloom filter type, one of " + Arrays.toString(BloomType.values()); protected static final String OPT_USAGE_COMPRESSION = "Compression type, " + "one of " + Arrays.toString(Compression.Algorithm.values()); public static final String OPT_DATA_BLOCK_ENCODING_USAGE = "Encoding algorithm (e.g. prefix " + "compression) to use for data blocks in the test column family, " + "one of " + Arrays.toString(DataBlockEncoding.values()) + "."; public static final String OPT_BLOOM = "bloom"; public static final String OPT_COMPRESSION = "compression"; public static final String OPT_DEFERRED_LOG_FLUSH = "deferredlogflush"; public static final String OPT_DEFERRED_LOG_FLUSH_USAGE = "Enable deferred log flush."; public static final String OPT_DATA_BLOCK_ENCODING = HColumnDescriptor.DATA_BLOCK_ENCODING.toLowerCase(); public static final String OPT_INMEMORY = "in_memory"; public static final String OPT_USAGE_IN_MEMORY = "Tries to keep the HFiles of the CF " + "inmemory as far as possible. Not guaranteed that reads are always served from inmemory"; public static final String OPT_GENERATOR = "generator"; public static final String OPT_GENERATOR_USAGE = "The class which generates load for the tool." + " Any args for this class can be passed as colon separated after class name"; public static final String OPT_READER = "reader"; public static final String OPT_READER_USAGE = "The class for executing the read requests"; protected static final String OPT_KEY_WINDOW = "key_window"; protected static final String OPT_WRITE = "write"; protected static final String OPT_MAX_READ_ERRORS = "max_read_errors"; protected static final String OPT_MULTIPUT = "multiput"; protected static final String OPT_NUM_KEYS = "num_keys"; protected static final String OPT_READ = "read"; protected static final String OPT_START_KEY = "start_key"; public static final String OPT_TABLE_NAME = "tn"; protected static final String OPT_ZK_QUORUM = "zk"; protected static final String OPT_ZK_PARENT_NODE = "zk_root"; protected static final String OPT_SKIP_INIT = "skip_init"; protected static final String OPT_INIT_ONLY = "init_only"; protected static final String NUM_TABLES = "num_tables"; protected static final String OPT_REGIONS_PER_SERVER = "regions_per_server"; protected static final String OPT_BATCHUPDATE = "batchupdate"; protected static final String OPT_UPDATE = "update"; public static final String OPT_ENCRYPTION = "encryption"; protected static final String OPT_ENCRYPTION_USAGE = "Enables transparent encryption on the test table, one of " + Arrays.toString(Encryption.getSupportedCiphers()); public static final String OPT_NUM_REGIONS_PER_SERVER = "num_regions_per_server"; protected static final String OPT_NUM_REGIONS_PER_SERVER_USAGE = "Desired number of regions per region server. Defaults to 5."; protected static int DEFAULT_NUM_REGIONS_PER_SERVER = 5; protected static final long DEFAULT_START_KEY = 0; /** This will be removed as we factor out the dependency on command line */ protected CommandLine cmd; protected MultiThreadedWriter writerThreads = null; protected MultiThreadedReader readerThreads = null; protected MultiThreadedUpdater updaterThreads = null; protected long startKey, endKey; protected boolean isWrite, isRead, isUpdate; protected boolean deferredLogFlush; // Column family options protected DataBlockEncoding dataBlockEncodingAlgo; protected Compression.Algorithm compressAlgo; protected BloomType bloomType; private boolean inMemoryCF; private User userOwner; // Writer options protected int numWriterThreads = DEFAULT_NUM_THREADS; protected int minColsPerKey, maxColsPerKey; protected int minColDataSize = DEFAULT_DATA_SIZE, maxColDataSize = DEFAULT_DATA_SIZE; protected boolean isMultiPut; // Updater options protected int numUpdaterThreads = DEFAULT_NUM_THREADS; protected int updatePercent; protected boolean ignoreConflicts = false; protected boolean isBatchUpdate; // Reader options private int numReaderThreads = DEFAULT_NUM_THREADS; private int keyWindow = MultiThreadedReader.DEFAULT_KEY_WINDOW; private int maxReadErrors = MultiThreadedReader.DEFAULT_MAX_ERRORS; private int verifyPercent; private int numTables = 1; private int regionsPerServer = HBaseTestingUtility.DEFAULT_REGIONS_PER_SERVER; private String superUser; private String userNames; //This file is used to read authentication information in secure clusters. private String authnFileName; // TODO: refactor LoadTestToolImpl somewhere to make the usage from tests less bad, // console tool itself should only be used from console. protected boolean isSkipInit = false; protected boolean isInitOnly = false; protected Cipher cipher = null; protected String[] splitColonSeparated(String option, int minNumCols, int maxNumCols) { String optVal = cmd.getOptionValue(option); String[] cols = optVal.split(COLON); if (cols.length < minNumCols || cols.length > maxNumCols) { throw new IllegalArgumentException("Expected at least " + minNumCols + " columns but no more than " + maxNumCols + " in the colon-separated value '" + optVal + "' of the " + "-" + option + " option"); } return cols; } protected int getNumThreads(String numThreadsStr) { return parseInt(numThreadsStr, 1, Short.MAX_VALUE); } /** * Apply column family options such as Bloom filters, compression, and data * block encoding. */ protected void applyColumnFamilyOptions(TableName tableName, byte[][] columnFamilies) throws IOException { HBaseAdmin admin = new HBaseAdmin(conf); HTableDescriptor tableDesc = admin.getTableDescriptor(tableName); LOG.info("Disabling table " + tableName); admin.disableTable(tableName); for (byte[] cf : columnFamilies) { HColumnDescriptor columnDesc = tableDesc.getFamily(cf); boolean isNewCf = columnDesc == null; if (isNewCf) { columnDesc = new HColumnDescriptor(cf); } if (bloomType != null) { columnDesc.setBloomFilterType(bloomType); } if (compressAlgo != null) { columnDesc.setCompressionType(compressAlgo); } if (dataBlockEncodingAlgo != null) { columnDesc.setDataBlockEncoding(dataBlockEncodingAlgo); } if (inMemoryCF) { columnDesc.setInMemory(inMemoryCF); } if (cipher != null) { byte[] keyBytes = new byte[cipher.getKeyLength()]; new SecureRandom().nextBytes(keyBytes); columnDesc.setEncryptionType(cipher.getName()); columnDesc.setEncryptionKey(EncryptionUtil.wrapKey(conf, User.getCurrent().getShortName(), new SecretKeySpec(keyBytes, cipher.getName()))); } if (isNewCf) { admin.addColumn(tableName, columnDesc); } else { admin.modifyColumn(tableName, columnDesc); } } LOG.info("Enabling table " + tableName); admin.enableTable(tableName); admin.close(); } @Override protected void addOptions() { addOptWithArg(OPT_ZK_QUORUM, "ZK quorum as comma-separated host names " + "without port numbers"); addOptWithArg(OPT_ZK_PARENT_NODE, "name of parent znode in zookeeper"); addOptWithArg(OPT_TABLE_NAME, "The name of the table to read or write"); addOptWithArg(OPT_WRITE, OPT_USAGE_LOAD); addOptWithArg(OPT_READ, OPT_USAGE_READ); addOptWithArg(OPT_UPDATE, OPT_USAGE_UPDATE); addOptNoArg(OPT_INIT_ONLY, "Initialize the test table only, don't do any loading"); addOptWithArg(OPT_BLOOM, OPT_USAGE_BLOOM); addOptWithArg(OPT_COMPRESSION, OPT_USAGE_COMPRESSION); addOptWithArg(OPT_DATA_BLOCK_ENCODING, OPT_DATA_BLOCK_ENCODING_USAGE); addOptWithArg(OPT_MAX_READ_ERRORS, "The maximum number of read errors " + "to tolerate before terminating all reader threads. The default is " + MultiThreadedReader.DEFAULT_MAX_ERRORS + "."); addOptWithArg(OPT_KEY_WINDOW, "The 'key window' to maintain between " + "reads and writes for concurrent write/read workload. The default " + "is " + MultiThreadedReader.DEFAULT_KEY_WINDOW + "."); addOptNoArg(OPT_MULTIPUT, "Whether to use multi-puts as opposed to " + "separate puts for every column in a row"); addOptNoArg(OPT_BATCHUPDATE, "Whether to use batch as opposed to " + "separate updates for every column in a row"); addOptNoArg(OPT_INMEMORY, OPT_USAGE_IN_MEMORY); addOptWithArg(OPT_GENERATOR, OPT_GENERATOR_USAGE); addOptWithArg(OPT_READER, OPT_READER_USAGE); addOptWithArg(OPT_NUM_KEYS, "The number of keys to read/write"); addOptWithArg(OPT_START_KEY, "The first key to read/write " + "(a 0-based index). The default value is " + DEFAULT_START_KEY + "."); addOptNoArg(OPT_SKIP_INIT, "Skip the initialization; assume test table " + "already exists"); addOptWithArg(NUM_TABLES, "A positive integer number. When a number n is speicfied, load test " + "tool will load n table parallely. -tn parameter value becomes " + "table name prefix. Each table name is in format <tn>_1...<tn>_n"); addOptWithArg(OPT_REGIONS_PER_SERVER, "A positive integer number. When a number n is specified, load test " + "tool will create the test table with n regions per server"); addOptWithArg(OPT_ENCRYPTION, OPT_ENCRYPTION_USAGE); addOptNoArg(OPT_DEFERRED_LOG_FLUSH, OPT_DEFERRED_LOG_FLUSH_USAGE); addOptWithArg(OPT_NUM_REGIONS_PER_SERVER, OPT_NUM_REGIONS_PER_SERVER_USAGE); } @Override protected void processOptions(CommandLine cmd) { this.cmd = cmd; tableName = TableName.valueOf(cmd.getOptionValue(OPT_TABLE_NAME, DEFAULT_TABLE_NAME)); isWrite = cmd.hasOption(OPT_WRITE); isRead = cmd.hasOption(OPT_READ); isUpdate = cmd.hasOption(OPT_UPDATE); isInitOnly = cmd.hasOption(OPT_INIT_ONLY); deferredLogFlush = cmd.hasOption(OPT_DEFERRED_LOG_FLUSH); if (!isWrite && !isRead && !isUpdate && !isInitOnly) { throw new IllegalArgumentException("Either -" + OPT_WRITE + " or " + "-" + OPT_UPDATE + "-" + OPT_READ + " has to be specified"); } if (isInitOnly && (isRead || isWrite || isUpdate)) { throw new IllegalArgumentException(OPT_INIT_ONLY + " cannot be specified with" + " either -" + OPT_WRITE + " or -" + OPT_UPDATE + " or -" + OPT_READ); } if (!isInitOnly) { if (!cmd.hasOption(OPT_NUM_KEYS)) { throw new IllegalArgumentException(OPT_NUM_KEYS + " must be specified in " + "read or write mode"); } startKey = parseLong(cmd.getOptionValue(OPT_START_KEY, String.valueOf(DEFAULT_START_KEY)), 0, Long.MAX_VALUE); long numKeys = parseLong(cmd.getOptionValue(OPT_NUM_KEYS), 1, Long.MAX_VALUE - startKey); endKey = startKey + numKeys; isSkipInit = cmd.hasOption(OPT_SKIP_INIT); System.out.println("Key range: [" + startKey + ".." + (endKey - 1) + "]"); } parseColumnFamilyOptions(cmd); if (isWrite) { String[] writeOpts = splitColonSeparated(OPT_WRITE, 2, 3); int colIndex = 0; minColsPerKey = 1; maxColsPerKey = 2 * Integer.parseInt(writeOpts[colIndex++]); int avgColDataSize = parseInt(writeOpts[colIndex++], 1, Integer.MAX_VALUE); minColDataSize = avgColDataSize / 2; maxColDataSize = avgColDataSize * 3 / 2; if (colIndex < writeOpts.length) { numWriterThreads = getNumThreads(writeOpts[colIndex++]); } isMultiPut = cmd.hasOption(OPT_MULTIPUT); System.out.println("Multi-puts: " + isMultiPut); System.out.println("Columns per key: " + minColsPerKey + ".." + maxColsPerKey); System.out.println("Data size per column: " + minColDataSize + ".." + maxColDataSize); } if (isUpdate) { String[] mutateOpts = splitColonSeparated(OPT_UPDATE, 1, 3); int colIndex = 0; updatePercent = parseInt(mutateOpts[colIndex++], 0, 100); if (colIndex < mutateOpts.length) { numUpdaterThreads = getNumThreads(mutateOpts[colIndex++]); } if (colIndex < mutateOpts.length) { ignoreConflicts = parseInt(mutateOpts[colIndex++], 0, 1) == 1; } isBatchUpdate = cmd.hasOption(OPT_BATCHUPDATE); System.out.println("Batch updates: " + isBatchUpdate); System.out.println("Percent of keys to update: " + updatePercent); System.out.println("Updater threads: " + numUpdaterThreads); System.out.println("Ignore nonce conflicts: " + ignoreConflicts); } if (isRead) { String[] readOpts = splitColonSeparated(OPT_READ, 1, 2); int colIndex = 0; verifyPercent = parseInt(readOpts[colIndex++], 0, 100); if (colIndex < readOpts.length) { numReaderThreads = getNumThreads(readOpts[colIndex++]); } if (cmd.hasOption(OPT_MAX_READ_ERRORS)) { maxReadErrors = parseInt(cmd.getOptionValue(OPT_MAX_READ_ERRORS), 0, Integer.MAX_VALUE); } if (cmd.hasOption(OPT_KEY_WINDOW)) { keyWindow = parseInt(cmd.getOptionValue(OPT_KEY_WINDOW), 0, Integer.MAX_VALUE); } System.out.println("Percent of keys to verify: " + verifyPercent); System.out.println("Reader threads: " + numReaderThreads); } numTables = 1; if (cmd.hasOption(NUM_TABLES)) { numTables = parseInt(cmd.getOptionValue(NUM_TABLES), 1, Short.MAX_VALUE); } regionsPerServer = DEFAULT_NUM_REGIONS_PER_SERVER; if (cmd.hasOption(OPT_NUM_REGIONS_PER_SERVER)) { regionsPerServer = Integer.parseInt(cmd.getOptionValue(OPT_NUM_REGIONS_PER_SERVER)); } } private void parseColumnFamilyOptions(CommandLine cmd) { String dataBlockEncodingStr = cmd.getOptionValue(OPT_DATA_BLOCK_ENCODING); dataBlockEncodingAlgo = dataBlockEncodingStr == null ? null : DataBlockEncoding.valueOf(dataBlockEncodingStr); String compressStr = cmd.getOptionValue(OPT_COMPRESSION); compressAlgo = compressStr == null ? Compression.Algorithm.NONE : Compression.Algorithm.valueOf(compressStr); String bloomStr = cmd.getOptionValue(OPT_BLOOM); bloomType = bloomStr == null ? BloomType.ROW : BloomType.valueOf(bloomStr); inMemoryCF = cmd.hasOption(OPT_INMEMORY); if (cmd.hasOption(OPT_ENCRYPTION)) { cipher = Encryption.getCipher(conf, cmd.getOptionValue(OPT_ENCRYPTION)); } } public void initTestTable() throws IOException { Durability durability = Durability.USE_DEFAULT; if (deferredLogFlush) { durability = Durability.ASYNC_WAL; } HBaseTestingUtility.createPreSplitLoadTestTable(conf, tableName, COLUMN_FAMILY, compressAlgo, dataBlockEncodingAlgo, regionsPerServer, durability); applyColumnFamilyOptions(tableName, COLUMN_FAMILIES); } @Override protected int doWork() throws IOException { if (numTables > 1) { return parallelLoadTables(); } else { return loadTable(); } } protected int loadTable() throws IOException { if (cmd.hasOption(OPT_ZK_QUORUM)) { conf.set(HConstants.ZOOKEEPER_QUORUM, cmd.getOptionValue(OPT_ZK_QUORUM)); } if (cmd.hasOption(OPT_ZK_PARENT_NODE)) { conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, cmd.getOptionValue(OPT_ZK_PARENT_NODE)); } if (isInitOnly) { LOG.info("Initializing only; no reads or writes"); initTestTable(); return 0; } if (!isSkipInit) { initTestTable(); } LoadTestDataGenerator dataGen = null; if (cmd.hasOption(OPT_GENERATOR)) { String[] clazzAndArgs = cmd.getOptionValue(OPT_GENERATOR).split(COLON); dataGen = getLoadGeneratorInstance(clazzAndArgs[0]); String[] args; if (dataGen instanceof LoadTestDataGeneratorWithACL) { LOG.info("Using LoadTestDataGeneratorWithACL"); if (User.isHBaseSecurityEnabled(conf)) { LOG.info("Security is enabled"); authnFileName = clazzAndArgs[1]; superUser = clazzAndArgs[2]; userNames = clazzAndArgs[3]; args = Arrays.copyOfRange(clazzAndArgs, 2, clazzAndArgs.length); Properties authConfig = new Properties(); authConfig.load(this.getClass().getClassLoader().getResourceAsStream(authnFileName)); try { addAuthInfoToConf(authConfig, conf, superUser, userNames); } catch (IOException exp) { LOG.error(exp); return EXIT_FAILURE; } userOwner = User.create(loginAndReturnUGI(conf, superUser)); } else { superUser = clazzAndArgs[1]; userNames = clazzAndArgs[2]; args = Arrays.copyOfRange(clazzAndArgs, 1, clazzAndArgs.length); userOwner = User.createUserForTesting(conf, superUser, new String[0]); } } else { args = clazzAndArgs.length == 1 ? new String[0] : Arrays.copyOfRange(clazzAndArgs, 1, clazzAndArgs.length); } dataGen.initialize(args); } else { // Default DataGenerator is MultiThreadedAction.DefaultDataGenerator dataGen = new MultiThreadedAction.DefaultDataGenerator(minColDataSize, maxColDataSize, minColsPerKey, maxColsPerKey, COLUMN_FAMILY); } if (userOwner != null) { LOG.info("Granting permissions for user " + userOwner.getShortName()); Permission.Action[] actions = { Permission.Action.ADMIN, Permission.Action.CREATE, Permission.Action.READ, Permission.Action.WRITE }; try { AccessControlClient.grant(conf, tableName, userOwner.getShortName(), null, null, actions); } catch (Throwable e) { LOG.fatal("Error in granting permission for the user " + userOwner.getShortName(), e); return EXIT_FAILURE; } } if (userNames != null) { // This will be comma separated list of expressions. String users[] = userNames.split(","); User user = null; for (String userStr : users) { if (User.isHBaseSecurityEnabled(conf)) { user = User.create(loginAndReturnUGI(conf, userStr)); } else { user = User.createUserForTesting(conf, userStr, new String[0]); } } } if (isWrite) { if (userOwner != null) { writerThreads = new MultiThreadedWriterWithACL(dataGen, conf, tableName, userOwner); } else { writerThreads = new MultiThreadedWriter(dataGen, conf, tableName); } writerThreads.setMultiPut(isMultiPut); } if (isUpdate) { if (userOwner != null) { updaterThreads = new MultiThreadedUpdaterWithACL(dataGen, conf, tableName, updatePercent, userOwner, userNames); } else { updaterThreads = new MultiThreadedUpdater(dataGen, conf, tableName, updatePercent); } updaterThreads.setBatchUpdate(isBatchUpdate); updaterThreads.setIgnoreNonceConflicts(ignoreConflicts); } if (isRead) { if (userOwner != null) { readerThreads = new MultiThreadedReaderWithACL(dataGen, conf, tableName, verifyPercent, userNames); } else { String readerClass = null; if (cmd.hasOption(OPT_READER)) { readerClass = cmd.getOptionValue(OPT_READER); } else { readerClass = MultiThreadedReader.class.getCanonicalName(); } readerThreads = getMultiThreadedReaderInstance(readerClass, dataGen); } readerThreads.setMaxErrors(maxReadErrors); readerThreads.setKeyWindow(keyWindow); } if (isUpdate && isWrite) { LOG.info("Concurrent write/update workload: making updaters aware of the " + "write point"); updaterThreads.linkToWriter(writerThreads); } if (isRead && (isUpdate || isWrite)) { LOG.info("Concurrent write/read workload: making readers aware of the " + "write point"); readerThreads.linkToWriter(isUpdate ? updaterThreads : writerThreads); } if (isWrite) { System.out.println("Starting to write data..."); writerThreads.start(startKey, endKey, numWriterThreads); } if (isUpdate) { LOG.info("Starting to mutate data..."); System.out.println("Starting to mutate data..."); // TODO : currently append and increment operations not tested with tags // Will update this aftet it is done updaterThreads.start(startKey, endKey, numUpdaterThreads); } if (isRead) { System.out.println("Starting to read data..."); readerThreads.start(startKey, endKey, numReaderThreads); } if (isWrite) { writerThreads.waitForFinish(); } if (isUpdate) { updaterThreads.waitForFinish(); } if (isRead) { readerThreads.waitForFinish(); } boolean success = true; if (isWrite) { success = success && writerThreads.getNumWriteFailures() == 0; } if (isUpdate) { success = success && updaterThreads.getNumWriteFailures() == 0; } if (isRead) { success = success && readerThreads.getNumReadErrors() == 0 && readerThreads.getNumReadFailures() == 0; } return success ? EXIT_SUCCESS : EXIT_FAILURE; } private LoadTestDataGenerator getLoadGeneratorInstance(String clazzName) throws IOException { try { Class<?> clazz = Class.forName(clazzName); Constructor<?> constructor = clazz.getConstructor(int.class, int.class, int.class, int.class, byte[][].class); return (LoadTestDataGenerator) constructor.newInstance(minColDataSize, maxColDataSize, minColsPerKey, maxColsPerKey, COLUMN_FAMILIES); } catch (Exception e) { throw new IOException(e); } } private MultiThreadedReader getMultiThreadedReaderInstance(String clazzName , LoadTestDataGenerator dataGen) throws IOException { try { Class<?> clazz = Class.forName(clazzName); Constructor<?> constructor = clazz.getConstructor( LoadTestDataGenerator.class, Configuration.class, TableName.class, double.class); return (MultiThreadedReader) constructor.newInstance(dataGen, conf, tableName, verifyPercent); } catch (Exception e) { throw new IOException(e); } } public static byte[] generateData(final Random r, int length) { byte [] b = new byte [length]; int i = 0; for(i = 0; i < (length-8); i += 8) { b[i] = (byte) (65 + r.nextInt(26)); b[i+1] = b[i]; b[i+2] = b[i]; b[i+3] = b[i]; b[i+4] = b[i]; b[i+5] = b[i]; b[i+6] = b[i]; b[i+7] = b[i]; } byte a = (byte) (65 + r.nextInt(26)); for(; i < length; i++) { b[i] = a; } return b; } public static void main(String[] args) { new LoadTestTool().doStaticMain(args); } /** * When NUM_TABLES is specified, the function starts multiple worker threads * which individually start a LoadTestTool instance to load a table. Each * table name is in format <tn>_<index>. For example, "-tn test -num_tables 2" * , table names will be "test_1", "test_2" * * @throws IOException */ private int parallelLoadTables() throws IOException { // create new command args String tableName = cmd.getOptionValue(OPT_TABLE_NAME, DEFAULT_TABLE_NAME); String[] newArgs = null; if (!cmd.hasOption(LoadTestTool.OPT_TABLE_NAME)) { newArgs = new String[cmdLineArgs.length + 2]; newArgs[0] = "-" + LoadTestTool.OPT_TABLE_NAME; newArgs[1] = LoadTestTool.DEFAULT_TABLE_NAME; System.arraycopy(cmdLineArgs, 0, newArgs, 2, cmdLineArgs.length); } else { newArgs = cmdLineArgs; } int tableNameValueIndex = -1; for (int j = 0; j < newArgs.length; j++) { if (newArgs[j].endsWith(OPT_TABLE_NAME)) { tableNameValueIndex = j + 1; } else if (newArgs[j].endsWith(NUM_TABLES)) { // change NUM_TABLES to 1 so that each worker loads one table newArgs[j + 1] = "1"; } } // starting to load multiple tables List<WorkerThread> workers = new ArrayList<WorkerThread>(); for (int i = 0; i < numTables; i++) { String[] workerArgs = newArgs.clone(); workerArgs[tableNameValueIndex] = tableName + "_" + (i+1); WorkerThread worker = new WorkerThread(i, workerArgs); workers.add(worker); LOG.info(worker + " starting"); worker.start(); } // wait for all workers finish LOG.info("Waiting for worker threads to finish"); for (WorkerThread t : workers) { try { t.join(); } catch (InterruptedException ie) { IOException iie = new InterruptedIOException(); iie.initCause(ie); throw iie; } checkForErrors(); } return EXIT_SUCCESS; } // If an exception is thrown by one of worker threads, it will be // stored here. protected AtomicReference<Throwable> thrown = new AtomicReference<Throwable>(); private void workerThreadError(Throwable t) { thrown.compareAndSet(null, t); } /** * Check for errors in the writer threads. If any is found, rethrow it. */ private void checkForErrors() throws IOException { Throwable thrown = this.thrown.get(); if (thrown == null) return; if (thrown instanceof IOException) { throw (IOException) thrown; } else { throw new RuntimeException(thrown); } } class WorkerThread extends Thread { private String[] workerArgs; WorkerThread(int i, String[] args) { super("WorkerThread-" + i); workerArgs = args; } @Override public void run() { try { int ret = ToolRunner.run(HBaseConfiguration.create(), new LoadTestTool(), workerArgs); if (ret != 0) { throw new RuntimeException("LoadTestTool exit with non-zero return code."); } } catch (Exception ex) { LOG.error("Error in worker thread", ex); workerThreadError(ex); } } } private void addAuthInfoToConf(Properties authConfig, Configuration conf, String owner, String userList) throws IOException { List<String> users = Arrays.asList(userList.split(",")); users.add(owner); for (String user : users) { String keyTabFileConfKey = "hbase." + user + ".keytab.file"; String principalConfKey = "hbase." + user + ".kerberos.principal"; if (!authConfig.containsKey(keyTabFileConfKey) || !authConfig.containsKey(principalConfKey)) { throw new IOException("Authentication configs missing for user : " + user); } } for (String key : authConfig.stringPropertyNames()) { conf.set(key, authConfig.getProperty(key)); } LOG.debug("Added authentication properties to config successfully."); } public static UserGroupInformation loginAndReturnUGI(Configuration conf, String username) throws IOException { String hostname = InetAddress.getLocalHost().getHostName(); String keyTabFileConfKey = "hbase." + username + ".keytab.file"; String keyTabFileLocation = conf.get(keyTabFileConfKey); String principalConfKey = "hbase." + username + ".kerberos.principal"; String principal = SecurityUtil.getServerPrincipal(conf.get(principalConfKey), hostname); if (keyTabFileLocation == null || principal == null) { LOG.warn("Principal or key tab file null for : " + principalConfKey + ", " + keyTabFileConfKey); } UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keyTabFileLocation); return ugi; } }
/* Copyright 2005 I Serv Consultoria Empresarial Ltda. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.helianto.inventory.domain; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapKey; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.helianto.core.domain.Entity; import org.helianto.inventory.AgreementLevel; import org.helianto.inventory.AgreementState; import org.helianto.inventory.ProcurementOption; import org.helianto.inventory.internal.AbstractRequirement; import org.helianto.partner.domain.Partner; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Join a partner to a requirement to represent an agreement to buy * or to sell something. * * <p> * Subclass to tenders or quotations. * </p> * * @author Mauricio Fernandes de Castro */ @javax.persistence.Entity @Table(name="inv_agreement", uniqueConstraints = {@UniqueConstraint(columnNames={"entityId", "internalNumber"})} ) @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name="type", discriminatorType=DiscriminatorType.CHAR ) @DiscriminatorValue("A") public class ProcessAgreement extends AbstractRequirement { private static final long serialVersionUID = 1L; @JsonIgnore @ManyToOne @JoinColumn(name="partnerId", nullable=true) private Partner partner; @Column(length=512) private String agreementDesc = ""; private Character agreementLevel = AgreementState.PENDING.getValue(); @Column(precision=10, scale=3) private BigDecimal agreementPrice = BigDecimal.ZERO; private int minimalOrderDuration; private Character procurementOption = ProcurementOption.UNRESOLVED.getValue(); @JsonIgnore @OneToMany(mappedBy="processAgreement") @MapKey(name="taxCode") private Map<String, Tax> taxes = new HashMap<String, Tax>(); /** * Default constructor. */ public ProcessAgreement() { super(); } /** * Key constructor. * * @param entity * @param internalNumber */ public ProcessAgreement(Entity entity, long internalNumber) { this(); setEntity(entity); setInternalNumber(internalNumber); } public String getInternalNumberKey() { return "AGREEM"; } public int getStartNumber() { return 1; } /** * Customer or supplier. */ public Partner getPartner() { return this.partner; } public void setPartner(Partner partner) { this.partner = partner; } /** * <<Transient>> Customer or supplier alias. */ public String getPartnerAlias() { if (partner==null) return ""; return this.partner.getEntityAlias(); } /** * Description. */ public String getAgreementDesc() { return agreementDesc; } public void setAgreementDesc(String agreementDesc) { this.agreementDesc = agreementDesc; } /** * Validate resolution. */ @Override protected final char validateResolution(char agreementState) { return agreementState; } public void setResolution(char agreementState) { super.setResolution(agreementState); } public void setResolutionAsEnum(AgreementState agreementState) { setResolution(agreementState.getValue()); } /** * True if approved. */ public boolean isApproved() { if (getResolution()==AgreementState.APPROVED.getValue()) { return true; } return false; } /** * Credit level assigned to the partner. */ public Character getAgreementLevel() { return agreementLevel; } public void setAgreementLevel(Character agreementLevel) { this.agreementLevel = agreementLevel; } public void setAgreementLevelAsEnum(AgreementLevel agreementLevel) { this.agreementLevel = agreementLevel.getValue(); } /** * Agreement price. */ public BigDecimal getAgreementPrice() { return agreementPrice; } public void setAgreementPrice(BigDecimal agreementPrice) { this.agreementPrice = agreementPrice; } /** * Minimal order duration. */ public int getMinimalOrderDuration() { return minimalOrderDuration; } public void setMinimalOrderDuration(int minimalOrderDuration) { this.minimalOrderDuration = minimalOrderDuration; } /** * Procurement option (make, buy local, import) */ public Character getProcurementOption() { return procurementOption; } public void setProcurementOption(Character procurementOption) { this.procurementOption = procurementOption; } public void setProcurementOptionAsEnum(ProcurementOption procurementOption) { this.procurementOption = procurementOption.getValue(); } /** * A map of taxes. */ public Map<String, Tax> getTaxes() { return taxes; } public void setTaxes(Map<String, Tax> taxes) { this.taxes = taxes; } /** * equals */ @Override public boolean equals(Object other) { if ( !(other instanceof ProcessAgreement) ) return false; return super.equals(other); } }
/* * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: BasicTestIterator.java,v 1.2.4.1 2005/09/14 19:45:20 jeffsuttor Exp $ */ package com.sun.org.apache.xpath.internal.axes; import com.sun.org.apache.xml.internal.dtm.DTM; import com.sun.org.apache.xml.internal.dtm.DTMFilter; import com.sun.org.apache.xml.internal.dtm.DTMIterator; import com.sun.org.apache.xml.internal.utils.PrefixResolver; import com.sun.org.apache.xpath.internal.compiler.Compiler; import com.sun.org.apache.xpath.internal.compiler.OpMap; /** * Base for iterators that handle predicates. Does the basic next * node logic, so all the derived iterator has to do is get the * next node. */ public abstract class BasicTestIterator extends LocPathIterator { static final long serialVersionUID = 3505378079378096623L; /** * Create a LocPathIterator object. * * @param nscontext The namespace context for this iterator, * should be OK if null. */ protected BasicTestIterator() { } /** * Create a LocPathIterator object. * * @param nscontext The namespace context for this iterator, * should be OK if null. */ protected BasicTestIterator(PrefixResolver nscontext) { super(nscontext); } /** * Create a LocPathIterator object, including creation * of step walkers from the opcode list, and call back * into the Compiler to create predicate expressions. * * @param compiler The Compiler which is creating * this expression. * @param opPos The position of this iterator in the * opcode list from the compiler. * * @throws javax.xml.transform.TransformerException */ protected BasicTestIterator(Compiler compiler, int opPos, int analysis) throws javax.xml.transform.TransformerException { super(compiler, opPos, analysis, false); int firstStepPos = OpMap.getFirstChildPos(opPos); int whatToShow = compiler.getWhatToShow(firstStepPos); if ((0 == (whatToShow & (DTMFilter.SHOW_ATTRIBUTE | DTMFilter.SHOW_NAMESPACE | DTMFilter.SHOW_ELEMENT | DTMFilter.SHOW_PROCESSING_INSTRUCTION))) || (whatToShow == DTMFilter.SHOW_ALL)) initNodeTest(whatToShow); else { initNodeTest(whatToShow, compiler.getStepNS(firstStepPos), compiler.getStepLocalName(firstStepPos)); } initPredicateInfo(compiler, firstStepPos); } /** * Create a LocPathIterator object, including creation * of step walkers from the opcode list, and call back * into the Compiler to create predicate expressions. * * @param compiler The Compiler which is creating * this expression. * @param opPos The position of this iterator in the * opcode list from the compiler. * @param shouldLoadWalkers True if walkers should be * loaded, or false if this is a derived iterator and * it doesn't wish to load child walkers. * * @throws javax.xml.transform.TransformerException */ protected BasicTestIterator( Compiler compiler, int opPos, int analysis, boolean shouldLoadWalkers) throws javax.xml.transform.TransformerException { super(compiler, opPos, analysis, shouldLoadWalkers); } /** * Get the next node via getNextXXX. Bottlenecked for derived class override. * @return The next node on the axis, or DTM.NULL. */ protected abstract int getNextNode(); /** * Returns the next node in the set and advances the position of the * iterator in the set. After a NodeIterator is created, the first call * to nextNode() returns the first node in the set. * * @return The next <code>Node</code> in the set being iterated over, or * <code>null</code> if there are no more members in that set. */ public int nextNode() { if(m_foundLast) { m_lastFetched = DTM.NULL; return DTM.NULL; } if(DTM.NULL == m_lastFetched) { resetProximityPositions(); } int next; com.sun.org.apache.xpath.internal.VariableStack vars; int savedStart; if (-1 != m_stackFrame) { vars = m_execContext.getVarStack(); // These three statements need to be combined into one operation. savedStart = vars.getStackFrame(); vars.setStackFrame(m_stackFrame); } else { // Yuck. Just to shut up the compiler! vars = null; savedStart = 0; } try { do { next = getNextNode(); if (DTM.NULL != next) { if(DTMIterator.FILTER_ACCEPT == acceptNode(next)) break; else continue; } else break; } while (next != DTM.NULL); if (DTM.NULL != next) { m_pos++; return next; } else { m_foundLast = true; return DTM.NULL; } } finally { if (-1 != m_stackFrame) { // These two statements need to be combined into one operation. vars.setStackFrame(savedStart); } } } /** * Get a cloned Iterator that is reset to the beginning * of the query. * * @return A cloned NodeIterator set of the start of the query. * * @throws CloneNotSupportedException */ public DTMIterator cloneWithReset() throws CloneNotSupportedException { ChildTestIterator clone = (ChildTestIterator) super.cloneWithReset(); clone.resetProximityPositions(); return clone; } }
package org.c4sg.service.impl; import static java.util.Objects.requireNonNull; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.c4sg.constant.Constants; import org.c4sg.dao.ApplicationDAO; import org.c4sg.dao.BookmarkDAO; import org.c4sg.dao.OrganizationDAO; import org.c4sg.dao.ProjectDAO; import org.c4sg.dao.ProjectSkillDAO; import org.c4sg.dao.UserDAO; import org.c4sg.dao.UserProjectDAO; import org.c4sg.dto.CreateProjectDTO; import org.c4sg.dto.JobTitleDTO; import org.c4sg.dto.ProjectDTO; import org.c4sg.entity.Application; import org.c4sg.entity.Bookmark; import org.c4sg.entity.JobTitle; import org.c4sg.entity.Organization; import org.c4sg.entity.Project; import org.c4sg.entity.User; import org.c4sg.entity.UserProject; import org.c4sg.exception.BadRequestException; import org.c4sg.exception.ProjectServiceException; import org.c4sg.exception.UserProjectException; import org.c4sg.mapper.ProjectMapper; import org.c4sg.service.AsyncEmailService; import org.c4sg.service.C4sgUrlService; import org.c4sg.service.ProjectService; import org.c4sg.service.SkillService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class ProjectServiceImpl implements ProjectService { @Autowired private ProjectDAO projectDAO; @Autowired private BookmarkDAO bookmarkDAO; @Autowired private UserDAO userDAO; @Autowired private UserProjectDAO userProjectDAO; @Autowired private ApplicationDAO applicationDAO; @Autowired private ProjectSkillDAO projectSkillDAO; @Autowired private ProjectMapper projectMapper; @Autowired private SkillService skillService; @Autowired private AsyncEmailService asyncEmailService; @Autowired private OrganizationDAO organizationDAO; @Autowired private C4sgUrlService urlService; public void save(ProjectDTO projectDTO) { Project project = projectMapper.getProjectEntityFromDto(projectDTO); projectDAO.save(project); } public List<ProjectDTO> findProjects() { List<Project> projects = projectDAO.findAllByOrderByIdDesc(); return projectMapper.getDtosFromEntities(projects); } public ProjectDTO findById(int id) { return projectMapper.getProjectDtoFromEntity(projectDAO.findById(id)); } public ProjectDTO findByName(String name) { return projectMapper.getProjectDtoFromEntity(projectDAO.findByName(name)); } public Page<ProjectDTO> search(String keyWord, List<Integer> jobTitles, List<Integer> skills, String status, String remote,Integer page, Integer size) { Page<Project> projectPages = null; List<Project> projects = null; if (page==null){ page=0; } if (size == null){ if(skills != null && jobTitles != null) { projects = projectDAO.findByKeywordAndJobAndSkill(keyWord, jobTitles, skills, status, remote); } else if(skills != null) { projects = projectDAO.findByKeywordAndSkill(keyWord, skills, status, remote); } else if(jobTitles != null) { projects = projectDAO.findByKeywordAndJob(keyWord, jobTitles, status, remote); } else { projects = projectDAO.findByKeyword(keyWord, status, remote); } projectPages=new PageImpl<Project>(projects); } else{ Pageable pageable = new PageRequest(page,size); if(skills != null && jobTitles != null) { projectPages = projectDAO.findByKeywordAndJobAndSkill(keyWord, jobTitles, skills, status, remote, pageable); } else if(skills != null) { projectPages = projectDAO.findByKeywordAndSkill(keyWord, skills, status, remote, pageable); } else if(jobTitles != null) { projectPages = projectDAO.findByKeywordAndJob(keyWord, jobTitles, status, remote, pageable); } else { projectPages = projectDAO.findByKeyword(keyWord, status, remote, pageable); } } return projectPages.map(p -> projectMapper.getProjectDtoFromEntity(p)); } @Override public List<ProjectDTO> findByOrganization(Integer orgId, String projectStatus) { List<Project> projects = projectDAO.getProjectsByOrganization(orgId, projectStatus); // There should always be a new project for an organization. If new project doesn't exist, create one if (projectStatus != null && projectStatus.equals("N")) { if ((projects == null) || projects.size() == 0) { Project project = new Project(); project.setOrganization(organizationDAO.findOne(orgId)); project.setRemoteFlag("Y"); project.setStatus("N"); projectDAO.save(project); projects = projectDAO.getProjectsByOrganization(orgId, projectStatus); } } return projectMapper.getDtosFromEntities(projects); } public ProjectDTO createProject(CreateProjectDTO createProjectDTO) { Project project = projectDAO.findByNameAndOrganizationId( createProjectDTO.getName(), createProjectDTO.getOrganizationId()); if (project != null) { System.out.println("Project already exist."); } else { project = projectDAO.save( projectMapper.getProjectEntityFromCreateProjectDto(createProjectDTO)); // Updates projectUpdateTime for the organization Organization localOrgan = project.getOrganization(); localOrgan.setProjectUpdatedTime(new Timestamp(Calendar.getInstance().getTime().getTime())); organizationDAO.save(localOrgan); } return projectMapper.getProjectDtoFromEntity(project); } public ProjectDTO updateProject(ProjectDTO projectDTO) { Project project = projectDAO.findById(projectDTO.getId()); if (project == null) { System.out.println("Project does not exist."); } else { String oldStatus = project.getStatus(); project = projectDAO.save(projectMapper.getProjectEntityFromDto(projectDTO)); String newStatus = project.getStatus(); // Notify volunteer users of new project if (Constants.PROJECT_STATUS_NEW.equals(oldStatus) && Constants.PROJECT_STATUS_ACTIVE.equals(newStatus)) { List<User> notifyUsers = userDAO.findByNotify(); if (notifyUsers != null && !notifyUsers.isEmpty()) { for (int i=0; i<notifyUsers.size(); i++) { String toAddress = notifyUsers.get(i).getEmail(); Map<String, Object> context = new HashMap<String, Object>(); addProjectAndUrlToContext(context, projectDTO); asyncEmailService.sendWithContext(Constants.C4SG_ADDRESS, toAddress, "",Constants.SUBJECT_NEW_PROJECT_NOTIFICATION, Constants.TEMPLATE_NEW_PROJECT_NOTIFICATION, context); } System.out.println("New project email sent: Project=" + projectDTO.getId()); } } else if (Constants.PROJECT_STATUS_CLOSED.equals(newStatus) && !Constants.PROJECT_STATUS_CLOSED.equals(oldStatus)) { Map<String, Object> context = new HashMap<String, Object>(); addProjectAndUrlToContext(context, projectDTO); asyncEmailService.sendWithContext(Constants.C4SG_ADDRESS, Constants.C4SG_ADDRESS, Constants.C4SG_ADDRESS, Constants.SUBJECT_PROJECT_CLOSE, Constants.TEMPLATE_PROJECT_CLOSE, context); System.out.println("Close Project email sent: Project=" + projectDTO.getId() + " Email id ; =" + Constants.C4SG_ADDRESS); } } return projectMapper.getProjectDtoFromEntity(project); } public List<JobTitleDTO> findJobTitles() { List<JobTitle> jobTitles = projectDAO.findJobTitles(); return projectMapper.getJobTitleDtosFromEntities(jobTitles); } @Override public void saveImage(Integer id, String imgUrl) { projectDAO.updateImage(imgUrl, id); } /*---------------------------------------User Project code -----------------------------------------------------------*/ /*@Override public List<ProjectDTO> findByUser(Integer userId, String userProjectStatus) throws ProjectServiceException { List<Project> projects = projectDAO.findByUserIdAndUserProjectStatus(userId, userProjectStatus); return projectMapper.getDtosFromEntities(projects); }*/ /* @Override public List<ProjectDTO> getApplicationByUserAndStatus(Integer userId, String userProjectStatus) throws ProjectServiceException { List<Application> applications = applicationDAO.findByUser_IdAndStatus(userId, userProjectStatus); return projectMapper.getDtosFromApplicationEntities(applications); } */ /*@Override public ProjectDTO saveUserProject(Integer userId, Integer projectId, String status ) { User user = userDAO.findById(userId); requireNonNull(user, "Invalid User Id"); Project project = projectDAO.findById(projectId); requireNonNull(project, "Invalid Project Id"); if (status == null || (!status.equals("A") && !status.equals("B") && !status.equals("C") && !status.equals("D"))) { throw new BadRequestException("Invalid Project Status"); } else { isRecordExist(userId, projectId, status); UserProject userProject = new UserProject(); userProject.setUser(user); userProject.setProject(project); userProject.setStatus(status); userProjectDAO.save(userProject); } sendEmail(user, project, status); return projectMapper.getProjectDtoFromEntity(project); }*/ /*@Override public ProjectDTO saveApplication(Integer userId, Integer projectId, String status, String comment, String resumeFlag){ User user = userDAO.findById(userId); requireNonNull(user, "Invalid User Id"); Project project = projectDAO.findById(projectId); requireNonNull(project, "Invalid Project Id"); if (status == null || (!status.equals("A") && !status.equals("C") && !status.equals("D"))) { throw new BadRequestException("Invalid Project Status"); } else { Application application = applicationDAO.findByUser_IdAndProject_Id(userId, projectId); if(java.util.Objects.isNull(application)){ //create application = new Application(); application.setUser(user); application.setProject(project); application.setStatus(status); application.setComment(comment); application.setResumeFlag(resumeFlag); application.setAppliedTime(new Timestamp(Calendar.getInstance().getTime().getTime())); } else{ //update isApplied(application, status); application.setStatus(status); application.setComment(comment); application.setResumeFlag(resumeFlag); if(status.equals("C")){ application.setAcceptedTime(new Timestamp(Calendar.getInstance().getTime().getTime())); }else if(status.equals("D")){ application.setDeclinedTime(new Timestamp(Calendar.getInstance().getTime().getTime())); } } applicationDAO.save(application); //userProjectDAO.save(userProject); } sendEmail(user, project, status); return projectMapper.getProjectDtoFromEntity(project); } */ public void deleteProject(int id) throws UserProjectException { Project localProject = projectDAO.findById(id); if (localProject != null) { // TODO delete image from S3 by frontend //userProjectDAO.deleteByProjectStatus(new Integer(id),"B"); applicationDAO.deleteByProject_id(id); bookmarkDAO.deleteByProject_id(id); projectSkillDAO.deleteByProjectId(id); projectDAO.deleteProject(id); } else { System.out.println("Project does not exist."); } } /*------------------------------------ private methods-------------------------------------------*/ /*@Async private void sendEmail(User user, Project project, String status) { Integer orgId = project.getOrganization().getId(); List<User> users = userDAO.findByOrgId(orgId); if (users != null && !users.isEmpty()) { List<String> userSkills = skillService.findSkillsForUser(user.getId()); User orgUser = users.get(0); Organization org = organizationDAO.findOne(project.getOrganization().getId()); if (status.equals("A")) { // send email to organization Map<String, Object> contextOrg = new HashMap<String, Object>(); contextOrg.put("user", user); contextOrg.put("skills", userSkills); contextOrg.put("project", project); contextOrg.put("projectLink", urlService.getProjectUrl(project.getId())); contextOrg.put("userLink", urlService.getUserUrl(user.getId())); asyncEmailService.sendWithContext(Constants.C4SG_ADDRESS, orgUser.getEmail(),user.getEmail(), Constants.SUBJECT_APPLICAITON_ORGANIZATION, Constants.TEMPLATE_APPLICAITON_ORGANIZATION, contextOrg); // send email to volunteer Map<String, Object> contextVolunteer = new HashMap<String, Object>(); contextVolunteer.put("org", org); contextVolunteer.put("orgUser", orgUser); contextVolunteer.put("project", project); contextVolunteer.put("projectLink", urlService.getProjectUrl(project.getId())); asyncEmailService.sendWithContext(Constants.C4SG_ADDRESS, user.getEmail(), orgUser.getEmail(), Constants.SUBJECT_APPLICAITON_VOLUNTEER, Constants.TEMPLATE_APPLICAITON_VOLUNTEER, contextVolunteer); System.out.println("Application email sent: Project=" + project.getId() + " ; ApplicantEmail=" + user.getEmail() + " ; OrgEmail=" + orgUser.getEmail()); } else if (status.equals("C")) { // send email to volunteer Map<String, Object> contextVolunteer = new HashMap<String, Object>(); contextVolunteer.put("org", org); contextVolunteer.put("orgUser", orgUser); contextVolunteer.put("project", project); contextVolunteer.put("projectLink", urlService.getProjectUrl(project.getId())); asyncEmailService.sendWithContext(Constants.C4SG_ADDRESS, user.getEmail(), orgUser.getEmail(), Constants.SUBJECT_APPLICAITON_ACCEPT, Constants.TEMPLATE_APPLICAITON_ACCEPT, contextVolunteer); System.out.println("Application email sent: Project=" + project.getId() + " ; ApplicantEmail=" + user.getEmail()); } else if (status.equals("D")) { // send email to volunteer Map<String, Object> contextVolunteer = new HashMap<String, Object>(); contextVolunteer.put("org", org); contextVolunteer.put("orgUser", orgUser); contextVolunteer.put("project", project); contextVolunteer.put("projectLink", urlService.getProjectUrl(project.getId())); asyncEmailService.sendWithContext(Constants.C4SG_ADDRESS, user.getEmail(), orgUser.getEmail(), Constants.SUBJECT_APPLICAITON_DECLINE, Constants.TEMPLATE_APPLICAITON_DECLINE, contextVolunteer); System.out.println("Application email sent: Project=" + project.getId() + " ; ApplicantEmail=" + user.getEmail()); } else if (status.equals("B")) { // do nothing } } }*/ /*private void isRecordExist(Integer userId, Integer projectId, String status) throws UserProjectException { List<UserProject> userProjects = userProjectDAO.findByUser_IdAndProject_IdAndStatus(userId, projectId, status); requireNonNull(userProjects, "Invalid operation"); for(UserProject userProject : userProjects) { if(userProject.getStatus().equals(status)) { throw new UserProjectException("Record already exist"); } } }*/ /*private void isApplied(Application application, String status) throws UserProjectException { //Application application = applicationDAO.findByUser_IdAndProject_Id(userId, projectId); //requireNonNull(application, "Invalid operation"); if(status.equals("A") && java.util.Objects.nonNull(application.getAppliedTime())) { throw new UserProjectException("Already applied for the porject."); } else if (status.equals("C") && java.util.Objects.nonNull(application.getAcceptedTime())){ throw new UserProjectException("Already accepted for the porject."); } else if (status.equals("D") && java.util.Objects.nonNull(application.getDeclinedTime())){ throw new UserProjectException("Already declined for the porject."); } }*/ private void addProjectAndUrlToContext(Map<String, Object> context, ProjectDTO projectDTO) { context.put("project", projectDTO); context.put("projectLink", urlService.getProjectUrl(projectDTO.getId())); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.tools.groovydoc; import org.codehaus.groovy.groovydoc.GroovyAnnotationRef; import org.codehaus.groovy.groovydoc.GroovyClassDoc; import org.codehaus.groovy.groovydoc.GroovyConstructorDoc; import org.codehaus.groovy.groovydoc.GroovyFieldDoc; import org.codehaus.groovy.groovydoc.GroovyMethodDoc; import org.codehaus.groovy.groovydoc.GroovyPackageDoc; import org.codehaus.groovy.groovydoc.GroovyParameter; import org.codehaus.groovy.groovydoc.GroovyRootDoc; import org.codehaus.groovy.groovydoc.GroovyType; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc implements GroovyClassDoc { public static final Pattern TAG_REGEX = Pattern.compile("(?sm)\\s*@([a-zA-Z.]+)\\s+(.*?)(?=\\s+@)"); public static final String DOCROOT_PATTERN2 = "(?m)[{]@docRoot}/"; public static final String DOCROOT_PATTERN = "(?m)[{]@docRoot}"; // group 1: tag name, group 2: tag body public static final Pattern LINK_REGEX = Pattern.compile("(?m)[{]@(link)\\s+([^}]*)}"); public static final Pattern LITERAL_REGEX = Pattern.compile("(?m)[{]@(literal)\\s+([^}]*)}"); public static final Pattern CODE_REGEX = Pattern.compile("(?m)[{]@(code)\\s+([^}]*)}"); public static final Pattern REF_LABEL_REGEX = Pattern.compile("([\\w.#\\$]*(\\(.*\\))?)(\\s(.*))?"); public static final Pattern NAME_ARGS_REGEX = Pattern.compile("([^(]+)\\(([^)]*)\\)"); public static final Pattern SPLIT_ARGS_REGEX = Pattern.compile(",\\s*"); private static final List<String> PRIMITIVES = Arrays.asList("void", "boolean", "byte", "short", "char", "int", "long", "float", "double"); private static final Map<String, String> TAG_TEXT = new LinkedHashMap<String, String>(); private static final GroovyConstructorDoc[] EMPTY_GROOVYCONSTRUCTORDOC_ARRAY = new GroovyConstructorDoc[0]; private static final GroovyClassDoc[] EMPTY_GROOVYCLASSDOC_ARRAY = new GroovyClassDoc[0]; private static final GroovyFieldDoc[] EMPTY_GROOVYFIELDDOC_ARRAY = new GroovyFieldDoc[0]; private static final GroovyMethodDoc[] EMPTY_GROOVYMETHODDOC_ARRAY = new GroovyMethodDoc[0]; static { TAG_TEXT.put("see", "See Also"); TAG_TEXT.put("param", "Parameters"); TAG_TEXT.put("throw", "Throws"); TAG_TEXT.put("exception", "Throws"); TAG_TEXT.put("return", "Returns"); TAG_TEXT.put("since", "Since"); TAG_TEXT.put("author", "Authors"); TAG_TEXT.put("version", "Version"); TAG_TEXT.put("default", "Default"); // typeparam is used internally as a specialization of param to separate type params from regular params. TAG_TEXT.put("typeparam", "Type Parameters"); } private final List<GroovyConstructorDoc> constructors; private final List<GroovyFieldDoc> fields; private final List<GroovyFieldDoc> properties; private final List<GroovyFieldDoc> enumConstants; private final List<GroovyMethodDoc> methods; private final List<String> importedClassesAndPackages; private final Map<String, String> aliases; private final List<String> interfaceNames; private final List<GroovyClassDoc> interfaceClasses; private final List<GroovyClassDoc> nested; private final List<LinkArgument> links; private final Map<String, Class<?>> resolvedExternalClassesCache; private GroovyClassDoc superClass; private GroovyClassDoc outer; private String superClassName; private String fullPathName; private boolean isgroovy; private GroovyRootDoc savedRootDoc = null; private String nameWithTypeArgs; public SimpleGroovyClassDoc(List<String> importedClassesAndPackages, Map<String, String> aliases, String name, List<LinkArgument> links) { super(name); this.importedClassesAndPackages = importedClassesAndPackages; this.aliases = aliases; this.links = links; constructors = new ArrayList<GroovyConstructorDoc>(); fields = new ArrayList<GroovyFieldDoc>(); properties = new ArrayList<GroovyFieldDoc>(); enumConstants = new ArrayList<GroovyFieldDoc>(); methods = new ArrayList<GroovyMethodDoc>(); interfaceNames = new ArrayList<String>(); interfaceClasses = new ArrayList<GroovyClassDoc>(); nested = new ArrayList<GroovyClassDoc>(); resolvedExternalClassesCache = new HashMap<String, Class<?>>(); } public SimpleGroovyClassDoc(List<String> importedClassesAndPackages, Map<String, String> aliases, String name) { this(importedClassesAndPackages, aliases, name, new ArrayList<LinkArgument>()); } public SimpleGroovyClassDoc(List<String> importedClassesAndPackages, String name) { this(importedClassesAndPackages, new LinkedHashMap<String, String>(), name, new ArrayList<LinkArgument>()); } /** * returns a sorted array of constructors */ @Override public GroovyConstructorDoc[] constructors() { Collections.sort(constructors); return constructors.toArray(EMPTY_GROOVYCONSTRUCTORDOC_ARRAY); } public boolean add(GroovyConstructorDoc constructor) { return constructors.add(constructor); } // TODO remove? public GroovyClassDoc getOuter() { return outer; } public void setOuter(GroovyClassDoc outer) { this.outer = outer; } public boolean isGroovy() { return isgroovy; } public void setGroovy(boolean isgroovy) { this.isgroovy = isgroovy; } /** * returns a sorted array of nested classes and interfaces */ @Override public GroovyClassDoc[] innerClasses() { Collections.sort(nested); return nested.toArray(EMPTY_GROOVYCLASSDOC_ARRAY); } public boolean addNested(GroovyClassDoc nestedClass) { return nested.add(nestedClass); } /** * returns a sorted array of fields */ @Override public GroovyFieldDoc[] fields() { Collections.sort(fields); return fields.toArray(EMPTY_GROOVYFIELDDOC_ARRAY); } public boolean add(GroovyFieldDoc field) { return fields.add(field); } /** * returns a sorted array of properties */ @Override public GroovyFieldDoc[] properties() { Collections.sort(properties); return properties.toArray(EMPTY_GROOVYFIELDDOC_ARRAY); } public boolean addProperty(GroovyFieldDoc property) { return properties.add(property); } /** * returns a sorted array of enum constants */ @Override public GroovyFieldDoc[] enumConstants() { Collections.sort(enumConstants); return enumConstants.toArray(EMPTY_GROOVYFIELDDOC_ARRAY); } public boolean addEnumConstant(GroovyFieldDoc field) { return enumConstants.add(field); } /** * returns a sorted array of methods */ @Override public GroovyMethodDoc[] methods() { Collections.sort(methods); return methods.toArray(EMPTY_GROOVYMETHODDOC_ARRAY); } public boolean add(GroovyMethodDoc method) { return methods.add(method); } public String getSuperClassName() { return superClassName; } public void setSuperClassName(String className) { superClassName = className; } @Override public GroovyClassDoc superclass() { return superClass; } public void setSuperClass(GroovyClassDoc doc) { superClass = doc; } @Override public String getFullPathName() { return fullPathName; } public void setFullPathName(String fullPathName) { this.fullPathName = fullPathName; } @Override public String getRelativeRootPath() { StringTokenizer tokenizer = new StringTokenizer(fullPathName, "/"); // todo windows?? StringBuilder sb = new StringBuilder(); if (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); // ignore the first token, as we want n-1 parent dirs } while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); sb.append("../"); } return sb.toString(); } // TODO move logic here into resolve public List<GroovyClassDoc> getParentClasses() { List<GroovyClassDoc> result = new LinkedList<GroovyClassDoc>(); if (isInterface()) return result; result.add(0, this); GroovyClassDoc next = this; while (next.superclass() != null && !"java.lang.Object".equals(next.qualifiedTypeName())) { next = next.superclass(); result.add(0, next); } GroovyClassDoc prev = next; Class nextClass = getClassOf(next.qualifiedTypeName()); while (nextClass != null && nextClass.getSuperclass() != null && !Object.class.equals(nextClass)) { nextClass = nextClass.getSuperclass(); GroovyClassDoc nextDoc = new ExternalGroovyClassDoc(nextClass); if (prev instanceof SimpleGroovyClassDoc) { SimpleGroovyClassDoc parent = (SimpleGroovyClassDoc) prev; parent.setSuperClass(nextDoc); } result.add(0, nextDoc); prev = nextDoc; } if (!result.get(0).qualifiedTypeName().equals("java.lang.Object")) { result.add(0, new ExternalGroovyClassDoc(Object.class)); } return result; } public Set<GroovyClassDoc> getParentInterfaces() { Set<GroovyClassDoc> result = new LinkedHashSet<GroovyClassDoc>(); result.add(this); Set<GroovyClassDoc> next = new LinkedHashSet<GroovyClassDoc>(Arrays.asList(this.interfaces())); while (!next.isEmpty()) { Set<GroovyClassDoc> temp = next; next = new LinkedHashSet<GroovyClassDoc>(); for (GroovyClassDoc t : temp) { if (t instanceof SimpleGroovyClassDoc) { next.addAll(((SimpleGroovyClassDoc)t).getParentInterfaces()); } else if (t instanceof ExternalGroovyClassDoc) { ExternalGroovyClassDoc d = (ExternalGroovyClassDoc) t; next.addAll(getJavaInterfaces(d)); } } next = DefaultGroovyMethods.minus(next, result); result.addAll(next); } return result; } private Set<GroovyClassDoc> getJavaInterfaces(ExternalGroovyClassDoc d) { Set<GroovyClassDoc> result = new LinkedHashSet<GroovyClassDoc>(); Class[] interfaces = d.externalClass().getInterfaces(); if (interfaces != null) { for (Class i : interfaces) { ExternalGroovyClassDoc doc = new ExternalGroovyClassDoc(i); result.add(doc); result.addAll(getJavaInterfaces(doc)); } } return result; } private Class getClassOf(String next) { try { return Class.forName(next.replace("/", "."), false, getClass().getClassLoader()); } catch (Throwable t) { return null; } } private void processAnnotationRefs(GroovyRootDoc rootDoc, GroovyAnnotationRef[] annotations) { for (GroovyAnnotationRef annotation : annotations) { SimpleGroovyAnnotationRef ref = (SimpleGroovyAnnotationRef) annotation; ref.setType(resolveClass(rootDoc, ref.name())); } } void resolve(GroovyRootDoc rootDoc) { this.savedRootDoc = rootDoc; Map visibleClasses = rootDoc.getVisibleClasses(importedClassesAndPackages); // resolve constructor parameter types for (GroovyConstructorDoc constructor : constructors) { // parameters for (GroovyParameter groovyParameter : constructor.parameters()) { SimpleGroovyParameter param = (SimpleGroovyParameter) groovyParameter; String paramTypeName = param.typeName(); if (visibleClasses.containsKey(paramTypeName)) { param.setType((GroovyType) visibleClasses.get(paramTypeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, paramTypeName); if (doc != null) param.setType(doc); } processAnnotationRefs(rootDoc, param.annotations()); } processAnnotationRefs(rootDoc, constructor.annotations()); } for (GroovyFieldDoc field : fields) { SimpleGroovyFieldDoc mutableField = (SimpleGroovyFieldDoc) field; GroovyType fieldType = field.type(); String typeName = fieldType.typeName(); if (visibleClasses.containsKey(typeName)) { mutableField.setType((GroovyType) visibleClasses.get(typeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, typeName); if (doc != null) mutableField.setType(doc); } processAnnotationRefs(rootDoc, field.annotations()); } // resolve method return types and parameter types for (GroovyMethodDoc method : methods) { // return types GroovyType returnType = method.returnType(); String typeName = returnType.typeName(); if (visibleClasses.containsKey(typeName)) { method.setReturnType((GroovyType) visibleClasses.get(typeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, typeName); if (doc != null) method.setReturnType(doc); } // parameters for (GroovyParameter groovyParameter : method.parameters()) { SimpleGroovyParameter param = (SimpleGroovyParameter) groovyParameter; String paramTypeName = param.typeName(); if (visibleClasses.containsKey(paramTypeName)) { param.setType((GroovyType) visibleClasses.get(paramTypeName)); } else { GroovyClassDoc doc = resolveClass(rootDoc, paramTypeName); if (doc != null) param.setType(doc); } processAnnotationRefs(rootDoc, param.annotations()); } processAnnotationRefs(rootDoc, method.annotations()); } // resolve property types for (GroovyFieldDoc property : properties) { if (property instanceof SimpleGroovyFieldDoc) { SimpleGroovyFieldDoc simpleGroovyFieldDoc = (SimpleGroovyFieldDoc) property; if (simpleGroovyFieldDoc.type() instanceof SimpleGroovyType) { SimpleGroovyType simpleGroovyType = (SimpleGroovyType) simpleGroovyFieldDoc.type(); GroovyClassDoc propertyTypeClassDoc = resolveClass(rootDoc, simpleGroovyType.qualifiedTypeName()); if (propertyTypeClassDoc != null) { simpleGroovyFieldDoc.setType(propertyTypeClassDoc); } } } processAnnotationRefs(rootDoc, property.annotations()); } if (superClassName != null && superClass == null) { superClass = resolveClass(rootDoc, superClassName); } for (String name : interfaceNames) { interfaceClasses.add(resolveClass(rootDoc, name)); } processAnnotationRefs(rootDoc, annotations()); } public String getDocUrl(String type) { return getDocUrl(type, false); } public String getDocUrl(String type, boolean full) { return getDocUrl(type, full, links, getRelativeRootPath(), savedRootDoc, this); } private static String resolveMethodArgs(GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc, String type) { if (!type.contains("(")) return type; Matcher m = NAME_ARGS_REGEX.matcher(type); if (m.matches()) { String name = m.group(1); String args = m.group(2); StringBuilder sb = new StringBuilder(); sb.append(name); sb.append("("); String[] argParts = SPLIT_ARGS_REGEX.split(args); boolean first = true; for (String argPart : argParts) { if (first) first = false; else sb.append(", "); GroovyClassDoc doc = classDoc.resolveClass(rootDoc, argPart); sb.append(doc == null ? argPart : doc.qualifiedTypeName()); } sb.append(")"); return sb.toString(); } return type; } public static String getDocUrl(String type, boolean full, List<LinkArgument> links, String relativePath, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) { if (type == null) return type; type = type.trim(); if (isPrimitiveType(type) || type.length() == 1) return type; if (type.equals("def")) type = "java.lang.Object def"; // cater for explicit href in e.g. @see, TODO: push this earlier? if (type.startsWith("<a href=")) return type; if (type.startsWith("? extends ")) return "? extends " + getDocUrl(type.substring(10), full, links, relativePath, rootDoc, classDoc); if (type.startsWith("? super ")) return "? super " + getDocUrl(type.substring(8), full, links, relativePath, rootDoc, classDoc); String label = null; int lt = type.indexOf('<'); if (lt != -1) { String outerType = type.substring(0, lt); int gt = type.lastIndexOf('>'); if (gt != -1) { if (gt > lt) { String allTypeArgs = type.substring(lt + 1, gt); List<String> typeArgs = new ArrayList<String>(); int nested = 0; StringBuilder sb = new StringBuilder(); for (char ch : allTypeArgs.toCharArray()) { if (ch == '<') nested++; else if (ch == '>') nested--; else if (ch == ',' && nested == 0) { typeArgs.add(sb.toString().trim()); sb = new StringBuilder(); continue; } sb.append(ch); } if (sb.length() > 0) { typeArgs.add(sb.toString().trim()); } List<String> typeUrls = new ArrayList<String>(); for (String typeArg : typeArgs) { typeUrls.add(getDocUrl(typeArg, full, links, relativePath, rootDoc, classDoc)); } sb = new StringBuilder(getDocUrl(outerType, full, links, relativePath, rootDoc, classDoc)); sb.append("&lt;"); sb.append(DefaultGroovyMethods.join((Iterable) typeUrls, ", ")); sb.append("&gt;"); return sb.toString(); } return type.replace("<", "&lt;").replace(">", "&gt;"); } } Matcher matcher = REF_LABEL_REGEX.matcher(type); if (matcher.find()) { type = matcher.group(1); label = matcher.group(4); } if (type.startsWith("#")) return "<a href='" + resolveMethodArgs(rootDoc, classDoc, type) + "'>" + (label == null ? type.substring(1) : label) + "</a>"; if (type.endsWith("[]")) { String componentType = type.substring(0, type.length() - 2); if (label != null) return getDocUrl(componentType + " " + label, full, links, relativePath, rootDoc, classDoc); return getDocUrl(componentType, full, links, relativePath, rootDoc, classDoc) + "[]"; } if (!type.contains(".") && classDoc != null) { String[] pieces = type.split("#", -1); String candidate = pieces[0]; Class c = classDoc.resolveExternalClassFromImport(candidate); if (c != null) type = c.getName(); if (pieces.length > 1) type += "#" + pieces[1]; type = resolveMethodArgs(rootDoc, classDoc, type); } final String[] target = type.split("#"); String shortClassName = target[0].replaceAll(".*\\.", ""); shortClassName += (target.length > 1 ? "#" + target[1].split("\\(", -1)[0] : ""); String name = (full ? target[0] : shortClassName).replace('#', '.').replace('$', '.'); // last chance lookup for classes within the current codebase if (rootDoc != null) { String slashedName = target[0].replace('.', '/'); GroovyClassDoc doc = rootDoc.classNamed(classDoc, slashedName); if (doc != null) { target[0] = doc.getFullPathName(); // if we added a package return buildUrl(relativePath, target, label == null ? name : label); } } if (type.indexOf('.') == -1) return type; if (links != null) { for (LinkArgument link : links) { final StringTokenizer tokenizer = new StringTokenizer(link.getPackages(), ", "); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); if (type.startsWith(token)) { return buildUrl(link.getHref(), target, label == null ? name : label); } } } } return type; } private static String buildUrl(String relativeRoot, String[] target, String shortClassName) { if (relativeRoot.length() > 0 && !relativeRoot.endsWith("/")) { relativeRoot += "/"; } String url = relativeRoot + target[0].replace('.', '/').replace('$', '.') + ".html" + (target.length > 1 ? "#" + target[1] : ""); return "<a href='" + url + "' title='" + shortClassName + "'>" + shortClassName + "</a>"; } private GroovyClassDoc resolveClass(GroovyRootDoc rootDoc, String name) { if (isPrimitiveType(name)) return null; GroovyClassDoc groovyClassDoc; Map<String, GroovyClassDoc> resolvedClasses = null; if (rootDoc != null) { resolvedClasses = rootDoc.getResolvedClasses(); groovyClassDoc = resolvedClasses.get(name); if (groovyClassDoc != null) { return groovyClassDoc; } } groovyClassDoc = doResolveClass(rootDoc, name); if (resolvedClasses != null) { resolvedClasses.put(name, groovyClassDoc); } return groovyClassDoc; } private GroovyClassDoc doResolveClass(final GroovyRootDoc rootDoc, final String name) { if (name.endsWith("[]")) { GroovyClassDoc componentClass = resolveClass(rootDoc, name.substring(0, name.length() - 2)); if (componentClass != null) return new ArrayClassDocWrapper(componentClass); return null; } // if (name.equals("T") || name.equals("U") || name.equals("K") || name.equals("V") || name.equals("G")) { // name = "java/lang/Object"; // } int slashIndex = name.lastIndexOf('/'); if (rootDoc != null) { GroovyClassDoc doc = ((SimpleGroovyRootDoc)rootDoc).classNamedExact(name); if (doc != null) return doc; if (slashIndex < 1) { doc = resolveInternalClassDocFromImport(rootDoc, name); if (doc != null) return doc; doc = resolveInternalClassDocFromSamePackage(rootDoc, name); if (doc != null) return doc; for (GroovyClassDoc nestedDoc : nested) { if (nestedDoc.name().endsWith("." + name)) return nestedDoc; } doc = rootDoc.classNamed(this, name); if (doc != null) return doc; } } // The class is not in the tree being documented String shortname = name; Class c; if (slashIndex > 0) { shortname = name.substring(slashIndex + 1); c = resolveExternalFullyQualifiedClass(name); } else { c = resolveExternalClassFromImport(name); } if (c == null) { c = resolveFromJavaLang(name); } if (c != null) { return new ExternalGroovyClassDoc(c); } if (name.contains("/")) { // search for nested class if (slashIndex > 0) { String outerName = name.substring(0, slashIndex); GroovyClassDoc gcd = resolveClass(rootDoc, outerName); if (gcd instanceof ExternalGroovyClassDoc) { ExternalGroovyClassDoc egcd = (ExternalGroovyClassDoc) gcd; String innerName = name.substring(slashIndex+1); Class outerClass = egcd.externalClass(); for (Class inner : outerClass.getDeclaredClasses()) { if (inner.getName().equals(outerClass.getName() + "$" + innerName)) { return new ExternalGroovyClassDoc(inner); } } } if (gcd instanceof SimpleGroovyClassDoc) { String innerClassName = name.substring(slashIndex + 1); SimpleGroovyClassDoc innerClass = new SimpleGroovyClassDoc(importedClassesAndPackages, aliases, innerClassName); innerClass.setFullPathName(gcd.getFullPathName() + "." + innerClassName); return innerClass; } } } // check if the name is actually an aliased type name if (hasAlias(name)) { String fullyQualifiedTypeName = getFullyQualifiedTypeNameForAlias(name); GroovyClassDoc gcd = resolveClass(rootDoc, fullyQualifiedTypeName); if (gcd != null) return gcd; } // and we can't find it SimpleGroovyClassDoc placeholder = new SimpleGroovyClassDoc(null, shortname); placeholder.setFullPathName(name); return placeholder; } private Class resolveFromJavaLang(String name) { try { return Class.forName("java.lang." + name, false, getClass().getClassLoader()); } catch (NoClassDefFoundError | ClassNotFoundException e) { // ignore } return null; } private static boolean isPrimitiveType(String name) { String type = name; if (name.endsWith("[]")) type = name.substring(0, name.length() - 2); return PRIMITIVES.contains(type); } private GroovyClassDoc resolveInternalClassDocFromImport(GroovyRootDoc rootDoc, String baseName) { if (isPrimitiveType(baseName)) return null; for (String importName : importedClassesAndPackages) { if (importName.endsWith("/" + baseName)) { GroovyClassDoc doc = ((SimpleGroovyRootDoc)rootDoc).classNamedExact(importName); if (doc != null) return doc; } else if (importName.endsWith("/*")) { GroovyClassDoc doc = ((SimpleGroovyRootDoc)rootDoc).classNamedExact(importName.substring(0, importName.length() - 2) + baseName); if (doc != null) return doc; } } return null; } private GroovyClassDoc resolveInternalClassDocFromSamePackage(GroovyRootDoc rootDoc, String baseName) { if (isPrimitiveType(baseName)) return null; if (baseName.contains(".")) return null; int lastSlash = fullPathName.lastIndexOf('/'); if (lastSlash < 0) return null; String pkg = fullPathName.substring(0, lastSlash + 1); return ((SimpleGroovyRootDoc)rootDoc).classNamedExact(pkg + baseName); } private Class resolveExternalClassFromImport(String name) { if (isPrimitiveType(name)) return null; Class<?> clazz = resolvedExternalClassesCache.get(name); if (clazz == null) { if (resolvedExternalClassesCache.containsKey(name)) { return null; } clazz = doResolveExternalClassFromImport(name); resolvedExternalClassesCache.put(name, clazz); } return clazz; } private Class doResolveExternalClassFromImport(final String name) { for (String importName : importedClassesAndPackages) { String candidate = null; if (importName.endsWith("/" + name)) { candidate = importName.replace('/', '.'); } else if (importName.endsWith("/*")) { candidate = importName.substring(0, importName.length() - 2).replace('/', '.') + "." + name; } if (candidate != null) { try { // TODO cache these?? return Class.forName(candidate, false, getClass().getClassLoader()); } catch (NoClassDefFoundError | ClassNotFoundException e) { // ignore } } } return null; } private Class resolveExternalFullyQualifiedClass(String name) { String candidate = name.replace('/', '.'); try { // TODO cache these?? return Class.forName(candidate, false, getClass().getClassLoader()); } catch (NoClassDefFoundError | ClassNotFoundException e) { // ignore } return null; } private boolean hasAlias(String alias) { return aliases.containsKey(alias); } private String getFullyQualifiedTypeNameForAlias(String alias) { if (!hasAlias(alias)) return ""; return aliases.get(alias); } // methods from GroovyClassDoc @Override public GroovyConstructorDoc[] constructors(boolean filter) {/*todo*/ return null; } @Override public boolean definesSerializableFields() {/*todo*/ return false; } @Override public GroovyFieldDoc[] fields(boolean filter) {/*todo*/ return null; } @Override public GroovyClassDoc findClass(String className) {/*todo*/ return null; } @Override public GroovyClassDoc[] importedClasses() {/*todo*/ return null; } @Override public GroovyPackageDoc[] importedPackages() {/*todo*/ return null; } @Override public GroovyClassDoc[] innerClasses(boolean filter) {/*todo*/ return null; } @Override public GroovyClassDoc[] interfaces() { Collections.sort(interfaceClasses); return interfaceClasses.toArray(EMPTY_GROOVYCLASSDOC_ARRAY); } @Override public GroovyType[] interfaceTypes() {/*todo*/ return null; } @Override public boolean isExternalizable() {/*todo*/ return false; } @Override public boolean isSerializable() {/*todo*/ return false; } @Override public GroovyMethodDoc[] methods(boolean filter) {/*todo*/ return null; } @Override public GroovyFieldDoc[] serializableFields() {/*todo*/ return null; } @Override public GroovyMethodDoc[] serializationMethods() {/*todo*/ return null; } @Override public boolean subclassOf(GroovyClassDoc gcd) {/*todo*/ return false; } @Override public GroovyType superclassType() {/*todo*/ return null; } // public GroovyTypeVariable[] typeParameters() {/*todo*/return null;} // not supported in groovy // public GroovyParamTag[] typeParamTags() {/*todo*/return null;} // not supported in groovy // methods from GroovyType (todo: remove this horrible copy of SimpleGroovyType.java) // public GroovyAnnotationTypeDoc asAnnotationTypeDoc() {/*todo*/return null;} // public GroovyClassDoc asClassDoc() {/*todo*/ return null; } // public GroovyParameterizedType asParameterizedType() {/*todo*/return null;} // public GroovyTypeVariable asTypeVariable() {/*todo*/return null;} // public GroovyWildcardType asWildcardType() {/*todo*/return null;} // public String dimension() {/*todo*/ return null; } @Override public boolean isPrimitive() {/*todo*/ return false; } @Override public String qualifiedTypeName() { String qtnWithSlashes = fullPathName.startsWith("DefaultPackage/") ? fullPathName.substring("DefaultPackage/".length()) : fullPathName; return qtnWithSlashes.replace('/', '.'); } // TODO remove dupe with SimpleGroovyType @Override public String simpleTypeName() { String typeName = qualifiedTypeName(); int lastDot = typeName.lastIndexOf('.'); if (lastDot < 0) return typeName; return typeName.substring(lastDot + 1); } @Override public String typeName() { return qualifiedTypeName(); } public void addInterfaceName(String className) { interfaceNames.add(className); } @Override public String firstSentenceCommentText() { if (super.firstSentenceCommentText() == null) setFirstSentenceCommentText(replaceTags(calculateFirstSentence(getRawCommentText()))); return super.firstSentenceCommentText(); } @Override public String commentText() { if (super.commentText() == null) setCommentText(replaceTags(getRawCommentText())); return super.commentText(); } public String replaceTags(String comment) { String result = comment.replaceAll("(?m)^\\s*\\*", ""); // todo precompile regex String relativeRootPath = getRelativeRootPath(); if (!relativeRootPath.endsWith("/")) { relativeRootPath += "/"; } result = result.replaceAll(DOCROOT_PATTERN2, relativeRootPath); result = result.replaceAll(DOCROOT_PATTERN, relativeRootPath); // {@link processing hack} result = replaceAllTags(result, "", "", LINK_REGEX); // {@literal tag} result = encodeAngleBracketsInTagBody(result, LITERAL_REGEX); result = replaceAllTags(result, "", "", LITERAL_REGEX); // {@code tag} result = encodeAngleBracketsInTagBody(result, CODE_REGEX); result = replaceAllTags(result, "<CODE>", "</CODE>", CODE_REGEX); // hack to reformat other groovydoc block tags (@see, @return, @param, @throws, @author, @since) into html result = replaceAllTagsCollated(result, "<DL><DT><B>", ":</B></DT><DD>", "</DD><DD>", "</DD></DL>", TAG_REGEX); return decodeSpecialSymbols(result); } public String replaceAllTags(String self, String s1, String s2, Pattern regex) { return replaceAllTags(self, s1, s2, regex, links, getRelativeRootPath(), savedRootDoc, this); } // TODO: this should go away once we have proper tags public static String replaceAllTags(String self, String s1, String s2, Pattern regex, List<LinkArgument> links, String relPath, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) { Matcher matcher = regex.matcher(self); if (matcher.find()) { matcher.reset(); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String tagname = matcher.group(1); if (!"interface".equals(tagname)) { String content = encodeSpecialSymbols(matcher.group(2)); if ("link".equals(tagname) || "see".equals(tagname)) { content = getDocUrl(content, false, links, relPath, rootDoc, classDoc); } matcher.appendReplacement(sb, s1 + content + s2); } } matcher.appendTail(sb); return sb.toString(); } else { return self; } } // TODO: is there a better way to do this? public String replaceAllTagsCollated(String self, String preKey, String postKey, String valueSeparator, String postValues, Pattern regex) { Matcher matcher = regex.matcher(self + " @endMarker"); if (matcher.find()) { matcher.reset(); Map<String, List<String>> savedTags = new LinkedHashMap<String, List<String>>(); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String tagname = matcher.group(1); if (!"interface".equals(tagname)) { String content = encodeSpecialSymbols(matcher.group(2)); if ("see".equals(tagname) || "link".equals(tagname)) { content = getDocUrl(content); } else if ("param".equals(tagname)) { int index = content.indexOf(' '); if (index >= 0) { String paramName = content.substring(0, index); String paramDesc = content.substring(index); if (paramName.startsWith("<") && paramName.endsWith(">")) { paramName = paramName.substring(1, paramName.length() - 1); tagname = "typeparam"; } content = "<code>" + paramName + "</code> - " + paramDesc; } } if (TAG_TEXT.containsKey(tagname)) { String text = TAG_TEXT.get(tagname); List<String> contents = savedTags.computeIfAbsent(text, k -> new ArrayList<String>()); contents.add(content); matcher.appendReplacement(sb, ""); } else { matcher.appendReplacement(sb, preKey + tagname + postKey + content + postValues); } } } matcher.appendTail(sb); // remove @endMarker sb = new StringBuffer(sb.substring(0, sb.length() - 10)); for (Map.Entry<String, List<String>> e : savedTags.entrySet()) { sb.append(preKey); sb.append(e.getKey()); sb.append(postKey); sb.append(DefaultGroovyMethods.join((Iterable)e.getValue(), valueSeparator)); sb.append(postValues); } return sb.toString(); } else { return self; } } /** * Replaces angle brackets inside a tag. * * @param text GroovyDoc text to process * @param regex has to capture tag name in group 1 and tag body in group 2 */ public static String encodeAngleBracketsInTagBody(String text, Pattern regex) { Matcher matcher = regex.matcher(text); if (matcher.find()) { matcher.reset(); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String tagName = matcher.group(1); String tagBody = matcher.group(2); String encodedBody = Matcher.quoteReplacement(encodeAngleBrackets(tagBody)); String replacement = "{@" + tagName + " " + encodedBody + "}"; matcher.appendReplacement(sb, replacement); } matcher.appendTail(sb); return sb.toString(); } else { return text; } } public static String encodeAngleBrackets(String text) { return text == null ? null : text.replace("<", "&lt;").replace(">", "&gt;"); } public static String encodeSpecialSymbols(String text) { return Matcher.quoteReplacement(text.replace("@", "&at;")); } public static String decodeSpecialSymbols(String text) { return text.replace("&at;", "@"); } public void setNameWithTypeArgs(String nameWithTypeArgs) { this.nameWithTypeArgs = nameWithTypeArgs; } public String getNameWithTypeArgs() { return nameWithTypeArgs; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.metastore.tools.schematool; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.ParseException; import org.apache.commons.io.output.NullOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.metastore.HiveMetaException; import org.apache.hadoop.hive.metastore.IMetaStoreSchemaInfo; import org.apache.hadoop.hive.metastore.MetaStoreSchemaInfoFactory; import org.apache.hadoop.hive.metastore.conf.MetastoreConf; import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars; import org.apache.hadoop.hive.metastore.tools.schematool.HiveSchemaHelper.MetaStoreConnectionInfo; import org.apache.hadoop.hive.metastore.tools.schematool.HiveSchemaHelper.NestedScriptParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sqlline.SqlLine; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.sql.Connection; import java.sql.SQLException; public class MetastoreSchemaTool { private static final Logger LOG = LoggerFactory.getLogger(MetastoreSchemaTool.class); private static final String PASSWD_MASK = "[passwd stripped]"; protected Configuration conf; protected String dbOpts = null; protected String dbType; protected String driver = null; protected boolean dryRun = false; protected String hiveDb; // Hive database, for use when creating the user, not for connecting protected String hivePasswd; // Hive password, for use when creating the user, not for connecting protected String hiveUser; // Hive username, for use when creating the user, not for connecting protected String metaDbType; protected IMetaStoreSchemaInfo metaStoreSchemaInfo; protected boolean needsQuotedIdentifier; protected String quoteCharacter; protected String passWord = null; protected String url = null; protected String userName = null; protected URI[] validationServers = null; // The list of servers the database/partition/table can locate on protected boolean verbose = false; protected SchemaToolCommandLine cmdLine; private static String homeDir; private static String findHomeDir() { // If METASTORE_HOME is set, use it, else use HIVE_HOME for backwards compatibility. homeDir = homeDir == null ? System.getenv("METASTORE_HOME") : homeDir; return homeDir == null ? System.getenv("HIVE_HOME") : homeDir; } @VisibleForTesting public static void setHomeDirForTesting() { homeDir = System.getProperty("test.tmp.dir", "target/tmp"); } @VisibleForTesting public MetastoreSchemaTool() { } @VisibleForTesting public void init(String metastoreHome, String[] args, OptionGroup additionalOptions, Configuration conf) throws HiveMetaException { try { cmdLine = new SchemaToolCommandLine(args, additionalOptions); } catch (ParseException e) { System.err.println("Failed to parse command line. "); throw new HiveMetaException(e); } if (metastoreHome == null || metastoreHome.isEmpty()) { throw new HiveMetaException("No Metastore home directory provided"); } this.conf = conf; this.dbType = cmdLine.getDbType(); this.metaDbType = cmdLine.getMetaDbType(); NestedScriptParser parser = getDbCommandParser(dbType, metaDbType); this.needsQuotedIdentifier = parser.needsQuotedIdentifier(); this.quoteCharacter = parser.getQuoteCharacter(); this.metaStoreSchemaInfo = MetaStoreSchemaInfoFactory.get(conf, metastoreHome, dbType); // If the dbType is "hive", this is setting up the information schema in Hive. // We will set the default jdbc url and driver. // It is overridden by command line options if passed (-url and -driver) if (dbType.equalsIgnoreCase(HiveSchemaHelper.DB_HIVE)) { this.url = HiveSchemaHelper.EMBEDDED_HS2_URL; this.driver = HiveSchemaHelper.HIVE_JDBC_DRIVER; } if (cmdLine.hasOption("userName")) { setUserName(cmdLine.getOptionValue("userName")); } else { setUserName(getConf().get(MetastoreConf.ConfVars.CONNECTION_USER_NAME.getVarname())); } if (cmdLine.hasOption("passWord")) { setPassWord(cmdLine.getOptionValue("passWord")); } else { try { setPassWord(MetastoreConf.getPassword(getConf(), ConfVars.PWD)); } catch (IOException err) { throw new HiveMetaException("Error getting metastore password", err); } } if (cmdLine.hasOption("url")) { setUrl(cmdLine.getOptionValue("url")); } if (cmdLine.hasOption("driver")) { setDriver(cmdLine.getOptionValue("driver")); } if (cmdLine.hasOption("dryRun")) { setDryRun(true); } if (cmdLine.hasOption("verbose")) { setVerbose(true); } if (cmdLine.hasOption("dbOpts")) { setDbOpts(cmdLine.getOptionValue("dbOpts")); } if (cmdLine.hasOption("validate") && cmdLine.hasOption("servers")) { setValidationServers(cmdLine.getOptionValue("servers")); } if (cmdLine.hasOption("hiveUser")) { setHiveUser(cmdLine.getOptionValue("hiveUser")); } if (cmdLine.hasOption("hivePassword")) { setHivePasswd(cmdLine.getOptionValue("hivePassword")); } if (cmdLine.hasOption("hiveDb")) { setHiveDb(cmdLine.getOptionValue("hiveDb")); } } public Configuration getConf() { return conf; } protected String getDbType() { return dbType; } protected void setUrl(String url) { this.url = url; } protected void setDriver(String driver) { this.driver = driver; } public void setUserName(String userName) { this.userName = userName; } public void setPassWord(String passWord) { this.passWord = passWord; } protected boolean isDryRun() { return dryRun; } protected void setDryRun(boolean dryRun) { this.dryRun = dryRun; } protected boolean isVerbose() { return verbose; } public MetastoreSchemaTool setVerbose(boolean verbose) { this.verbose = verbose; return this; } protected void setDbOpts(String dbOpts) { this.dbOpts = dbOpts; } protected URI[] getValidationServers() { return validationServers; } protected void setValidationServers(String servers) { if(StringUtils.isNotEmpty(servers)) { String[] strServers = servers.split(","); this.validationServers = new URI[strServers.length]; for (int i = 0; i < validationServers.length; i++) { validationServers[i] = new Path(strServers[i]).toUri(); } } } protected String getHiveUser() { return hiveUser; } protected void setHiveUser(String hiveUser) { this.hiveUser = hiveUser; } protected String getHivePasswd() { return hivePasswd; } protected void setHivePasswd(String hivePasswd) { this.hivePasswd = hivePasswd; } protected String getHiveDb() { return hiveDb; } protected void setHiveDb(String hiveDb) { this.hiveDb = hiveDb; } protected SchemaToolCommandLine getCmdLine() { return cmdLine; } public Connection getConnectionToMetastore(boolean printInfo) throws HiveMetaException { return HiveSchemaHelper.getConnectionToMetastore(userName, passWord, url, driver, printInfo, conf, null); } protected NestedScriptParser getDbCommandParser(String dbType, String metaDbType) { return HiveSchemaHelper.getDbCommandParser(dbType, dbOpts, userName, passWord, conf, null, true); } protected MetaStoreConnectionInfo getConnectionInfo(boolean printInfo) { return new MetaStoreConnectionInfo(userName, passWord, url, driver, printInfo, conf, dbType, hiveDb); } protected IMetaStoreSchemaInfo getMetaStoreSchemaInfo() { return metaStoreSchemaInfo; } /** * check if the current schema version in metastore matches the Hive version */ @VisibleForTesting void verifySchemaVersion() throws HiveMetaException { // don't check version if its a dry run if (dryRun) { return; } String newSchemaVersion = metaStoreSchemaInfo.getMetaStoreSchemaVersion(getConnectionInfo(false)); // verify that the new version is added to schema assertCompatibleVersion(metaStoreSchemaInfo.getHiveSchemaVersion(), newSchemaVersion); } protected void assertCompatibleVersion(String hiveSchemaVersion, String dbSchemaVersion) throws HiveMetaException { if (!metaStoreSchemaInfo.isVersionCompatible(hiveSchemaVersion, dbSchemaVersion)) { throw new HiveMetaException("Metastore schema version is not compatible. Hive Version: " + hiveSchemaVersion + ", Database Schema Version: " + dbSchemaVersion); } } /*** * Execute a given metastore script. This default version uses sqlline to execute the files, * which requires only running one file. Subclasses can use other executors. * @param scriptDir directory script is in * @param scriptFile file in the directory to run * @throws IOException if it cannot read the file or directory * @throws HiveMetaException default implementation never throws this */ protected void execSql(String scriptDir, String scriptFile) throws IOException, HiveMetaException { execSql(scriptDir + File.separatorChar + scriptFile); } // Generate the beeline args per hive conf and execute the given script protected void execSql(String sqlScriptFile) throws IOException { CommandBuilder builder = new CommandBuilder(conf, url, driver, userName, passWord, sqlScriptFile) .setVerbose(verbose); // run the script using SqlLine SqlLine sqlLine = new SqlLine(); ByteArrayOutputStream outputForLog = null; if (!verbose) { OutputStream out; if (LOG.isDebugEnabled()) { out = outputForLog = new ByteArrayOutputStream(); } else { out = new NullOutputStream(); } sqlLine.setOutputStream(new PrintStream(out)); System.setProperty("sqlline.silent", "true"); } LOG.info("Going to run command <" + builder.buildToLog() + ">"); SqlLine.Status status = sqlLine.begin(builder.buildToRun(), null, false); if (LOG.isDebugEnabled() && outputForLog != null) { LOG.debug("Received following output from Sqlline:"); LOG.debug(outputForLog.toString("UTF-8")); } if (status != SqlLine.Status.OK) { throw new IOException("Schema script failed, errorcode " + status); } } // test the connection metastore using the config property protected void testConnectionToMetastore() throws HiveMetaException { Connection conn = getConnectionToMetastore(true); try { conn.close(); } catch (SQLException e) { throw new HiveMetaException("Failed to close metastore connection", e); } } // Quote if the database requires it protected String quote(String stmt) { stmt = stmt.replace("<q>", needsQuotedIdentifier ? quoteCharacter : ""); stmt = stmt.replace("<qa>", quoteCharacter); return stmt; } protected static class CommandBuilder { protected final String userName; protected final String password; protected final String sqlScriptFile; protected final String driver; protected final String url; private boolean verbose = false; protected CommandBuilder(Configuration conf, String url, String driver, String userName, String password, String sqlScriptFile) throws IOException { this.userName = userName; this.password = password; this.url = url == null ? HiveSchemaHelper.getValidConfVar(MetastoreConf.ConfVars.CONNECT_URL_KEY, conf) : url; this.driver = driver == null ? HiveSchemaHelper.getValidConfVar(MetastoreConf.ConfVars.CONNECTION_DRIVER, conf) : driver; this.sqlScriptFile = sqlScriptFile; } public CommandBuilder setVerbose(boolean verbose) { this.verbose = verbose; return this; } public String[] buildToRun() throws IOException { return argsWith(password); } public String buildToLog() throws IOException { if (verbose) { logScript(); } return StringUtils.join(argsWith(PASSWD_MASK), " "); } protected String[] argsWith(String password) throws IOException { return new String[] { "-u", url, "-d", driver, "-n", userName, "-p", password, "--isolation=TRANSACTION_READ_COMMITTED", "-f", sqlScriptFile }; } private void logScript() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Going to invoke file that contains:"); try (BufferedReader reader = new BufferedReader(new FileReader(sqlScriptFile))) { String line; while ((line = reader.readLine()) != null) { LOG.debug("script: " + line); } } } } } // Create the required command line options private static void logAndPrintToError(String errmsg) { LOG.error(errmsg); System.err.println(errmsg); } public static void main(String[] args) { MetastoreSchemaTool tool = new MetastoreSchemaTool(); System.exit(tool.run(args)); } public int run(String[] args) { return run(findHomeDir(), args, null, MetastoreConf.newMetastoreConf()); } public int run(String metastoreHome, String[] args, OptionGroup additionalOptions, Configuration conf) { try { init(metastoreHome, args, additionalOptions, conf); SchemaToolTask task; if (cmdLine.hasOption("info")) { task = new SchemaToolTaskInfo(); } else if (cmdLine.hasOption("upgradeSchema") || cmdLine.hasOption("upgradeSchemaFrom")) { task = new SchemaToolTaskUpgrade(); } else if (cmdLine.hasOption("initSchema") || cmdLine.hasOption("initSchemaTo")) { task = new SchemaToolTaskInit(); } else if (cmdLine.hasOption("initOrUpgradeSchema")) { task = new SchemaToolTaskInitOrUpgrade(); } else if (cmdLine.hasOption("validate")) { task = new SchemaToolTaskValidate(); } else if (cmdLine.hasOption("createCatalog")) { task = new SchemaToolTaskCreateCatalog(); } else if (cmdLine.hasOption("alterCatalog")) { task = new SchemaToolTaskAlterCatalog(); } else if (cmdLine.hasOption("mergeCatalog")) { task = new SchemaToolTaskMergeCatalog(); } else if (cmdLine.hasOption("moveDatabase")) { task = new SchemaToolTaskMoveDatabase(); } else if (cmdLine.hasOption("moveTable")) { task = new SchemaToolTaskMoveTable(); } else if (cmdLine.hasOption("createUser")) { task = new SchemaToolTaskCreateUser(); } else if (cmdLine.hasOption("dropAllDatabases")) { task = new SchemaToolTaskDrop(); } else if (cmdLine.hasOption("createLogsTable")) { task = new SchemaToolTaskCreateLogsTable(); } else { throw new HiveMetaException("No task defined!"); } task.setHiveSchemaTool(this); task.setCommandLineArguments(cmdLine); task.execute(); return 0; } catch (HiveMetaException e) { logAndPrintToError(e.getMessage()); if (e.getCause() != null) { Throwable t = e.getCause(); logAndPrintToError("Underlying cause: " + t.getClass().getName() + " : " + t.getMessage()); if (e.getCause() instanceof SQLException) { logAndPrintToError("SQL Error code: " + ((SQLException) t).getErrorCode()); } } if (cmdLine != null) { if (cmdLine.hasOption("verbose")) { e.printStackTrace(); } else { logAndPrintToError("Use --verbose for detailed stacktrace."); } } logAndPrintToError("*** schemaTool failed ***"); return 1; } } }
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.hughes.android.dictionary; import android.Manifest; import android.app.AlertDialog; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.support.v4.provider.DocumentFile; import android.support.v7.preference.PreferenceManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.text.InputType; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.hughes.android.dictionary.DictionaryInfo.IndexInfo; import com.hughes.android.util.IntentLauncher; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; // Right-click: // Delete, move to top. public class DictionaryManagerActivity extends AppCompatActivity { private static final String LOG = "QuickDic"; private static boolean blockAutoLaunch = false; private ListView listView; private ListView getListView() { if (listView == null) { listView = (ListView)findViewById(android.R.id.list); } return listView; } private void setListAdapter(ListAdapter adapter) { getListView().setAdapter(adapter); } private ListAdapter getListAdapter() { return getListView().getAdapter(); } // For DownloadManager bug workaround private final Set<Long> finishedDownloadIds = new HashSet<>(); private DictionaryApplication application; private SearchView filterSearchView; private ToggleButton showDownloadable; private LinearLayout dictionariesOnDeviceHeaderRow; private LinearLayout downloadableDictionariesHeaderRow; private Handler uiHandler; private final Runnable dictionaryUpdater = new Runnable() { @Override public void run() { if (uiHandler == null) { return; } uiHandler.post(new Runnable() { @Override public void run() { setMyListAdapter(); } }); } }; private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public synchronized void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) { startActivity(getLaunchIntent(getApplicationContext()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)); } if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { final long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications final DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); final Cursor cursor = downloadManager.query(query); if (cursor == null || !cursor.moveToFirst()) { Log.e(LOG, "Couldn't find download."); return; } final String dest = cursor .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); final int status = cursor .getInt(cursor .getColumnIndex(DownloadManager.COLUMN_STATUS)); if (DownloadManager.STATUS_SUCCESSFUL != status) { final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)); Log.w(LOG, "Download failed: status=" + status + ", reason=" + reason); String msg = Integer.toString(reason); switch (reason) { case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break; case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break; case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break; } new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show(); return; } Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId); if (!isFinishing()) Toast.makeText(context, getString(R.string.unzippingDictionary, dest), Toast.LENGTH_LONG).show(); if (unzipInstall(context, Uri.parse(dest), dest, true)) { finishedDownloadIds.add(downloadId); Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId); } } } }; private boolean unzipInstall(Context context, Uri zipUri, String dest, boolean delete) { File localZipFile = null; InputStream zipFileStream = null; ZipInputStream zipFile = null; FileOutputStream zipOut = null; boolean result = false; try { if (zipUri.getScheme().equals("content")) { zipFileStream = context.getContentResolver().openInputStream(zipUri); localZipFile = null; } else { localZipFile = new File(zipUri.getPath()); try { zipFileStream = new FileInputStream(localZipFile); } catch (Exception e) { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0); return false; } throw e; } } zipFile = new ZipInputStream(new BufferedInputStream(zipFileStream)); ZipEntry zipEntry; while ((zipEntry = zipFile.getNextEntry()) != null) { // Note: this check prevents security issues like accidental path // traversal, which unfortunately ZipInputStream has no protection against. // So take extra care when changing it. if (!Pattern.matches("[-A-Za-z]+\\.quickdic", zipEntry.getName())) { Log.w(LOG, "Invalid zip entry: " + zipEntry.getName()); continue; } Log.d(LOG, "Unzipping entry: " + zipEntry.getName()); DocumentFile targetFile = application.getDictDir().findFile(zipEntry.getName()); if (targetFile != null && targetFile.exists()) { targetFile.renameTo(zipEntry.getName().replace(".quickdic", ".bak.quickdic")); } targetFile = application.getDictDir().createFile("", zipEntry.getName()); zipOut = context.getContentResolver().openAssetFileDescriptor(targetFile.getUri(), "wt").createOutputStream(); copyStream(zipFile, zipOut); } application.backgroundUpdateDictionaries(dictionaryUpdater); if (!isFinishing()) Toast.makeText(context, getString(R.string.installationFinished, dest), Toast.LENGTH_LONG).show(); result = true; } catch (Exception e) { String msg = getString(R.string.unzippingFailed, dest + ": " + e.getMessage()); DocumentFile dir = application.getDictDir(); if (!dir.canWrite() || !DictionaryApplication.checkFileCreate(dir)) { msg = getString(R.string.notWritable, dir.getUri().getPath()); } new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show(); Log.e(LOG, "Failed to unzip.", e); } finally { try { if (zipOut != null) zipOut.close(); } catch (IOException ignored) {} try { if (zipFile != null) zipFile.close(); } catch (IOException ignored) {} try { if (zipFileStream != null) zipFileStream.close(); } catch (IOException ignored) {} if (delete) { if (localZipFile != null) localZipFile.delete(); else context.getContentResolver().delete(zipUri, null); } } return result; } public static Intent getLaunchIntent(Context c) { final Intent intent = new Intent(c, DictionaryManagerActivity.class); intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false); return intent; } private void readableCheckAndError(boolean requestPermission) { final DocumentFile dictDir = application.getDictDir(); if (dictDir.canRead()) return; blockAutoLaunch = true; if (requestPermission && ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0); return; } blockAutoLaunch = true; AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext()); builder.setTitle(getString(R.string.error)); builder.setMessage(getString( R.string.unableToReadDictionaryDir, dictDir.getUri().toString(), Environment.getExternalStorageDirectory())); builder.setNeutralButton("Close", null); builder.create().show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { readableCheckAndError(false); application.backgroundUpdateDictionaries(dictionaryUpdater); setMyListAdapter(); } @Override public void onCreate(Bundle savedInstanceState) { DictionaryApplication.INSTANCE.init(getApplicationContext()); application = DictionaryApplication.INSTANCE; // This must be first, otherwise the action bar doesn't get // styled properly. setTheme(application.getSelectedTheme().themeId); super.onCreate(savedInstanceState); Log.d(LOG, "onCreate:" + this); setTheme(application.getSelectedTheme().themeId); blockAutoLaunch = false; // UI init. setContentView(R.layout.dictionary_manager_activity); dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from( getListView().getContext()).inflate( R.layout.dictionary_manager_header_row_on_device, getListView(), false); downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from( getListView().getContext()).inflate( R.layout.dictionary_manager_header_row_downloadable, getListView(), false); showDownloadable = downloadableDictionariesHeaderRow .findViewById(R.id.hideDownloadable); showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { onShowDownloadableChanged(); } }); /* Disable version update notification, I don't maintain the text really and I don't think it is very useful. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion); if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals( thanksForUpdatingLatestVersion)) { blockAutoLaunch = true; startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext())); prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion) .commit(); } */ IntentFilter downloadManagerIntents = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); downloadManagerIntents.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED); registerReceiver(broadcastReceiver, downloadManagerIntents); setMyListAdapter(); registerForContextMenu(getListView()); getListView().setItemsCanFocus(true); readableCheckAndError(true); onCreateSetupActionBar(); final Intent intent = getIntent(); if (intent != null && intent.getAction() != null && intent.getAction().equals(Intent.ACTION_VIEW)) { blockAutoLaunch = true; Uri uri = intent.getData(); unzipInstall(this, uri, uri.getLastPathSegment(), false); } } private void onCreateSetupActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayHomeAsUpEnabled(false); filterSearchView = new SearchView(getSupportActionBar().getThemedContext()); filterSearchView.setIconifiedByDefault(false); // filterSearchView.setIconified(false); // puts the magnifying glass in // the // wrong place. filterSearchView.setQueryHint(getString(R.string.searchText)); filterSearchView.setSubmitButtonEnabled(false); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); filterSearchView.setLayoutParams(lp); filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT); filterSearchView.setImeOptions( EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI | // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API // 11 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS); filterSearchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { filterSearchView.clearFocus(); return false; } @Override public boolean onQueryTextChange(String filterText) { setMyListAdapter(); return true; } }); filterSearchView.setFocusable(true); actionBar.setCustomView(filterSearchView); actionBar.setDisplayShowCustomEnabled(true); // Avoid wasting space on large left inset Toolbar tb = (Toolbar)filterSearchView.getParent(); tb.setContentInsetsRelative(0, 0); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(broadcastReceiver); } private static void copyStream(final InputStream ins, final FileOutputStream outs) throws IOException { ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64); FileChannel out = outs.getChannel(); int bytesRead; int pos = 0; final byte[] bytes = new byte[1024 * 64]; do { bytesRead = ins.read(bytes, pos, bytes.length - pos); if (bytesRead != -1) pos += bytesRead; if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) { buf.put(bytes, 0, pos); pos = 0; buf.flip(); while (buf.hasRemaining()) out.write(buf); buf.clear(); } } while (bytesRead != -1); } @Override protected void onStart() { super.onStart(); uiHandler = new Handler(); } @Override protected void onStop() { super.onStop(); uiHandler = null; } @Override protected void onResume() { super.onResume(); if (PreferenceActivity.prefsMightHaveChanged) { PreferenceActivity.prefsMightHaveChanged = false; finish(); startActivity(getIntent()); } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true)); if (!blockAutoLaunch && getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) && prefs.contains(C.DICT_FILE) && prefs.contains(C.INDEX_SHORT_NAME)) { Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary."); startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(), prefs.getString(C.DICT_FILE, ""), prefs.getString(C.INDEX_SHORT_NAME, ""), "")); finish(); return; } // Remove the active dictionary from the prefs so we won't autolaunch // next time. prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit(); application.backgroundUpdateDictionaries(dictionaryUpdater); setMyListAdapter(); } @Override public boolean onCreateOptionsMenu(final Menu menu) { if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab"))) { return false; // testing the menu is not very interesting } final MenuItem sort = menu.add(getString(R.string.sortDicts)); MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER); sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(final MenuItem menuItem) { application.sortDictionaries(); setMyListAdapter(); return true; } }); final MenuItem browserDownload = menu.add(getString(R.string.browserDownload)); MenuItemCompat.setShowAsAction(browserDownload, MenuItem.SHOW_AS_ACTION_NEVER); browserDownload.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(final MenuItem menuItem) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri .parse("https://github.com/rdoeffinger/Dictionary/releases/v0.3-dictionaries")); startActivity(intent); return false; } }); DictionaryApplication.onCreateGlobalOptionsMenu(this, menu); return true; } @Override public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); Log.d(LOG, "onCreateContextMenu, " + menuInfo); final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo; final int position = adapterContextMenuInfo.position; final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position); if (row.dictionaryInfo == null) { return; } if (position > 0 && row.onDevice) { final android.view.MenuItem moveToTopMenuItem = menu.add(R.string.moveToTop); moveToTopMenuItem.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(android.view.MenuItem item) { application.moveDictionaryToTop(row.dictionaryInfo); setMyListAdapter(); return true; } }); } if (row.onDevice) { final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary); deleteMenuItem .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(android.view.MenuItem item) { application.deleteDictionary(row.dictionaryInfo); setMyListAdapter(); return true; } }); } } private void onShowDownloadableChanged() { setMyListAdapter(); Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit(); prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked()); prefs.commit(); } class MyListAdapter extends BaseAdapter { final List<DictionaryInfo> dictionariesOnDevice; final List<DictionaryInfo> downloadableDictionaries; class Row { final DictionaryInfo dictionaryInfo; final boolean onDevice; private Row(DictionaryInfo dictionaryInfo, boolean onDevice) { this.dictionaryInfo = dictionaryInfo; this.onDevice = onDevice; } } private MyListAdapter(final String[] filters) { dictionariesOnDevice = application.getDictionariesOnDevice(filters); if (showDownloadable.isChecked()) { downloadableDictionaries = application.getDownloadableDictionaries(filters); } else { downloadableDictionaries = Collections.emptyList(); } } @Override public int getCount() { return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size(); } @Override public Row getItem(int position) { if (position == 0) { return new Row(null, true); } position -= 1; if (position < dictionariesOnDevice.size()) { return new Row(dictionariesOnDevice.get(position), true); } position -= dictionariesOnDevice.size(); if (position == 0) { return new Row(null, false); } position -= 1; assert position < downloadableDictionaries.size(); return new Row(downloadableDictionaries.get(position), false); } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 3; } @Override public int getItemViewType(int position) { final Row row = getItem(position); if (row.dictionaryInfo == null) { return row.onDevice ? 0 : 1; } assert row.dictionaryInfo.indexInfos.size() <= 2; return 2; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == dictionariesOnDeviceHeaderRow || convertView == downloadableDictionariesHeaderRow) { return convertView; } final Row row = getItem(position); if (row.dictionaryInfo == null) { assert convertView == null; return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow; } return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice); } } private void setMyListAdapter() { final String filter = filterSearchView == null ? "" : filterSearchView.getQuery() .toString(); final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+"); setListAdapter(new MyListAdapter(filters)); } private boolean isDownloadActive(String downloadUrl, boolean cancel) { DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); final DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING); final Cursor cursor = downloadManagerQuery(downloadManager, query, cancel); if (cursor == null) { return cancel; } String destFile; try { destFile = new File(new URL(downloadUrl).getPath()).getName(); } catch (MalformedURLException e) { throw new RuntimeException("Invalid download URL!", e); } while (cursor.moveToNext()) { if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)))) break; if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)))) break; } boolean active = !cursor.isAfterLast(); if (active && cancel) { long downloadId = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)); finishedDownloadIds.add(downloadId); downloadManager.remove(downloadId); } cursor.close(); return active; } private Cursor downloadManagerQuery(DownloadManager downloadManager, DownloadManager.Query query, boolean cancel) { final Cursor cursor; try { cursor = downloadManager.query(query); } catch (SecurityException se) { Log.w(LOG, "Failed to query download manager", se); showDownloadFailedAlert(getString(R.string.downloadManagerQueryPermissionDenied)); return null; } // Due to a bug, cursor is null instead of empty when // the download manager is disabled. if (cursor == null && cancel) { showDownloadFailedAlert(getString(R.string.downloadManagerQueryFailed)); } return cursor; } private void showDownloadFailedAlert(String msg) { new AlertDialog.Builder(this).setTitle(getString(R.string.error)) .setMessage(getString(R.string.downloadFailed, msg)) .setNeutralButton("Close", null).show(); } private View createDictionaryRow(final DictionaryInfo dictionaryInfo, final ViewGroup parent, View row, boolean canLaunch) { if (row == null) { row = LayoutInflater.from(parent.getContext()).inflate( R.layout.dictionary_manager_row, parent, false); } final TextView name = row.findViewById(R.id.dictionaryName); final TextView details = row.findViewById(R.id.dictionaryDetails); name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename)); final boolean updateAvailable = application.updateAvailable(dictionaryInfo); final Button downloadButton = row.findViewById(R.id.downloadButton); final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename); boolean broken = false; if (!dictionaryInfo.isValid()) { broken = true; canLaunch = false; } if (downloadable != null && (!canLaunch || updateAvailable)) { downloadButton .setText(getString( R.string.downloadButton, downloadable.zipBytes / 1024.0 / 1024.0)); downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2); downloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton); } }); downloadButton.setVisibility(View.VISIBLE); if (isDownloadActive(downloadable.downloadUrl, false)) downloadButton.setText("X"); } else { downloadButton.setVisibility(View.GONE); } LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons); final List<IndexInfo> sortedIndexInfos = application .sortedIndexInfos(dictionaryInfo.indexInfos); final StringBuilder builder = new StringBuilder(); if (updateAvailable) { builder.append(getString(R.string.updateAvailable)); } assert buttons.getChildCount() == 4; for (int i = 0; i < 2; i++) { final Button textButton = (Button)buttons.getChildAt(2*i); final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1); if (i >= sortedIndexInfos.size()) { textButton.setVisibility(View.GONE); imageButton.setVisibility(View.GONE); continue; } final IndexInfo indexInfo = sortedIndexInfos.get(i); final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton, indexInfo); if (canLaunch) { button.setOnClickListener( new IntentLauncher(buttons.getContext(), DictionaryActivity.getLaunchIntent(getApplicationContext(), application.getPath(dictionaryInfo.uncompressedFilename).getUri().toString(), indexInfo.shortName, ""))); } button.setEnabled(canLaunch); button.setFocusable(canLaunch); if (builder.length() != 0) { builder.append("; "); } builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount)); } builder.append("; "); builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0)); if (broken) { name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename)); builder.append("; Cannot be used, redownload, check hardware/file system"); } details.setText(builder.toString()); if (canLaunch) { row.setOnClickListener(new IntentLauncher(parent.getContext(), DictionaryActivity.getLaunchIntent(getApplicationContext(), application.getPath(dictionaryInfo.uncompressedFilename).getUri().toString(), dictionaryInfo.indexInfos.get(0).shortName, ""))); // do not setFocusable, for keyboard navigation // offering only the index buttons is better. } row.setClickable(canLaunch); // Allow deleting, even if we cannot open row.setLongClickable(broken || canLaunch); row.setBackgroundResource(android.R.drawable.menuitem_background); return row; } private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) { if (isDownloadActive(downloadUrl, true)) { downloadButton .setText(getString( R.string.downloadButton, bytes / 1024.0 / 1024.0)); return; } // API 19 and earlier have issues with github URLs, both http and https. // Really old (~API 10) DownloadManager cannot handle https at all. // Work around both with in one. String altUrl = downloadUrl.replace("https://github.com/rdoeffinger/Dictionary/releases/download/v0.2-dictionaries/", "http://ffmpeg.org/~reimar/dict/"); altUrl = altUrl.replace("https://github.com/rdoeffinger/Dictionary/releases/download/v0.3-dictionaries/", "http://ffmpeg.org/~reimar/dict/"); Request request = new Request(Uri.parse(Build.VERSION.SDK_INT < 21 ? altUrl : downloadUrl)); String destFile; try { destFile = new File(new URL(downloadUrl).getPath()).getName(); } catch (MalformedURLException e) { throw new RuntimeException("Invalid download URL!", e); } Log.d(LOG, "Downloading to: " + destFile); request.setTitle(destFile); DocumentFile destFilePath = application.getDictDir().findFile(destFile); if (destFilePath != null) destFilePath.delete(); destFilePath = application.getDictDir().createFile("", destFile); try { request.setDestinationUri(destFilePath.getUri()); } catch (Exception e) { if (destFilePath != null) destFilePath.delete(); } DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); if (downloadManager == null) { String msg = getString(R.string.downloadManagerQueryFailed); new AlertDialog.Builder(this).setTitle(getString(R.string.error)) .setMessage(getString(R.string.downloadFailed, msg)) .setNeutralButton("Close", null).show(); return; } try { downloadManager.enqueue(request); } catch (Exception e) { if (destFilePath != null) destFilePath.delete(); request = new Request(Uri.parse(downloadUrl)); request.setTitle(destFile); downloadManager.enqueue(request); } Log.w(LOG, "Download started: " + destFile); downloadButton.setText("X"); } }
/* * The MIT License * * Copyright (c) 2011-2014, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cloudbees.plugins.deployer.sources; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.FilePath; import hudson.model.AbstractProject; import hudson.model.Run; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import org.apache.commons.lang.StringUtils; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.FileSet; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.util.logging.Logger; /** * Finds the first file that matches an fixed selection. * */ @SuppressWarnings("unused") // used by stapler public class StaticSelectionDeploySource extends DeploySource { private static final Logger LOGGER = Logger.getLogger(StaticSelectionDeploySource.class.getName()); /** * The fixed file path. */ @NonNull private final String filePath; /** * Constructor used by stapler. * * @param filePath the file path. */ @DataBoundConstructor public StaticSelectionDeploySource(@CheckForNull String filePath) { this.filePath = StringUtils.trimToEmpty(filePath); } /** * Returns the file path. * * @return the file path. */ @NonNull public String getFilePath() { return filePath; } /** * {@inheritDoc} */ @Override @CheckForNull public File getApplicationFile(@NonNull Run run) { if (run.getArtifactsDir().isDirectory()) { File file = new File(run.getArtifactsDir(), filePath); return file.exists() ? file : null; } else { return null; } } /** * {@inheritDoc} */ @Override @NonNull public FilePath getApplicationFile(@NonNull FilePath workspace) { return workspace.child(filePath); } /** * {@inheritDoc} */ @Override @NonNull public String toString() { return filePath; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StaticSelectionDeploySource that = (StaticSelectionDeploySource) o; if (!filePath.equals(that.filePath)) { return false; } return true; } /** * {@inheritDoc} */ @Override public int hashCode() { return filePath.hashCode(); } /** * Descriptor for {@link StaticSelectionDeploySource}. */ @Extension public static class DescriptorImpl extends DeploySourceDescriptor { /** * {@inheritDoc} */ @Override public String getDisplayName() { return Messages.StaticSelectionDeploySource_DisplayName(); } /** * {@inheritDoc} */ @Override public boolean isSupported(@CheckForNull DeploySourceOrigin source) { return DeploySourceOrigin.RUN.equals(source); } /** * {@inheritDoc} */ @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return !isMavenJob(jobType); } @SuppressWarnings("unused") // used by stapler public FormValidation doCheckFilePath(@QueryParameter final String value) throws IOException, ServletException, InterruptedException { Run run = findRun(); if (run != null) { if (!run.getHasArtifacts()) { return FormValidation.warning( "No artifacts were archived in the last successful run, unable to validate '" + value + "'"); } if (new File(run.getArtifactsDir(), value).isFile()) { return FormValidation.ok(); } } return FormValidation.warning("Could not find a match for '" + value + "'"); } @SuppressWarnings("unused") // used by stapler public ListBoxModel doFillFilePathItems() throws IOException, InterruptedException { Run run = findRun(); ListBoxModel m = new ListBoxModel(); if (run != null) { FileSet fileSet = new FileSet(); fileSet.setProject(new Project()); fileSet.setDir(run.getArtifactsDir()); fileSet.setIncludes("**/*.war"); for (String path : fileSet.getDirectoryScanner().getIncludedFiles()) { m.add(path); } } return m; } @Override public DeploySource newInstance() { return new StaticSelectionDeploySource(null); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.vault.fs.io; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import org.apache.jackrabbit.vault.fs.api.Artifact; import org.apache.jackrabbit.vault.fs.api.VaultFile; import org.apache.jackrabbit.vault.util.JcrConstants; import org.apache.jackrabbit.vault.util.PathUtil; import org.apache.jackrabbit.vault.util.PlatformNameFormat; import org.apache.jackrabbit.vault.util.Text; /** * Implements a Vault filesystem exporter that exports Vault files to a JCR * repository. * It uses the {@link PlatformNameFormat} for formatting the jcr file * names to local ones. */ public class JcrExporter extends AbstractExporter { private final Node localParent; private boolean autoDeleteFiles; /** * Constructs a new jcr exporter. * @param localFile the local parent folder */ public JcrExporter(Node localFile) { this.localParent = localFile; } public boolean isAutoDeleteFiles() { return autoDeleteFiles; } public void setAutoDeleteFiles(boolean autoDeleteFiles) { this.autoDeleteFiles = autoDeleteFiles; } /** * {@inheritDoc} */ public void open() throws IOException, RepositoryException { scan(localParent); } /** * {@inheritDoc} */ public void close() throws IOException, RepositoryException { if (autoDeleteFiles) { for (ExportInfo.Entry e: exportInfo.getEntries().values()) { if (e.type == ExportInfo.Type.DELETE) { String relPath = PathUtil.getRelativePath(localParent.getPath(), e.path); try { Node node = localParent.getNode(relPath); node.remove(); track("D", relPath); } catch (RepositoryException e1) { track(e1, relPath); } } } } localParent.getSession().save(); } private void scan(Node dir) throws RepositoryException { NodeIterator iter = dir.getNodes(); while (iter.hasNext()) { Node child = iter.nextNode(); String name = child.getName(); if (".svn".equals(name) || ".vlt".equals(name)) { continue; } if (child.isNodeType(JcrConstants.NT_FOLDER)) { exportInfo.update(ExportInfo.Type.RMDIR, child.getPath()); scan(child); } else if (child.isNodeType(JcrConstants.NT_FILE)) { exportInfo.update(ExportInfo.Type.DELETE, child.getPath()); } } } public void createDirectory(VaultFile file, String relPath) throws RepositoryException, IOException { getOrCreateItem(getPlatformFilePath(file, relPath), true); } public void createDirectory(String relPath) throws IOException { getOrCreateItem(relPath, true); } public void writeFile(VaultFile file, String relPath) throws RepositoryException, IOException { Node local = getOrCreateItem(getPlatformFilePath(file, relPath), false); track(local.isNew() ? "A" : "U", relPath); Node content; if (local.hasNode(JcrConstants.JCR_CONTENT)) { content = local.getNode(JcrConstants.JCR_CONTENT); } else { content = local.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE); } Artifact a = file.getArtifact(); switch (a.getPreferredAccess()) { case NONE: throw new RepositoryException("Artifact has no content."); case SPOOL: // we can't support spool case STREAM: try (InputStream in = a.getInputStream()) { Binary b = content.getSession().getValueFactory().createBinary(in); content.setProperty(JcrConstants.JCR_DATA, b); b.dispose(); } break; } Calendar now = Calendar.getInstance(); if (a.getLastModified() >= 0) { now.setTimeInMillis(a.getLastModified()); } content.setProperty(JcrConstants.JCR_LASTMODIFIED, now); if (a.getContentType() != null) { content.setProperty(JcrConstants.JCR_MIMETYPE, a.getContentType()); } else if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)){ content.setProperty(JcrConstants.JCR_MIMETYPE, "application/octet-stream"); } } public void writeFile(InputStream in, String relPath) throws IOException { try { Node content; Node local = getOrCreateItem(relPath, false); if (local.hasNode(JcrConstants.JCR_CONTENT)) { content = local.getNode(JcrConstants.JCR_CONTENT); } else { content = local.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE); } Binary b = content.getSession().getValueFactory().createBinary(in); content.setProperty(JcrConstants.JCR_DATA, b); content.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance()); if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)){ content.setProperty(JcrConstants.JCR_MIMETYPE, "application/octet-stream"); } b.dispose(); in.close(); } catch (RepositoryException e) { IOException io = new IOException("Error while writing file " + relPath); io.initCause(e); throw io; } } private Node getOrCreateItem(String relPath, boolean isDir) throws IOException { try { String[] segments = Text.explode(relPath, '/'); Node root = localParent; for (int i=0; i<segments.length; i++) { String s = segments[i]; if (root.hasNode(s)) { root = root.getNode(s); if (isDir) { exportInfo.update(ExportInfo.Type.NOP, root.getPath()); } else { exportInfo.update(ExportInfo.Type.UPDATE, root.getPath()); } } else { if (i == segments.length -1 && !isDir) { root = root.addNode(s, JcrConstants.NT_FILE); exportInfo.update(ExportInfo.Type.ADD, root.getPath()); } else { root = root.addNode(s, JcrConstants.NT_FOLDER); exportInfo.update(ExportInfo.Type.MKDIR, root.getPath()); } } } return root; } catch (RepositoryException e) { IOException io = new IOException("Error while creating item " + relPath); io.initCause(e); throw io; } } }