answer
stringlengths
17
10.2M
package com.f2prateek.segment; import android.Manifest; import android.app.Application; import com.squareup.moshi.Moshi; import com.squareup.moshi.Rfc3339DateJsonAdapter; import java.util.Arrays; import java.util.Date; import java.util.List; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; import static com.google.common.truth.Truth.assertThat; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 23) public class SegmentTest { @Rule public final MockWebServer server = new MockWebServer(); private Segment segment; private static void grantPermission(final Application app, final String permission) { ShadowApplication shadowApp = Shadows.shadowOf(app); shadowApp.grantPermissions(permission); } @Before public void setUp() { grantPermission(RuntimeEnvironment.application, Manifest.permission.INTERNET); segment = new Segment.Builder() .writeKey("writeKey") .context(RuntimeEnvironment.application) .baseUrl(server.url("/")) .build(); } @Test public void e2e() throws Exception { List<Message> messages = Arrays.asList(segment.newAlias("newId").build(), segment.newGroup("groupId").build(), segment.newIdentify("userId").build(), segment.newScreen("name").build(), segment.newTrack("event").build()); for (Message m : messages) { server.enqueue(new MockResponse()); segment.enqueue(m).get(); segment.flush().get(); RecordedRequest request = server.takeRequest(); assertThat(request.getRequestLine()).isEqualTo("POST /v1/batch HTTP/1.1"); //noinspection SpellCheckingInspection assertThat(request.getHeader("Authorization")).isEqualTo("Basic d3JpdGVLZXk6"); // TODO: Use proper fixtures. Currently IDs and timestamps are not consistent between runs. final Moshi moshi = new Moshi.Builder() .add(SegmentMoshiAdapterFactory.create()) .add(Date.class, new Rfc3339DateJsonAdapter()) .build(); Batch batch = moshi.adapter(Batch.class).fromJson(request.getBody()); assertThat(batch.batch()).hasSize(1); assertThat(batch.batch().get(0)).isEqualTo(m); } } }
package com.battleejb.entities; import java.io.Serializable; import javax.persistence.*; import java.util.List; /** * The persistent class for the User database table. * */ @Entity @NamedQueries({ @NamedQuery(name="User.findByLogin", query="SELECT u FROM User u WHERE u.login = :login") }) public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private byte active; private byte commentAble; private byte approveregistration; private String email; private String login; private String name; private String password; private String photoPath; private String surname; @OneToMany(mappedBy="user") private List<Comment> comments; @OneToMany(mappedBy="user") private List<Competition> competitions; @OneToMany(mappedBy="user") private List<Project> projects; @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST) private Address address; @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST) private Role role; @OneToMany(mappedBy="user") private List<Voice> voices; public User() { } public User(String email, String login, String name, String password, String photoPath, String surname, Address address, Role role) { super(); this.email = email; this.login = login; this.name = name; this.password = password; this.photoPath = photoPath; this.surname = surname; this.address = address; this.role = role; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public byte getActive() { return this.active; } public void setActive(byte active) { this.active = active; } public byte getCommentAble() { return this.commentAble; } public void setCommentAble(byte commentAble) { this.commentAble = commentAble; } public byte getApproveregistration() { return this.approveregistration; } public void setApproveregistration(byte approveregistration) { this.approveregistration = approveregistration; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getPhotoPath() { return this.photoPath; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } public String getSurname() { return this.surname; } public void setSurname(String surname) { this.surname = surname; } public List<Comment> getComments() { return this.comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public List<Competition> getCompetitions() { return this.competitions; } public void setCompetitions(List<Competition> competitions) { this.competitions = competitions; } public List<Project> getProjects() { return this.projects; } public void setProjects(List<Project> projects) { this.projects = projects; } public Address getAddress() { return this.address; } public void setAddress(Address address) { this.address = address; } public Role getRole() { return this.role; } public void setRole(Role role) { this.role = role; } public List<Voice> getVoices() { return this.voices; } public void setVoices(List<Voice> voices) { this.voices = voices; } }
package edu.mit.streamjit.impl.compiler2; import com.google.common.collect.FluentIterable; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.common.math.LongMath; import com.google.common.primitives.Ints; import com.google.common.primitives.Primitives; import edu.mit.streamjit.api.RoundrobinSplitter; import edu.mit.streamjit.api.StreamCompilationFailedException; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.Blob.Token; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.common.Configuration.SwitchParameter; import edu.mit.streamjit.impl.compiler.Schedule; import edu.mit.streamjit.util.CollectionUtils; import static edu.mit.streamjit.util.Combinators.*; import edu.mit.streamjit.util.bytecode.Module; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; /** * * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 9/22/2013 */ public class Compiler2 { private final ImmutableSet<ActorArchetype> archetypes; private final NavigableSet<Actor> actors; private ImmutableSortedSet<ActorGroup> groups; private final Configuration config; private final int maxNumCores; private final DrainData initialState; private final Set<Storage> storage; private ImmutableMap<ActorGroup, Integer> externalSchedule; private final Module module = new Module(); private ImmutableMap<ActorGroup, Integer> initSchedule; /** * ConcreteStorage instances used during initialization (bound into the * initialization code). */ private ImmutableMap<Storage, ConcreteStorage> initStorage; /** * ConcreteStorage instances used during the steady-state (bound into the * steady-state code). */ private ImmutableMap<Storage, ConcreteStorage> steadyStateStorage; /** * Code to run the initialization schedule. (Initialization is * single-threaded.) */ private MethodHandle initCode; /** * The number of elements to read or write from Buffers during the init * schedule. */ private ImmutableMap<Token, Integer> tokenInitSchedule; /** * Code to run the steady state schedule. The blob host takes care of * filling/flushing buffers, adjusting storage and the global barrier. */ private ImmutableList<MethodHandle> steadyStateCode; /** * The number of elements to read or write from Buffers during one run of * the steady-state schedule. */ private ImmutableMap<Token, Integer> tokenSteadyStateSchedule; /** * Runnables that move live items from initialization storage to * steady-state storage. */ private ImmutableList<Runnable> migrationInstructions; public Compiler2(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores, DrainData initialState) { Map<Class<?>, ActorArchetype> archetypesBuilder = new HashMap<>(); Map<Worker<?, ?>, WorkerActor> workerActors = new HashMap<>(); for (Worker<?, ?> w : workers) { @SuppressWarnings("unchecked") Class<? extends Worker<?, ?>> wClass = (Class<? extends Worker<?, ?>>)w.getClass(); if (archetypesBuilder.get(wClass) == null) archetypesBuilder.put(wClass, new ActorArchetype(wClass, module)); WorkerActor actor = new WorkerActor(w, archetypesBuilder.get(wClass)); workerActors.put(w, actor); } this.archetypes = ImmutableSet.copyOf(archetypesBuilder.values()); Map<Token, TokenActor> tokenActors = new HashMap<>(); Table<Actor, Actor, Storage> storageTable = HashBasedTable.create(); int[] inputTokenId = new int[]{Integer.MIN_VALUE}, outputTokenId = new int[]{Integer.MAX_VALUE}; for (WorkerActor a : workerActors.values()) a.connect(ImmutableMap.copyOf(workerActors), tokenActors, storageTable, inputTokenId, outputTokenId); this.actors = new TreeSet<>(); this.actors.addAll(workerActors.values()); this.actors.addAll(tokenActors.values()); this.storage = new HashSet<>(storageTable.values()); this.config = config; this.maxNumCores = maxNumCores; this.initialState = initialState; } public Blob compile() { fuse(); schedule(); // identityRemoval(); // splitterRemoval(); //joinerRemoval(); // unbox(); initSchedule(); createStorage(); createCode(); return null; } /** * Fuses actors into groups as directed by the configuration. */ private void fuse() { List<ActorGroup> actorGroups = new ArrayList<>(); for (Actor a : actors) actorGroups.add(ActorGroup.of(a)); //Fuse as much as possible. just_fused: do { try_fuse: for (Iterator<ActorGroup> it = actorGroups.iterator(); it.hasNext();) { ActorGroup g = it.next(); if (g.isTokenGroup()) continue try_fuse; for (ActorGroup pg : g.predecessorGroups()) if (pg.isTokenGroup()) continue try_fuse; if (g.isPeeking() || g.predecessorGroups().size() > 1) continue try_fuse; //TODO: initial data prevents fusion String paramName = String.format("fuse%d", g.id()); SwitchParameter<Boolean> fuseParam = config.getParameter(paramName, SwitchParameter.class, Boolean.class); if (!fuseParam.getValue()) continue try_fuse; ActorGroup gpred = Iterables.getOnlyElement(g.predecessorGroups()); ActorGroup fusedGroup = ActorGroup.fuse(g, gpred); it.remove(); actorGroups.remove(gpred); actorGroups.add(fusedGroup); continue just_fused; } break; } while (true); this.groups = ImmutableSortedSet.copyOf(actorGroups); } /** * Computes each group's internal schedule and the external schedule. */ private void schedule() { for (ActorGroup g : groups) internalSchedule(g); Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(groups); for (ActorGroup g : groups) { for (Storage e : g.outputs()) { Actor upstream = Iterables.getOnlyElement(e.upstream()); Actor downstream = Iterables.getOnlyElement(e.downstream()); ActorGroup other = downstream.group(); int upstreamAdjust = g.schedule().get(upstream); int downstreamAdjust = other.schedule().get(downstream); scheduleBuilder.connect(g, other) .push(e.push() * upstreamAdjust) .pop(e.pop() * downstreamAdjust) .peek(e.peek() * downstreamAdjust) .bufferExactly(0); } } try { externalSchedule = scheduleBuilder.build().getSchedule(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find external schedule", ex); } } /** * Computes the internal schedule for the given group. */ private void internalSchedule(ActorGroup g) { Schedule.Builder<Actor> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(g.actors()); for (Storage s : g.internalEdges()) { scheduleBuilder.connect(Iterables.getOnlyElement(s.upstream()), Iterables.getOnlyElement(s.downstream())) .push(s.push()) .pop(s.pop()) .peek(s.peek()) .bufferExactly(0); } try { Schedule<Actor> schedule = scheduleBuilder.build(); g.setSchedule(schedule.getSchedule()); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find internal schedule for group "+g.id(), ex); } } // private void splitterRemoval() { // for (Actor splitter : ImmutableSortedSet.copyOf(actors)) { // List<MethodHandle> transfers = splitterTransferFunctions(splitter); // if (transfers == null) continue; // Storage survivor = Iterables.getOnlyElement(splitter.inputs()); // MethodHandle Sin = Iterables.getOnlyElement(splitter.inputIndexFunctions()); // for (int i = 0; i < splitter.outputs().size(); ++i) { // Storage victim = splitter.outputs().get(i); // MethodHandle t = transfers.get(i); // MethodHandle t2 = MethodHandles.filterReturnValue(t, Sin); // for (Object o : victim.downstream()) // if (o instanceof Actor) { // Actor q = (Actor)o; // List<Storage> inputs = q.inputs(); // List<MethodHandle> inputIndices = q.inputIndexFunctions(); // for (int j = 0; j < inputs.size(); ++j) // if (inputs.get(j).equals(victim)) { // inputs.set(j, survivor); // inputIndices.set(j, MethodHandles.filterReturnValue(t2, inputIndices.get(j))); // } else if (o instanceof Token) { // Token q = (Token)o; // tokenInputIndices.put(q, MethodHandles.filterReturnValue(t2, tokenInputIndices.get(q))); // } else // throw new AssertionError(o); // removeActor(splitter); // /** // * Returns transfer functions for the given splitter, or null if the actor // * isn't a splitter or isn't one of the built-in splitters or for some other // * reason we can't make transfer functions. // * // * A splitter has one transfer function for each output that maps logical // * output indices to logical input indices (representing the splitter's // * distribution pattern). // * @param a an actor // * @return transfer functions, or null // */ // private List<MethodHandle> splitterTransferFunctions(Actor a) { // if (a.worker() instanceof RoundrobinSplitter) { // //Nx, Nx + 1, Nx + 2, ..., Nx+(N-1) // int N = a.outputs().size(); // ImmutableList.Builder<MethodHandle> transfer = ImmutableList.builder(); // for (int n = 0; n < N; ++n) // transfer.add(add(mul(MethodHandles.identity(int.class), N), n)); // return transfer.build(); // } else //TODO: WeightedRoundrobinSplitter, DuplicateSplitter // return null; /** * Removes an Actor from this compiler's data structures. The Actor should * already have been unlinked from the graph (no incoming edges); this takes * care of removing it from the actors set, its actor group (possibly * removing the group if it's now empty), and the schedule. * @param a the actor to remove */ private void removeActor(Actor a) { assert actors.contains(a) : a; actors.remove(a); ActorGroup g = a.group(); g.remove(a); if (g.actors().isEmpty()) { groups = ImmutableSortedSet.copyOf(Sets.difference(groups, ImmutableSet.of(g))); externalSchedule = ImmutableMap.copyOf(Maps.difference(externalSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft()); } } // /** // * Removes Identity instances from the graph, unless doing so would make the // * graph empty. // */ // private void identityRemoval() { // //TODO: remove from group, possibly removing the group if it becomes empty // for (Iterator<Actor> iter = actors.iterator(); iter.hasNext();) { // if (actors.size() == 1) // break; // Actor actor = iter.next(); // if (!actor.archetype().workerClass().equals(Identity.class)) // continue; // iter.remove(); // assert actor.predecessors().size() == 1 && actor.successors().size() == 1; // Object upstream = actor.predecessors().get(0), downstream = actor.successors().get(0); // if (upstream instanceof Actor) // replace(((Actor)upstream).successors(), actor, downstream); // if (downstream instanceof Actor) // replace(((Actor)downstream).predecessors(), actor, upstream); // //No index function changes required for Identity actors. // private static int replace(List<Object> list, Object target, Object replacement) { // int replacements = 0; // for (int i = 0; i < list.size(); ++i) // if (Objects.equals(list.get(0), target)) { // list.set(i, replacement); // ++replacements; // return replacements; // /** // * Symbolically unboxes a Storage if its common type is a wrapper type and // * all the connected Actors support unboxing. // */ // private void unbox() { // next_storage: for (Storage s : storage) { // Class<?> commonType = s.commonType(); // if (!Primitives.isWrapperType(commonType)) continue; // for (Object o : s.upstream()) // if (o instanceof Actor && !((Actor)o).archetype().canUnboxOutput()) // continue next_storage; // for (Object o : s.downstream()) // if (o instanceof Actor && !((Actor)o).archetype().canUnboxInput()) // continue next_storage; // s.setType(Primitives.unwrap(s.commonType())); /** * Computes the initialization schedule, which is in terms of ActorGroup * executions. */ private void initSchedule() { Map<Storage, Set<Integer>> requiredReadIndices = new HashMap<>(); for (Storage s : storage) { s.computeRequirements(externalSchedule); requiredReadIndices.put(s, new HashSet<>(s.readIndices())); } //TODO: initial state will reduce the required read indices. //TODO: what if we have more state than required for reads (due to rate //lag)? Will need to leave space for it. /** * Actual init: iterations of each group necessary to fill the required * read indices of the output Storage. */ Map<ActorGroup, Integer> actualInit = new HashMap<>(); for (ActorGroup g : groups) //TODO: this is assuming we can stop as soon as an iteration doesn't //help. Will this always be true? for (int i = 0; ; ++i) { boolean changed = false; for (Map.Entry<Storage, Set<Integer>> e : g.writes(i).entrySet()) changed |= requiredReadIndices.get(e.getKey()).removeAll(e.getValue()); if (!changed) { actualInit.put(g, i); break; } } /** * Total init, which is actual init plus allowances for downstream's * total init. Computed bottom-up via reverse iteration on groups. */ Map<ActorGroup, Integer> totalInit = new HashMap<>(); for (ActorGroup g : groups.descendingSet()) { if (g.successorGroups().isEmpty()) totalInit.put(g, actualInit.get(g)); long us = externalSchedule.get(g); List<Long> downstreamReqs = new ArrayList<>(g.successorGroups().size() + 1); downstreamReqs.add(0L); //Always at least 0. for (ActorGroup s : g.successorGroups()) { //I think reverse iteration guarantees bottom-up? assert totalInit.containsKey(s) : g.id() + " requires " + s.id(); //them * (us / them) = us; we round up. int st = totalInit.get(s); int them = externalSchedule.get(s); downstreamReqs.add(LongMath.divide(LongMath.checkedMultiply(st, us), them, RoundingMode.CEILING)); } totalInit.put(g, Ints.checkedCast(Collections.max(downstreamReqs) + actualInit.get(g))); } this.initSchedule = ImmutableMap.copyOf(totalInit); /** * Compute the memory requirement for the init schedule. This is the * required read span (difference between the min and max read index), * plus throughput for each steady-state unit (or fraction thereof) * beyond the first, maximized across all writers. */ for (Storage s : storage) { List<Long> size = new ArrayList<>(s.upstream().size()); for (ActorGroup writer : s.upstreamGroups()) size.add(LongMath.checkedMultiply(LongMath.divide(totalInit.get(writer), externalSchedule.get(writer), RoundingMode.CEILING) - 1, s.throughput())); int initCapacity = Ints.checkedCast(Collections.max(size) + s.readIndices().last() - s.readIndices().first()); s.setInitCapacity(initCapacity); } /** * Compute post-initialization liveness (data items written during init * that will be read in a future steady-state iteration). These are the * items that must be moved into steady-state storage. We compute by * building the written physical indices during the init schedule, then * building the read physical indices for future steady-state executions * and taking the intersection. * * TODO: This makes the same assumption as above, that we can stop * translating indices as soon as adding an execution doesn't change the * indices, which may not be true. */ Map<Storage, Set<Integer>> initWrites = new HashMap<>(); Map<Storage, Set<Integer>> futureReads = new HashMap<>(); for (Storage s : storage) { initWrites.put(s, new HashSet<Integer>()); futureReads.put(s, new HashSet<Integer>()); } for (ActorGroup g : groups) for (int i = 0; i < initSchedule.get(g); ++i) for (Map.Entry<Storage, Set<Integer>> writes : g.writes(i).entrySet()) initWrites.get(writes.getKey()).addAll(writes.getValue()); for (ActorGroup g : groups) { //We run until our read indices don't intersect any of the write //indices, at which point we aren't keeping any more elements live. boolean progress = true; for (int i = initSchedule.get(g); progress; ++i) { progress = false; for (Map.Entry<Storage, Set<Integer>> reads : g.reads(i).entrySet()) { Storage s = reads.getKey(); Set<Integer> readIndices = reads.getValue(); Set<Integer> writeIndices = initWrites.get(s); if (!Sets.intersection(readIndices, writeIndices).isEmpty()) { writeIndices.addAll(readIndices); progress = true; } } } } for (Storage s : storage) s.setIndicesLiveAfterInit(ImmutableSortedSet.copyOf(Sets.intersection(initWrites.get(s), futureReads.get(s)))); //Assert we covered the required read indices. for (Storage s : storage) { for (int i : s.readIndices()) assert s.indicesLiveDuringSteadyState().contains(i); } //TODO: Compute the steady-state capacities. //(max(writers, rounded up) - min(readers, rounded down) + 1) * throughput } /** * Creates initialization and steady-state ConcreteStorage. */ private void createStorage() { //Initialization storage is unsynchronized. ImmutableMap.Builder<Storage, ConcreteStorage> initStorageBuilder = ImmutableMap.builder(); for (Storage s : storage) if (!s.isInternal()) initStorageBuilder.put(s, MapConcreteStorage.factory().make(s)); this.initStorage = initStorageBuilder.build(); //TODO: pack in initial state here //TODO: pre-allocate entries in the map by storing null/0? (to avoid //OOME during init code execution) -- maybe this should be a param to //MapConcreteStorage.factory(), or just always done //Steady-state storage is synchronized. //TODO: parameterize the factory used. ImmutableMap.Builder<Storage, ConcreteStorage> ssStorageBuilder = ImmutableMap.builder(); for (Storage s : storage) if (!s.isInternal()) ssStorageBuilder.put(s, MapConcreteStorage.factory().make(s)); this.steadyStateStorage = ssStorageBuilder.build(); /** * Create migration instructions: Runnables that move live items from * initialization to steady-state storage. */ ImmutableList.Builder<Runnable> migrationInstructionsBuilder = ImmutableList.builder(); for (Storage s : initStorage.keySet()) migrationInstructionsBuilder.add(new MigrationInstruction( s, initStorage.get(s), steadyStateStorage.get(s))); this.migrationInstructions = migrationInstructionsBuilder.build(); } private static final class MigrationInstruction implements Runnable { private final ConcreteStorage init, steady; private final ImmutableSortedSet<Integer> indicesToMigrate; private final int offset; private MigrationInstruction(Storage storage, ConcreteStorage init, ConcreteStorage steady) { this.init = init; this.steady = steady; this.indicesToMigrate = storage.indicesLiveAfterInit(); this.offset = storage.indicesLiveAfterInit().first() - storage.indicesLiveDuringSteadyState().first(); } @Override public void run() { init.sync(); for (int i : indicesToMigrate) steady.write(i - offset, init.read(i)); steady.sync(); } } private void createCode() { /** * During init, all (nontoken) groups are assigned to the same Core in * topological order (via the ordering on ActorGroups). At the same * time we build the token init schedule information required by the * blob host. */ Core initCore = new Core(storage, initStorage, MapConcreteStorage.factory()); ImmutableMap.Builder<Token, Integer> tokenInitScheduleBuilder = ImmutableMap.builder(); for (ActorGroup g : groups) if (!g.isTokenGroup()) initCore.allocate(g, Range.closedOpen(0, initSchedule.get(g))); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; tokenInitScheduleBuilder.put(ta.token(), initSchedule.get(g)); } this.initCode = initCore.code(); this.tokenInitSchedule = tokenInitScheduleBuilder.build(); List<Core> ssCores = new ArrayList<>(maxNumCores); for (int i = 0; i < maxNumCores; ++i) ssCores.add(new Core(storage, steadyStateStorage, MapConcreteStorage.factory())); ImmutableMap.Builder<Token, Integer> tokenSteadyStateScheduleBuilder = ImmutableMap.builder(); for (ActorGroup g : groups) if (!g.isTokenGroup()) //TODO: use Configuration here ssCores.get(0).allocate(g, Range.closedOpen(0, externalSchedule.get(g))); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; tokenSteadyStateScheduleBuilder.put(ta.token(), externalSchedule.get(g)); } ImmutableList.Builder<MethodHandle> steadyStateCodeBuilder = ImmutableList.builder(); for (Core c : ssCores) steadyStateCodeBuilder.add(c.code()); this.steadyStateCode = steadyStateCodeBuilder.build(); this.tokenSteadyStateSchedule = tokenSteadyStateScheduleBuilder.build(); } }
/** * StatisticsScreen * * Class representing the screen that allows users to view statistics. * * @author Willy McHie * Wheaton College, CSCI 335, Spring 2013 */ package edu.wheaton.simulator.gui; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.HashMap; import java.util.Map; import javax.swing.*; import edu.wheaton.simulator.entity.Prototype; import edu.wheaton.simulator.statistics.StatisticsManager; public class StatisticsScreen extends Screen { private JPanel dataPanel; private String[] entities; private String[] agentFields; private JComboBox cardSelector; private JComboBox popEntityBox; private JComboBox fieldEntityBox; private JComboBox lifeEntityBox; private Map<String, JComboBox> agentFieldsBoxes; private JPanel fieldCard; private StatisticsManager statMan; private static final long serialVersionUID = 714636604315959167L; //TODO fix layout of this screen //TODO make sure that correct fields box gets put on the panel when an agent is selected. public StatisticsScreen(final ScreenManager sm) { super(sm); statMan = sm.getStatManager(); dataPanel = new JPanel(); dataPanel.setLayout(new CardLayout()); this.setLayout(new BorderLayout()); final String populationsStr = "Populations"; final String fieldsStr = "Fields"; final String lifespansStr = "Lifespans"; JPanel populationCard = makePopulationCard(); dataPanel.add(populationCard, populationsStr); fieldCard = makeFieldCard(); dataPanel.add(fieldCard, fieldsStr); JPanel lifespanCard = makeLifespanCard(); dataPanel.add(lifespanCard, lifespansStr); JPanel boxPanel = new JPanel(); String[] boxItems = {populationsStr, fieldsStr, lifespansStr}; cardSelector = makeCardSelector(boxItems,dataPanel); boxPanel.add(cardSelector); entities = new String[0]; popEntityBox = new JComboBox(entities); populationCard.add(popEntityBox); agentFields = new String[0]; agentFieldsBoxes = new HashMap<String, JComboBox>(); agentFieldsBoxes.put("", new JComboBox(agentFields)); fieldEntityBox = makeFieldEntityBox(entities); fieldCard.add(fieldEntityBox); fieldCard.add(agentFieldsBoxes.get("")); lifeEntityBox = new JComboBox(entities); lifespanCard.add(lifeEntityBox); if(popEntityBox.getSelectedIndex() >= 0){ int[] popVsTime = sm.getStatManager().getPopVsTime(sm.getFacade(). getPrototype(popEntityBox.getSelectedItem().toString()) .getPrototypeID() ); Object[][] timePop = new Object[popVsTime.length][2]; for(int i = 0; i < popVsTime.length; i++) timePop[i] = new Object[]{i, popVsTime[i]}; JTable jt = makeTable(timePop,"Population","Time"); populationCard.add(jt); } JButton displayButton = makeDisplayButton(populationsStr,fieldsStr); JButton finishButton = makeFinishButton(); //COMING SOON: Average Field Table Statistics // if(fieldEntityTypes.getSelectedIndex() >= 0){ // double[] p = statMan.getAvgFieldValue((sm.getFacade(). // getPrototype(popEntityTypes.getSelectedItem().toString()) // .getPrototypeID()), (String) agentFieldsBox.getSelectedItem() // String[] popTime = {"Population", "Time"}; // Object[][] timePop = new Object[p.length][2]; // for(int i = 0; i < p.length; i++){ // Object[] array= {i, p[i]}; // timePop[i] = array; // JTable jt = new JTable(timePop ,popTime); // populationCard.add(jt); // JLabel label = new JLabel("Statistics"); // label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); // label.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); // label.setPreferredSize(new Dimension(300, 150)); // this.add(label, BorderLayout.NORTH); JPanel graphPanel = new JPanel(); JPanel buttonPanel = new JPanel(); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); //TODO MAJOR figure out how to make a graph or something!! buttonPanel.add(displayButton); buttonPanel.add(finishButton); graphPanel.add(new JLabel("Graph object goes here")); mainPanel.add(graphPanel); mainPanel.add(boxPanel); mainPanel.add(dataPanel); mainPanel.add(buttonPanel); this.add(mainPanel); } private static JTable makeTable(Object[][] data, String label1, String label2){ String[] labels = {label1, label2}; JTable jt = new JTable(data ,labels); return jt; } private JButton makeDisplayButton(final String populationsStr, final String fieldsStr){ JButton displayButton = new JButton("Display"); displayButton.setPreferredSize(new Dimension(150, 70)); displayButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (cardSelector.getSelectedItem().equals(populationsStr)) { int[] pops = statMan.getPopVsTime(sm.getFacade(). getPrototype((String)popEntityBox.getSelectedItem()) .getPrototypeID()); System.out.println("Population over time: "); //TODO temporary solution to demonstrate compatibility //TODO this loop displays nothing for a basic simulation for (int i = 0; i < pops.length; i++) { System.out.println(i + ": " + pops[i]); } } else if (cardSelector.getSelectedItem().equals(fieldsStr)) { String s = (String)fieldEntityBox.getSelectedItem(); Prototype p = sm.getFacade().getPrototype(s); double[] vals = statMan.getAvgFieldValue(p.getPrototypeID(), ((String)agentFieldsBoxes.get(s).getSelectedItem())); //TODO temporary solution to demonstrate compatibility //TODO this loop displays nothing for a basic simulation System.out.println("Average field value over time: "); for (int i = 0; i < vals.length; i++) { System.out.println(i + ": " + vals[i]); } } else { Prototype p = sm.getFacade().getPrototype((String)lifeEntityBox.getSelectedItem()); //TODO temporary solution to demonstrate compatibility //getAvgLifespan returns NaN (not a number; 0 / 0 ?) System.out.println("Average lifespan: " + statMan.getAvgLifespan(p.getPrototypeID())); } } } ); return displayButton; } private JButton makeFinishButton(){ JButton finishButton = new JButton("Finish"); finishButton.setPreferredSize(new Dimension(150, 70)); finishButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sm.update(sm.getScreen("Edit Simulation")); } }); return finishButton; } private JComboBox makeFieldEntityBox(String[] entities){ JComboBox box = new JComboBox(entities); box.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { fieldCard.remove(1); fieldCard.add(agentFieldsBoxes.get(e.getItem())); validate(); repaint(); } } ); return box; } private static JComboBox makeCardSelector(final String[] boxItems, final JPanel dataPanel){ JComboBox selector = new JComboBox(boxItems); selector.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { CardLayout cl = (CardLayout)dataPanel.getLayout(); cl.show(dataPanel, (String)e.getItem()); } } ); return selector; } private static JPanel makePopulationCard(){ JPanel popCard = new JPanel(); popCard.setLayout(new BoxLayout(popCard, BoxLayout.X_AXIS)); return popCard; } private static JPanel makeFieldCard(){ JPanel fieldCard = new JPanel(); fieldCard.setLayout(new BoxLayout(fieldCard, BoxLayout.X_AXIS)); return fieldCard; } private static JPanel makeLifespanCard(){ JPanel lifespanCard = new JPanel(); lifespanCard.setLayout(new BoxLayout(lifespanCard, BoxLayout.X_AXIS)); return lifespanCard; } //TODO finish this @Override public void load() { entities = new String[sm.getFacade().prototypeNames().size()]; popEntityBox.removeAllItems(); fieldEntityBox.removeAllItems(); lifeEntityBox.removeAllItems(); agentFieldsBoxes.clear(); int i = 0; for (String s : sm.getFacade().prototypeNames()) { entities[i++] = s; agentFields = sm.getFacade().getPrototype(s).getCustomFieldMap().keySet().toArray(agentFields); agentFieldsBoxes.put(s, new JComboBox(agentFields)); popEntityBox.addItem(s); fieldEntityBox.addItem(s); lifeEntityBox.addItem(s); } } }
package com.zierfisch.render; import org.joml.Vector3f; import org.joml.Vector3fc; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.zierfisch.flocking.FlockingComponent; /** * This system applies the acceleration and velocity onto the position taking the delta time into account. */ public class MovementSystem extends IteratingSystem { public MovementSystem() { super(Family.one(Pose.class).get()); } @Override protected void processEntity(Entity entity, float deltaTime) { Pose p = entity.getComponent(Pose.class); p.velocity.add(p.acceleration); // clamp to maxSpeed if(p.velocity.lengthSquared() > Pose.maxSpeed*Pose.maxSpeed){ p.velocity.normalize(); p.velocity.mul(Pose.maxSpeed); } p.position.add(p.velocity.mul(deltaTime, new Vector3f())); if(p.acceleration.lengthSquared() > 0){ p.orientation.identity(); p.orientation.lookAlong(p.acceleration.normalize(), new Vector3f(0,1,0)); p.orientation.normalize(); } p.acceleration.zero(); p.smut(); } }
package io.spine.code.java; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.Descriptors.Descriptor; import io.spine.test.code.NoOuterClassnameSourceFileTest.NoOuterClassnameMessage; import io.spine.test.code.SourceFile.NestedMessage; import io.spine.test.code.StandaloneMessage; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import spine.test.code.InheritAllSourceFileTest.InheritAllMessage; import spine.test.code.InheritPackage; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Dmytro Dashenkov */ @DisplayName("Java SourceFile should") @SuppressWarnings("InnerClassMayBeStatic") // Nested test suite. class SourceFileTest { @DisplayName("compile path to class generated from message which") @Nested class GeneratedMessage { @Test @DisplayName("has a separate file") void separate() { checkPath("io/spine/test/code/StandaloneMessage.java", StandaloneMessage.getDescriptor()); } @Test @DisplayName("is declared in an outer class with a custom name") void nested() { checkPath("io/spine/test/code/SourceFile.java", NestedMessage.getDescriptor()); } @Test @DisplayName("is declared in an outer class with the default name") void nestedInDefault() { checkPath("io/spine/test/code/NoOuterClassnameSourceFileTest.java", NoOuterClassnameMessage.getDescriptor()); } @Test @DisplayName("inherits Protobuf package") void noPackage() { checkPath("spine/test/code/InheritPackage.java", InheritPackage.getDescriptor()); } @Test @DisplayName("inherits Protobuf package and is declared in an outer class") void inheritAll() { checkPath("spine/test/code/InheritAllSourceFileTest.java", InheritAllMessage.getDescriptor()); } } private static void checkPath(String expectedName, Descriptor descriptor) { DescriptorProto message = descriptor.toProto(); FileDescriptorProto file = descriptor.getFile().toProto(); SourceFile sourceFile = SourceFile.forMessage(message, file); assertEquals(expectedName, sourceFile.toString()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.micromanager.api; import ij.gui.ImageWindow; /** * To use register your implementation of ImageFocusListener, * call GUIUtils.registerImageFocusListener(ImageFocusListener l); */ public interface ImageFocusListener { public void focusReceived(ImageWindow focusedWindow); }
package de.ddb.pdc.metadata; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.xml.xpath.Jaxp13XPathTemplate; import org.springframework.xml.xpath.XPathOperations; import org.w3c.dom.Node; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; /** * Implementation of the {@link MetaFetcher} interface. */ public class MetaFetcherImpl implements MetaFetcher { private static final String URL = "https: private RestTemplate restTemplate; private String apiKey; private XPathOperations xpathTemplate; /** * Creates a new object of the class MetaFetcherImpl. * This class collects the needed information for answering the questions. * The data about works and authors is collected by calls to the DDB API. * * @param restTemplate RestTemplate to use for issuing requests * @param apiKey DDB API key for authentication */ public MetaFetcherImpl(RestTemplate restTemplate, String apiKey) { this.restTemplate = restTemplate; this.restTemplate.getMessageConverters() .add(new Jaxb2RootElementHttpMessageConverter()); this.apiKey = apiKey; initNamespaces(); } /** * initialize the namespaces for XPath */ private void initNamespaces() { Map<String,String> namespaces = new HashMap<String,String>(); namespaces.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns namespaces.put("gndo", "http://d-nb.info/standards/elementset/gnd namespaces.put("ctx", "http: namespaces.put("ns2", "http: namespaces.put("ns3", "http://www.w3.org/1999/02/22-rdf-syntax-ns namespaces.put("ns4", "http: namespaces.put("ore", "http: namespaces.put("edm", "http: namespaces.put("skos", "http://www.w3.org/2004/02/skos/core namespaces.put("dc", "http://purl.org/dc/elements/1.1/" ); namespaces.put("dcterms", "http://purl.org/dc/terms/"); Jaxp13XPathTemplate jaxp13XPathTemplate = new Jaxp13XPathTemplate(); jaxp13XPathTemplate.setNamespaces(namespaces); this.xpathTemplate = jaxp13XPathTemplate; } /** * {@inheritDoc} */ public DDBItem[] searchForItems(String query, int startItem, int maxCount, String sort) throws RestClientException { String url = ApiUrls.searchUrl(query, startItem, maxCount, sort, apiKey); SearchResults results = restTemplate.getForObject(url, SearchResults.class); return getDDBItems(results); } private DDBItem[] getDDBItems(SearchResults results) { if (results.getResultItems() == null) { return new DDBItem[0]; } int numItems = results.getResultItems().size(); DDBItem[] ddbItems = new DDBItem[numItems]; int idx = 0; for (SearchResultItem rsi : results.getResultItems()) { DDBItem ddbItem = new DDBItem(rsi.getId()); ddbItem.setMaxResults(results.getNumberOfResults()); ddbItem.setTitle(deleteMatchTags(rsi.getTitle())); ddbItem.setSubtitle(deleteMatchTags(rsi.getSubtitle())); ddbItem.setImageUrl(URL + rsi.getThumbnail()); ddbItem.setCategory(rsi.getCategory()); ddbItem.setMedia(rsi.getMedia()); ddbItem.setType(rsi.getType()); ddbItems[idx] = ddbItem; idx++; } return ddbItems; } private static String deleteMatchTags(String string) { return string.replace("<match>", "").replace("</match>", ""); } /** * {@inheritDoc} */ public DDBItem fetchMetadata(String itemId) throws RestClientException { DDBItem ddbItem = new DDBItem(itemId); String url = ApiUrls.itemAipUrl(itemId, apiKey); DOMSource result = restTemplate.getForObject(url, DOMSource.class); if (result != null) { fillDDBItem(ddbItem, result); fetchAuthorMetadata(ddbItem); } return ddbItem; } private void fillDDBItem(DDBItem item, DOMSource result) { String xpathIssued = "//dcterms:issued"; String xpathInstitution = "//edm:dataProvider[1]"; item.setPublishedYear(getDateAsInt(xpathTemplate .evaluateAsString(xpathIssued, result),"\\d{4}")); item.setInstitution(xpathTemplate .evaluateAsString(xpathInstitution, result)); for (String authorId : listAuthorIDs(result)) { Author author = new Author(authorId); item.addAuthor(author); } } private int getDateAsInt(String date, String regex) { return Integer.parseInt(MetadataUtils.useRegex(date, regex)); } private List<String> listAuthorIDs(DOMSource domSource) { List<String> authorIDs = new ArrayList<String>(); String xpathFacetRole = "//ctx:facet[@name='affiliate_fct_role_normdata']/ctx:value"; String xpathFacet = "//ctx:facet[@name='affiliate_fct_normdata']/ctx:value"; List<Node> nodes = xpathTemplate.evaluateAsNodeList(xpathFacetRole, domSource); for (Node node : nodes) { String value = node.getFirstChild().getTextContent(); if (value.endsWith("_1_affiliate_fct_subject") || value.endsWith("_1_affiliate_fct_involved")) { authorIDs.add(value.split("_")[0]); } } if (authorIDs.size() == 0) { nodes = xpathTemplate.evaluateAsNodeList(xpathFacet, domSource); for (Node node : nodes) { authorIDs.add(node.getFirstChild().getTextContent()); } } return authorIDs; } private void fetchAuthorMetadata(DDBItem item) { for (Author author : item.getAuthors()) { String dnbUrl = ApiUrls.dnbUrl(author.getDnbId()); DOMSource result = restTemplate.getForObject(dnbUrl, DOMSource.class); fillAuthor(author, result); } } private void fillAuthor(Author author, Source result) { String xpathName = "//gndo:variantNameForThePerson"; String xpathDOB = "//gndo:dateOfBirth"; String xpathDOD = "//gndo:dateOfDeath"; String xpathPOD = "//gndo:placeOfDeath/rdf:Description/@rdf:about"; String xpathLoc = "//gndo:geographicAreaCode/@rdf:resource"; if (result != null) { author.setName(xpathTemplate.evaluateAsString(xpathName, result)); author.setDateOfBirth(formatDateString(xpathTemplate .evaluateAsString(xpathDOB, result))); author.setDateOfDeath(formatDateString(xpathTemplate .evaluateAsString(xpathDOD, result))); String placeOfDeath = xpathTemplate.evaluateAsString(xpathPOD, result); if (placeOfDeath != null) { String dnbUrl = ApiUrls.dnbUrl(placeOfDeath); DOMSource location = restTemplate.getForObject(dnbUrl, DOMSource.class); if (location != null) { author.setNationality(iso2Locate(xpathTemplate .evaluateAsString(xpathLoc, location))); } } } } private Calendar formatDateString(String date) { Calendar cal = null; String[] temp = date.split("-"); if (temp.length == 3) { cal = new GregorianCalendar(); cal.set(Integer.parseInt(temp[0]),Integer.parseInt(temp[1]), Integer.parseInt(temp[2])); } return cal; } private String iso2Locate(String location) { if (location != null) { String[] temp = location.split(" String[] temp2 = temp[temp.length - 1].split("-"); if (temp2.length > 2) { return temp2[1].toLowerCase(); } } return null; } }
package jetbrains.buildServer.clouds.kubernetes.podSpec; import com.intellij.openapi.util.Pair; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.extensions.Deployment; import jetbrains.buildServer.clouds.CloudInstanceUserData; import jetbrains.buildServer.clouds.kubernetes.*; import jetbrains.buildServer.serverSide.ServerSettings; import jetbrains.buildServer.util.CollectionsUtil; import jetbrains.buildServer.util.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class DeploymentBuildAgentPodTemplateProvider implements BuildAgentPodTemplateProvider { public static final String ID = "deployment-base"; private final ServerSettings myServerSettings; private final DeploymentContentProvider myDeploymentContentProvider; public DeploymentBuildAgentPodTemplateProvider(ServerSettings serverSettings, DeploymentContentProvider deploymentContentProvider) { myServerSettings = serverSettings; myDeploymentContentProvider = deploymentContentProvider; } @NotNull @Override public String getId() { return ID; } @NotNull @Override public String getDisplayName() { return "Use pod template from deployment"; } @Nullable @Override public String getDescription() { return null; } @NotNull @Override public Pod getPodTemplate(@NotNull CloudInstanceUserData cloudInstanceUserData, @NotNull KubeCloudImage kubeCloudImage, @NotNull KubeCloudClientParameters kubeClientParams) { String sourceDeploymentName = kubeCloudImage.getSourceDeploymentName(); if(StringUtil.isEmpty(sourceDeploymentName)) throw new KubeCloudException("Deployment name is not set in kubernetes cloud image " + kubeCloudImage.getId()); Deployment sourceDeployment = myDeploymentContentProvider.findDeployment(sourceDeploymentName, kubeClientParams); if(sourceDeployment == null) throw new KubeCloudException("Can't find source deployment by name " + sourceDeploymentName); final String agentNameProvided = cloudInstanceUserData.getAgentName(); final String instanceName = StringUtil.isEmpty(agentNameProvided) ? sourceDeploymentName + "-" + UUID.randomUUID().toString() : agentNameProvided; final String serverAddress = cloudInstanceUserData.getServerAddress(); PodTemplateSpec podTemplateSpec = sourceDeployment.getSpec().getTemplate(); ObjectMeta metadata = podTemplateSpec.getMetadata(); metadata.setName(instanceName); metadata.setNamespace(kubeClientParams.getNamespace()); String serverUUID = myServerSettings.getServerUUID(); String cloudProfileId = cloudInstanceUserData.getProfileId(); Map<String, String> patchedLabels = new HashMap<>(); patchedLabels.putAll(metadata.getLabels()); patchedLabels.putAll(CollectionsUtil.asMap( KubeTeamCityLabels.TEAMCITY_AGENT_LABEL, "", KubeTeamCityLabels.TEAMCITY_SERVER_UUID, serverUUID, KubeTeamCityLabels.TEAMCITY_CLOUD_PROFILE, cloudProfileId, KubeTeamCityLabels.TEAMCITY_CLOUD_IMAGE, kubeCloudImage.getId())); metadata.setLabels(patchedLabels); PodSpec spec = podTemplateSpec.getSpec(); for (Container container : spec.getContainers()){ Map<String, String> patchedEnvData = new HashMap<>(); for (EnvVar env : container.getEnv()){ patchedEnvData.put(env.getName(), env.getValue()); } for (Pair<String, String> env : Arrays.asList( new Pair<>(KubeContainerEnvironment.SERVER_UUID, serverUUID), new Pair<>(KubeContainerEnvironment.PROFILE_ID, cloudProfileId), new Pair<>(KubeContainerEnvironment.AGENT_NAME, kubeCloudImage.getAgentName(instanceName)), new Pair<>(KubeContainerEnvironment.IMAGE_NAME, kubeCloudImage.getName()), new Pair<>(KubeContainerEnvironment.INSTANCE_NAME, instanceName))){ patchedEnvData.put(env.first, env.second); } if(!patchedEnvData.containsKey(KubeContainerEnvironment.SERVER_URL)){ patchedEnvData.put(KubeContainerEnvironment.SERVER_URL, serverAddress); } if(!patchedEnvData.containsKey(KubeContainerEnvironment.OFFICIAL_IMAGE_SERVER_URL)){ patchedEnvData.put(KubeContainerEnvironment.OFFICIAL_IMAGE_SERVER_URL, serverAddress); } List<EnvVar> patchedEnv = new ArrayList<>(); for (String envName : patchedEnvData.keySet()){ patchedEnv.add(new EnvVar(envName, patchedEnvData.get(envName), null)); } container.setEnv(patchedEnv); } final Pod pod = new Pod(); pod.setMetadata(metadata); pod.setSpec(spec); return pod; } }
package de.maikmerten.quaketexturetool; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Queue; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; /** * * @author maik */ public class Main { private final static String opt_reduce = "reduce"; private final static String opt_ditherfull = "ditherfullbrights"; private final static String opt_ditherstrength = "ditherstrength"; private final static String opt_liquidfullbrights = "liquidfullbrights"; private final static String opt_output = "output"; public static void main(String[] args) throws Exception { // set up command line parsing Options opts = new Options(); opts.addOption("h", "help", false, "Displays help"); opts.addOption(opt_reduce, true, "Downsampling factor (default: 4)"); opts.addOption(opt_ditherfull, true, "Dither fullbrights (default: 0)"); opts.addOption(opt_ditherstrength, true, "Dither strength (default: 0.25)"); opts.addOption(opt_liquidfullbrights, true, "Allow fullbrights on liquids (default: 0)"); opts.addOption(opt_output, true, "file name for output WAD"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, args); if(cmd.hasOption("help") || cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar QuakeTextureTool.jar", opts); System.exit(0); } if(!cmd.hasOption(opt_output)) { System.out.println(" System.out.println("Use the -h option to get a list of options."); System.exit(1); } int reduce = Integer.parseInt(cmd.getOptionValue(opt_reduce, "4")); boolean ditherFullbrights = Integer.parseInt(cmd.getOptionValue(opt_ditherfull, "0")) != 0; float ditherStrength = 0.25f; if(cmd.hasOption(opt_ditherstrength)) { ditherStrength = Float.parseFloat(cmd.getOptionValue(opt_ditherstrength)); } boolean noLiquidFullbrights = Integer.parseInt(cmd.getOptionValue(opt_liquidfullbrights, "0")) == 0; String outputFile = cmd.getOptionValue(opt_output); Converter conv = new Converter(); conv.setReduce(reduce); conv.setDitherFullbrights(ditherFullbrights); conv.setDitherStrength(ditherStrength); File workingDir = new File("."); FileFinder fileFinder = new FileFinder(workingDir); Queue<File> colorMapFiles = fileFinder.findColorMaps(); Wad wad = new Wad(); List<Thread> threads = new ArrayList<>(); for(int i = 0; i < Runtime.getRuntime().availableProcessors(); ++i) { Thread t = new ConverterThread(colorMapFiles, conv, wad, fileFinder, noLiquidFullbrights); threads.add(t); t.start(); } for(Thread t : threads) { t.join(); } File wadFile = new File(outputFile); try (FileOutputStream fos = new FileOutputStream(wadFile)) { wad.write(fos); } } }
package org.meshwork.core.transport.serial.jssc; import jssc.*; import org.meshwork.core.AbstractMessageTransport; import org.meshwork.core.MessageData; import org.meshwork.core.TransportTimeoutException; import java.io.IOException; public class SerialMessageTransport implements AbstractMessageTransport, SerialPortEventListener { protected SerialPort port; protected String portName; public SerialMessageTransport() { } public void init(SerialConfiguration config, String portName) throws Exception { //todo set up port, etc. and call init(port) port = new SerialPort(portName); port.openPort(); port.setParams(config.getBaudRate(), config.getDataBits(), config.getStopBits(), config.getParity(), config.isSetRTS(), config.isSetDTR()); initPort(port); } public void deinit() throws Exception { port.removeEventListener(); port.closePort(); port = null; portName = null; } //port assumed to be set up with correct settings, opened by the caller before calling this method, and having no other event listener added public void initPort(SerialPort port) throws Exception { if ( port == null ) throw new IllegalArgumentException("SerialPort cannot be null!"); this.port = port; try { port.addEventListener(this);//, SerialPort.MASK_RXCHAR); } catch (SerialPortException e) { e.printStackTrace(); this.port = null; throw e; } finally { port.removeEventListener(); } purgeBuffers(true, true); } //port assumed to be closed by the caller after this method returns public void deinitPort() throws Exception { if ( port == null ) throw new IllegalArgumentException("SerialPort not yet initialized!"); purgeBuffers(true, true); try { port.removeEventListener(); } catch (SerialPortException e) { e.printStackTrace(); port = null; throw e; } } protected boolean purgeBuffers(boolean read, boolean write) { boolean result = false; try { result = port.purgePort( (read ? (SerialPort.PURGE_RXABORT | SerialPort.PURGE_RXCLEAR) : 0 ) | (write ? (SerialPort.PURGE_TXABORT | SerialPort.PURGE_TXCLEAR) : 0 ) ); } catch (Exception e) { e.printStackTrace(); } return result; } @Override public MessageData readMessage(int timeout) throws TransportTimeoutException, IOException { MessageData result = null; try { result = _readOneMessage(timeout); } finally { purgeBuffers(true, true); } return result; } protected MessageData _readOneMessage(int timeout) throws TransportTimeoutException, IOException { MessageData result = new MessageData(); byte[] header = null; try { System.out.println("<<<<<<<<<< ENTER SerialMessageTransport._readOneMessage with timeout: "+timeout+" <<<<<<<<<<"); header = port.readBytes(3, timeout); } catch (SerialPortTimeoutException e) { throw new TransportTimeoutException("Timeout while reading the message header:" +e.getMessage(), e); } catch (Exception e) { throw new IOException("Exception while reading the message header: "+e.getMessage(), e); } result.seq = header[0]; result.len = header[1]; result.code = header[2]; if ( result.len > 1 ) { try { result.data = port.readBytes(result.len-1, timeout); } catch (SerialPortTimeoutException e) { throw new TransportTimeoutException("Timeout while reading the message header:" +e.getMessage(), e); } catch (Exception e) { throw new IOException("Exception while reading the message header: "+e.getMessage(), e); } } System.out.println("<<<<<<<<<< EXIT SerialMessageTransport._readOneMessage data: "+result+" <<<<<<<<<<"); return result; } @Override public int sendMessage(MessageData message) throws IOException { int result = SEND_NOK; try { result = _sendOneMessage(message); } catch (Exception e) { throw new IOException(e); } finally { purgeBuffers(true, false); } return result; } protected int _sendOneMessage(MessageData message) throws SerialPortException { System.out.println(">>>>>>>>>> ENTER SerialMessageTransport._sendOneMessage: "+message+" >>>>>>>>>>"); // port.writeByte(message.seq); // port.writeByte(message.len); // port.writeByte(message.code); // if ( message.len > 1 ) // port.writeBytes(message.data); byte[] temp = new byte[2 + message.len]; temp[0] = message.seq; temp[1] = message.len; temp[2] = message.code; if ( message.len > 1 ) System.arraycopy(message.data, 0, temp, 3, message.len-1); port.writeBytes(temp); System.out.println(">>>>>>>>>> EXIT SerialMessageTransport._sendOneMessage >>>>>>>>>>"); return SEND_OK; } @Override public void serialEvent(SerialPortEvent serialPortEvent) { //TODO decide later on if we should process the data async or not //TODO implement start-of-message markers for port disconnection robustness } }
package de.oio.refactoring.badtelefon; public class Kunde { double gebuehr = 0.0; Tarif tarif; public Kunde(int tarifArt) { this.tarif = new Tarif(tarifArt); } public void account(int minuten, int stunde, int minute) { String message1 = String.format("Berechne Gesprch mit %02d min um %02d:%02d mit Tarif %s", minuten, stunde, minute, tarif.tarif); writeToConsole(message1); double preis = 0; boolean mondschein = isMondschein(stunde); // Gespraechspreis ermitteln switch (tarif.tarif) { case Tarif.PRIVAT: minuten = minuten - 1; minuten = minuten < 0 ? 0 : minuten; if (mondschein) preis = minuten * 0.69; else preis = minuten * 1.99; break; case Tarif.BUSINESS: if (mondschein) preis = minuten * 0.79; else preis = minuten * 1.29; break; case Tarif.PROFI: preis = minuten * 0.69; break; } String message2 = String.format("Preis fr das Gesprch: %.2f", preis); writeToConsole(message2); gebuehr += preis; String message3 = String.format("Gesamtgebhr nach Gesprch um %02d:%02d (Mondscheinzeit: %s): %.2f", stunde, minute, mondschein, gebuehr); writeToConsole(message3); } protected void writeToConsole(String message1) { System.out.println(message1); } protected static boolean isMondschein(int stunde) { return stunde < 9 || stunde > 18; } public double getGebuehr() { return gebuehr; } }
package de.prob2.ui; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.dotty.DottyView; import de.prob2.ui.history.HistoryView; import de.prob2.ui.modelchecking.ModelcheckingController; import de.prob2.ui.operations.OperationsView; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Accordion; import javafx.scene.control.SplitPane; import javafx.scene.control.TitledPane; import javafx.scene.input.MouseEvent; import java.io.IOException; @Singleton public class NewAnimationPerspective extends SplitPane{ @FXML private OperationsView operations; @FXML private TitledPane operationsTP; @FXML private HistoryView history; @FXML private TitledPane historyTP; @FXML private DottyView dotty; @FXML private TitledPane dottyTP; @FXML private ModelcheckingController modelcheck; @FXML private TitledPane modelcheckTP; @FXML private Accordion accordion; @Inject public NewAnimationPerspective() { try { FXMLLoader loader = ProB2.injector.getInstance(FXMLLoader.class); loader.setLocation(getClass().getResource("new_animation_perspective.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); parentProperty().addListener((ObservableValue<? extends Parent> ov, Parent previousParent, Parent nextParent)-> { onDrag(); }); } catch (IOException e) { e.printStackTrace(); } } @FXML public void initialize() {} private void onDrag() { operations.setOnDragDetected((MouseEvent t) -> { if (!this.getChildren().contains(operations)){ this.getItems().add(operations); accordion.getPanes().remove(operationsTP); removeAccordion(); } else { addAccordion(); operationsTP.setContent(operations); accordion.getPanes().add(0,operationsTP); } }); history.setOnDragDetected((MouseEvent t) -> { if (!this.getChildren().contains(history)){ this.getItems().add(history); accordion.getPanes().remove(historyTP); removeAccordion(); } else { addAccordion(); historyTP.setContent(history); accordion.getPanes().add(1,historyTP); } }); dotty.setOnDragDetected((MouseEvent t) -> { if (!this.getChildren().contains(dotty)){ this.getItems().add(dotty); accordion.getPanes().remove(dottyTP); removeAccordion(); } else { addAccordion(); dottyTP.setContent(dotty); accordion.getPanes().add(2,dottyTP); } }); modelcheck.setOnDragDetected((MouseEvent t) -> { if (!this.getChildren().contains(modelcheck)){ this.getItems().add(modelcheck); accordion.getPanes().remove(modelcheckTP); removeAccordion(); } else { addAccordion(); modelcheckTP.setContent(modelcheck); accordion.getPanes().add(3,modelcheckTP); } }); } void removeAccordion(){ if (accordion.getPanes().size()==0){ this.getItems().remove(0); } } void addAccordion(){ if (!this.getChildren().contains(accordion)){ this.getItems().add(0,accordion); } } }
package org.openhab.binding.ambientweather.internal.handler; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.openhab.binding.ambientweather.internal.model.DeviceJson; import org.openhab.binding.ambientweather.internal.model.EventDataGenericJson; import org.openhab.binding.ambientweather.internal.model.EventSubscribedJson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; /** * The {@link AmbientWeatherEventListener} is responsible for establishing * a socket.io connection with ambientweather.net, subscribing/unsubscribing * to data events, receiving data events through the real-time socket.io API, * and for routing the data events to a weather station thing handler for processing. * * @author Mark Hilbush - Initial contribution */ public class AmbientWeatherEventListener { // URL used to get the realtime event stream private static final String REALTIME_URL = "https://api.ambientweather.net/?api=1&applicationKey=%APPKEY%"; // JSON used to subscribe or unsubscribe from weather data events private static final String SUB_UNSUB_JSON = "{ apiKeys: [ '%APIKEY%' ] }"; private final Logger logger = LoggerFactory.getLogger(AmbientWeatherEventListener.class); // Maintain mapping of handler and weather station MAC address private final Map<AmbientWeatherStationHandler, String> handlers = new ConcurrentHashMap<>(); private String apiKey; private String applicationKey; // Socket.io socket used to access Ambient Weather real-time API private Socket socket; // Identifies if connected to real-time API private boolean isConnected; private Gson gson; private AmbientWeatherBridgeHandler bridgeHandler; public AmbientWeatherEventListener(AmbientWeatherBridgeHandler bridgeHandler) { this.bridgeHandler = bridgeHandler; } /* * Update the list of handlers to include 'handler' at MAC address 'macAddress' */ public void addHandler(AmbientWeatherStationHandler handler, String macAddress) { logger.debug("Listener: Add station handler to list: {}", handler.getThing().getUID()); handlers.put(handler, macAddress); } /* * Update the list of handlers to remove 'handler' at MAC address 'macAddress' */ public void removeHandler(AmbientWeatherStationHandler handler, String macAddress) { logger.debug("Listener: Remove station handler from list: {}", handler.getThing().getUID()); handlers.remove(handler); } /* * Send weather station information (station name and location) to the * thing handler associated with the MAC address */ private void sendStationInfoToHandler(String macAddress, String name, String location) { AmbientWeatherStationHandler handler = getHandler(macAddress); if (handler != null) { handler.handleInfoEvent(macAddress, name, location); } } /* * Send an Ambient Weather data event to the station thing handler associated * with the MAC address */ private void sendWeatherDataToHandler(String macAddress, String jsonData) { AmbientWeatherStationHandler handler = getHandler(macAddress); if (handler != null) { handler.handleWeatherDataEvent(jsonData); } } private AmbientWeatherStationHandler getHandler(String macAddress) { logger.debug("Listener: Search for MAC {} in handlers list with {} entries: {}", macAddress, handlers.size(), Arrays.asList(handlers.values())); for (Map.Entry<AmbientWeatherStationHandler, String> device : handlers.entrySet()) { AmbientWeatherStationHandler handler = device.getKey(); String mac = device.getValue(); if (mac.equalsIgnoreCase(macAddress)) { logger.debug("Listener: Found handler for {} with MAC {}", handler.getThing().getUID(), macAddress); return handler; } } logger.debug("Listener: No handler available for event for station with MAC {}", macAddress); return null; } /* * Start the event listener for the Ambient Weather real-time API */ public void start(String applicationKey, String apiKey, Gson gson) { logger.debug("Listener: Event listener starting"); this.applicationKey = applicationKey; this.apiKey = apiKey; this.gson = gson; connectToService(); } /* * Stop the event listener for the Ambient Weather real-time API. */ public void stop() { logger.debug("Listener: Event listener stopping"); sendUnsubscribe(); disconnectFromService(); handlers.clear(); } /* * Initiate the connection to the Ambient Weather real-time API */ private synchronized void connectToService() { final String url = REALTIME_URL.replace("%APPKEY%", applicationKey); try { IO.Options options = new IO.Options(); options.forceNew = true; options.transports = new String[] { "websocket" }; socket = IO.socket(url, options); } catch (URISyntaxException e) { logger.info("Listener: URISyntaxException getting IO socket: {}", e.getMessage()); return; } socket.on(Socket.EVENT_CONNECT, onEventConnect); socket.on(Socket.EVENT_CONNECT_ERROR, onEventConnectError); socket.on(Socket.EVENT_CONNECT_TIMEOUT, onEventConnectTimeout); socket.on(Socket.EVENT_DISCONNECT, onEventDisconnect); socket.on(Socket.EVENT_RECONNECT, onEventReconnect); socket.on("data", onData); socket.on("subscribed", onSubscribed); logger.debug("Listener: Opening connection to ambient weather service with socket {}", socket.toString()); socket.connect(); } /* * Initiate a disconnect from the Ambient Weather real-time API */ private void disconnectFromService() { if (socket != null) { logger.debug("Listener: Disconnecting socket and removing event listeners for {}", socket.toString()); socket.disconnect(); socket.off(); socket = null; } } /* * Attempt to reconnect to the Ambient Weather real-time API */ private void reconnectToService() { logger.debug("Listener: Attempting to reconnect to service"); disconnectFromService(); connectToService(); } /* * Socket.io event callbacks */ private Emitter.Listener onEventConnect = new Emitter.Listener() { @Override public void call(final Object... args) { logger.debug("Listener: Connected! Subscribe to weather data events"); isConnected = true; bridgeHandler.markBridgeOnline(); sendSubscribe(); } }; private Emitter.Listener onEventDisconnect = new Emitter.Listener() { @Override public void call(final Object... args) { logger.debug("Listener: Disconnected from the ambient weather service)"); handleError(Socket.EVENT_DISCONNECT, args); isConnected = false; } }; private Emitter.Listener onEventConnectError = new Emitter.Listener() { @Override public void call(final Object... args) { handleError(Socket.EVENT_CONNECT_ERROR, args); } }; private Emitter.Listener onEventConnectTimeout = new Emitter.Listener() { @Override public void call(final Object... args) { handleError(Socket.EVENT_CONNECT_TIMEOUT, args); } }; private Emitter.Listener onEventReconnect = new Emitter.Listener() { @Override public void call(final Object... args) { logger.debug("Listener: Received reconnect event from service"); reconnectToService(); } }; private Emitter.Listener onSubscribed = new Emitter.Listener() { @Override public void call(final Object... args) { logger.debug("Listener: Received SUBSCRIBED event"); // Got a response to a subscribe or unsubscribe command if (args.length > 0) { handleSubscribed(((JSONObject) args[0]).toString()); } } }; private Emitter.Listener onData = new Emitter.Listener() { @Override public void call(final Object... args) { logger.debug("Listener: Received DATA event"); // Got a weather data event from ambientweather.net if (args.length > 0) { handleData(((JSONObject) args[0]).toString()); } } }; /* * Handlers for events */ private void handleError(String event, Object... args) { String reason = "Unknown"; if (args.length > 0) { if (args[0] instanceof String) { reason = (String) args[0]; } else if (args[0] instanceof Exception) { reason = String.format("Exception=%s Message=%s", args[0].getClass(), ((Exception) args[0]).getMessage()); } } logger.debug("Listener: Received socket event: {}, Reason: {}", event, reason); bridgeHandler.markBridgeOffline(reason); } /* * Parse the subscribed event, then tell the handler to update the station info channels. */ private void handleSubscribed(String jsonData) { logger.debug("Listener: subscribed={}", jsonData); // Extract the station names and locations and give to handlers try { EventSubscribedJson subscribed = gson.fromJson(jsonData, EventSubscribedJson.class); if (subscribed.invalidApiKeys != null) { logger.info("Listener: Invalid keys!! invalidApiKeys={}", subscribed.invalidApiKeys); bridgeHandler.markBridgeOffline("Invalid API keys"); return; } if (subscribed.devices != null && subscribed.devices instanceof ArrayList) { // Convert the ArrayList back to JSON, then parse it String innerJson = gson.toJson(subscribed.devices); DeviceJson[] stations = gson.fromJson(innerJson, DeviceJson[].class); // Inform handlers of their name and location for (DeviceJson station : stations) { logger.debug("Listener: Subscribed event has station: name = {}, location = {}, MAC = {}", station.info.name, station.info.location, station.macAddress); sendStationInfoToHandler(station.macAddress, station.info.name, station.info.location); } } if (subscribed.isMethodSubscribe()) { logger.debug("Listener: Subscribed to data events. Waiting for data..."); } else if (subscribed.isMethodUnsubscribe()) { logger.debug("Listener: Unsubscribed from data events"); } } catch (JsonSyntaxException e) { logger.debug("Listener: Exception parsing subscribed.devices: {}", e.getMessage()); } } /* * Parse the weather data event, then send to handler to update the channels */ private synchronized void handleData(String jsonData) { logger.debug("Listener: Data: {}", jsonData); try { EventDataGenericJson data = gson.fromJson(jsonData, EventDataGenericJson.class); if (StringUtils.isNotEmpty(data.macAddress)) { sendWeatherDataToHandler(data.macAddress, jsonData); } } catch (JsonSyntaxException e) { logger.info("Listener: Exception parsing subscribed event: {}", e.getMessage()); } } /* * Subscribe to weather data events for stations associated with the API key */ private void sendSubscribe() { if (apiKey == null) { return; } final String sub = SUB_UNSUB_JSON.replace("%APIKEY%", apiKey); if (isConnected && socket != null) { logger.debug("Listener: Sending subscribe request"); socket.emit("subscribe", new JSONObject(sub)); } } /* * Unsubscribe from weather data events for stations associated with the API key */ private void sendUnsubscribe() { if (apiKey == null) { return; } final String unsub = SUB_UNSUB_JSON.replace("%APIKEY%", apiKey); if (isConnected && socket != null) { logger.debug("Listener: Sending unsubscribe request"); socket.emit("unsubscribe", new JSONObject(unsub)); } } /* * Resubscribe when a handler is initialized */ public synchronized void resubscribe() { sendUnsubscribe(); sendSubscribe(); } }
package dmillerw.event.data.trigger; import com.google.gson.JsonObject; import dmillerw.event.data.lore.Lore; import dmillerw.event.data.lore.LoreRegistry; import dmillerw.event.data.lore.LoreStatusTracker; import dmillerw.event.network.PacketHandler; import dmillerw.event.network.packet.S01PlayLoreAudio; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; /** * @author dmillerw */ public abstract class Trigger { private String loreIdent; // Set upon creation public final void setLoreIdent(String loreIdent) { this.loreIdent = loreIdent; } public final void startPlayingLore(EntityPlayer entityPlayer) { if (hasBeenRead(entityPlayer)) return; Lore lore = LoreRegistry.getLore(loreIdent); if (!lore.repeat) markAsRead(entityPlayer); PacketHandler.INSTANCE.sendTo(new S01PlayLoreAudio(loreIdent), (EntityPlayerMP) entityPlayer); } public final boolean hasBeenRead(EntityPlayer entityPlayer) { return LoreStatusTracker.getStatusTracker(entityPlayer).hasBeenRead(loreIdent); } public final void markAsRead(EntityPlayer entityPlayer) { LoreStatusTracker.getStatusTracker(entityPlayer).markAsRead(loreIdent); } public abstract void acceptData(JsonObject object); }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.api.SearchFields; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.faces.view.ViewScoped; import javax.inject.Named; @ViewScoped @Named("SearchPage") public class SearchPage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(SearchPage.class.getCanonicalName()); private String query; private List<String> filterQueries = new ArrayList<>(); private String fq0; private String fq1; private String fq2; private String fq3; private String fq4; private String fq5; private String fq6; private String fq7; private String fq8; private String fq9; private List<SolrSearchResult> searchResultsList = new ArrayList<>(); private Long searchResultsCount; private int paginationStart; private List<FacetCategory> facetCategoryList = new ArrayList<FacetCategory>(); private List<String> spelling_alternatives = new ArrayList<>(); private Map<String, String> friendlyName = new HashMap<>(); @EJB SearchServiceBean searchService; @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; public SearchPage() { logger.info("SearchPage initialized. Query: " + query); } public void search() { logger.info("Search button clicked. Query: " + query); // query = query.trim(); // buggy, threw an NPE // query = query.isEmpty() ? "*" : query; // also buggy query = query == null ? "*" : query; filterQueries = new ArrayList<>(); for (String fq : Arrays.asList(fq0, fq1, fq2, fq3, fq4, fq5, fq6, fq7, fq8, fq9)) { if (fq != null) { filterQueries.add(fq); } } SolrQueryResponse solrQueryResponse = null; try { solrQueryResponse = searchService.search(query, filterQueries, paginationStart); } catch (EJBException ex) { Throwable cause = ex; StringBuilder sb = new StringBuilder(); sb.append(cause + " "); while (cause.getCause() != null) { cause = cause.getCause(); sb.append(cause.getClass().getCanonicalName() + " "); sb.append(cause + " "); } String message = "Exception running search for [" + query + "] with filterQueries " + filterQueries + " and paginationStart [" + paginationStart + "]: " + sb.toString(); logger.info(message); return; } searchResultsList = solrQueryResponse.getSolrSearchResults(); List<SolrSearchResult> searchResults = solrQueryResponse.getSolrSearchResults(); for (SolrSearchResult solrSearchResult : searchResults) { if (solrSearchResult.getType().equals("dataverses")) { List<Dataset> datasets = datasetService.findByOwnerId(solrSearchResult.getEntityId()); solrSearchResult.setDatasets(datasets); } else if (solrSearchResult.getType().equals("datasets")) { Dataset dataset = datasetService.find(solrSearchResult.getEntityId()); try { if (dataset.getLatestVersion().getMetadata().getCitation() != null) { solrSearchResult.setCitation(dataset.getLatestVersion().getMetadata().getCitation()); } } catch (NullPointerException npe) { logger.info("caught NullPointerException trying to get citation for " + dataset.getId()); } } else if (solrSearchResult.getType().equals("files")) { /** * @todo: show DataTable variables */ } } searchResultsCount = solrQueryResponse.getNumResultsFound(); for (Map.Entry<String, List<String>> entry : solrQueryResponse.getSpellingSuggestionsByToken().entrySet()) { spelling_alternatives.add(entry.getValue().toString()); } facetCategoryList = solrQueryResponse.getFacetCategoryList(); friendlyName.put(SearchFields.SUBTREE, "Dataverse Subtree"); friendlyName.put(SearchFields.ORIGINAL_DATAVERSE, "Original Dataverse"); // friendlyName.put(SearchFields.CATEGORY, "Category"); friendlyName.put(SearchFields.AUTHOR_STRING, "Author"); friendlyName.put(SearchFields.AFFILIATION, "Affiliation"); friendlyName.put(SearchFields.CITATION_YEAR, "Citation Year"); // friendlyName.put(SearchFields.FILE_TYPE, "File Type"); friendlyName.put(SearchFields.FILE_TYPE_GROUP, "File Type"); } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public List<String> getFilterQueries() { return filterQueries; } public void setFilterQueries(List<String> filterQueries) { this.filterQueries = filterQueries; } public String getFq0() { return fq0; } public void setFq0(String fq0) { this.fq0 = fq0; } public String getFq1() { return fq1; } public void setFq1(String fq1) { this.fq1 = fq1; } public String getFq2() { return fq2; } public void setFq2(String fq2) { this.fq2 = fq2; } public String getFq3() { return fq3; } public void setFq3(String fq3) { this.fq3 = fq3; } public String getFq4() { return fq4; } public void setFq4(String fq4) { this.fq4 = fq4; } public String getFq5() { return fq5; } public void setFq5(String fq5) { this.fq5 = fq5; } public String getFq6() { return fq6; } public void setFq6(String fq6) { this.fq6 = fq6; } public String getFq7() { return fq7; } public void setFq7(String fq7) { this.fq7 = fq7; } public String getFq8() { return fq8; } public void setFq8(String fq8) { this.fq8 = fq8; } public String getFq9() { return fq9; } public void setFq9(String fq9) { this.fq9 = fq9; } public List<SolrSearchResult> getSearchResultsList() { return searchResultsList; } public void setSearchResultsList(List<SolrSearchResult> searchResultsList) { this.searchResultsList = searchResultsList; } public Long getSearchResultsCount() { return searchResultsCount; } public void setSearchResultsCount(Long searchResultsCount) { this.searchResultsCount = searchResultsCount; } public int getPaginationStart() { return paginationStart; } public void setPaginationStart(int paginationStart) { this.paginationStart = paginationStart; } public List<FacetCategory> getFacetCategoryList() { return facetCategoryList; } public void setFacetCategoryList(List<FacetCategory> facetCategoryList) { this.facetCategoryList = facetCategoryList; } public List<String> getSpelling_alternatives() { return spelling_alternatives; } public void setSpelling_alternatives(List<String> spelling_alternatives) { this.spelling_alternatives = spelling_alternatives; } public Map<String, String> getFriendlyName() { return friendlyName; } public void setFriendlyName(Map<String, String> friendlyName) { this.friendlyName = friendlyName; } }
package edu.harvard.iq.dataverse.api; import edu.harvard.iq.dataverse.Dataverse; import edu.harvard.iq.dataverse.search.SearchFields; import edu.harvard.iq.dataverse.DataverseServiceBean; import edu.harvard.iq.dataverse.DvObject; import edu.harvard.iq.dataverse.DvObjectServiceBean; import edu.harvard.iq.dataverse.FacetCategory; import edu.harvard.iq.dataverse.FacetLabel; import edu.harvard.iq.dataverse.RoleAssignment; import edu.harvard.iq.dataverse.SolrSearchResult; import edu.harvard.iq.dataverse.SearchServiceBean; import edu.harvard.iq.dataverse.SolrQueryResponse; import edu.harvard.iq.dataverse.authorization.users.User; import edu.harvard.iq.dataverse.search.DvObjectSolrDoc; import edu.harvard.iq.dataverse.search.SearchException; import edu.harvard.iq.dataverse.search.SolrIndexServiceBean; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObjectBuilder; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("search") public class Search extends AbstractApiBean { private static final Logger logger = Logger.getLogger(Search.class.getCanonicalName()); @EJB SearchServiceBean searchService; @EJB DataverseServiceBean dataverseService; @EJB DvObjectServiceBean dvObjectService; @EJB SolrIndexServiceBean SolrIndexService; @GET public Response search(@QueryParam("key") String apiToken, @QueryParam("q") String query, @QueryParam("fq") final List<String> filterQueries, @QueryParam("sort") String sortField, @QueryParam("order") String sortOrder, @QueryParam("start") final int paginationStart, @QueryParam("showrelevance") boolean showRelevance) { if (query != null) { if (sortField == null) { // predictable default sortField = SearchFields.RELEVANCE; } if (sortOrder == null) { sortOrder = "desc"; // descending for Relevance } SolrQueryResponse solrQueryResponse; try { User dataverseUser = null; if (apiToken != null) { dataverseUser = findUserByApiToken(apiToken); if (dataverseUser == null) { String message = "Unable to find a user with API token provided."; return errorResponse(Response.Status.FORBIDDEN, message); } } boolean dataRelatedToMe = false; int numResultsPerPage = 10; solrQueryResponse = searchService.search(dataverseUser, dataverseService.findRootDataverse(), query, filterQueries, sortField, sortOrder, paginationStart, dataRelatedToMe, numResultsPerPage); } catch (SearchException ex) { Throwable cause = ex; StringBuilder sb = new StringBuilder(); sb.append(cause + " "); while (cause.getCause() != null) { cause = cause.getCause(); sb.append(cause.getClass().getCanonicalName() + " "); sb.append(cause + " "); // if you search for a colon you see RemoteSolrException: org.apache.solr.search.SyntaxError: Cannot parse ':' } String message = "Exception running search for [" + query + "] with filterQueries " + filterQueries + " and paginationStart [" + paginationStart + "]: " + sb.toString(); logger.info(message); return errorResponse(Response.Status.INTERNAL_SERVER_ERROR, message); } JsonArrayBuilder itemsArrayBuilder = Json.createArrayBuilder(); JsonArrayBuilder relevancePerResult = Json.createArrayBuilder(); List<SolrSearchResult> solrSearchResults = solrQueryResponse.getSolrSearchResults(); for (SolrSearchResult solrSearchResult : solrSearchResults) { itemsArrayBuilder.add(solrSearchResult.toJsonObject()); relevancePerResult.add(solrSearchResult.getRelevance()); } JsonObjectBuilder spelling_alternatives = Json.createObjectBuilder(); for (Map.Entry<String, List<String>> entry : solrQueryResponse.getSpellingSuggestionsByToken().entrySet()) { spelling_alternatives.add(entry.getKey(), entry.getValue().toString()); } JsonArrayBuilder facets = Json.createArrayBuilder(); JsonObjectBuilder facetCategoryBuilder = Json.createObjectBuilder(); for (FacetCategory facetCategory : solrQueryResponse.getFacetCategoryList()) { JsonObjectBuilder facetCategoryBuilderFriendlyPlusData = Json.createObjectBuilder(); JsonArrayBuilder facetLabelBuilderData = Json.createArrayBuilder(); for (FacetLabel facetLabel : facetCategory.getFacetLabel()) { JsonObjectBuilder countBuilder = Json.createObjectBuilder(); countBuilder.add(facetLabel.getName(), facetLabel.getCount()); facetLabelBuilderData.add(countBuilder); } facetCategoryBuilderFriendlyPlusData.add("friendly", facetCategory.getFriendlyName()); facetCategoryBuilderFriendlyPlusData.add("labels", facetLabelBuilderData); facetCategoryBuilder.add(facetCategory.getName(), facetCategoryBuilderFriendlyPlusData); } facets.add(facetCategoryBuilder); Map<String, String> datasetfieldFriendlyNamesBySolrField = solrQueryResponse.getDatasetfieldFriendlyNamesBySolrField(); // logger.info("the hash: " + datasetfieldFriendlyNamesBySolrField); for (Map.Entry<String, String> entry : datasetfieldFriendlyNamesBySolrField.entrySet()) { String string = entry.getKey(); String string1 = entry.getValue(); // logger.info(string + ":" + string1); } List filterQueriesActual = solrQueryResponse.getFilterQueriesActual(); JsonObjectBuilder value = Json.createObjectBuilder() .add("q", query) .add("fq_provided", filterQueries.toString()) .add("fq_actual", filterQueriesActual.toString()) .add("total_count", solrQueryResponse.getNumResultsFound()) .add("start", solrQueryResponse.getResultsStart()) .add("count_in_response", solrSearchResults.size()) .add("items", solrSearchResults.toString()); if (showRelevance) { value.add("relevance", relevancePerResult.build()); } if (false) { /* * @todo: add booleans to enable these * You can use SettingsServiceBeans for this */ value.add("spelling_alternatives", spelling_alternatives); value.add("facets", facets); } if (solrQueryResponse.getError() != null) { /** * @todo You get here if you pass only ":" as a query, for * example. Should we return more or better information? */ return errorResponse(Response.Status.BAD_REQUEST, solrQueryResponse.getError()); } return okResponse(value); } else { return errorResponse(Response.Status.BAD_REQUEST, "q parameter is missing"); } } /** * This method is for integration tests of search and should be disabled * with the boolean within it before release. */ @GET @Path("test") public Response searchDebug( @QueryParam("key") String apiToken, @QueryParam("q") String query, @QueryParam("fq") final List<String> filterQueries) { boolean searchTestMethodDisabled = false; if (searchTestMethodDisabled) { return errorResponse(Response.Status.BAD_REQUEST, "disabled"); } User user = findUserByApiToken(apiToken); if (user == null) { return errorResponse(Response.Status.UNAUTHORIZED, "Invalid apikey '" + apiToken + "'"); } Dataverse subtreeScope = dataverseService.findRootDataverse(); String sortField = SearchFields.ID; String sortOrder = "asc"; int paginationStart = 0; boolean dataRelatedToMe = false; int numResultsPerPage = Integer.MAX_VALUE; SolrQueryResponse solrQueryResponse; try { solrQueryResponse = searchService.search(user, subtreeScope, query, filterQueries, sortField, sortOrder, paginationStart, dataRelatedToMe, numResultsPerPage); } catch (SearchException ex) { return errorResponse(Response.Status.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage() + ": " + ex.getCause().getLocalizedMessage()); } JsonArrayBuilder itemsArrayBuilder = Json.createArrayBuilder(); List<SolrSearchResult> solrSearchResults = solrQueryResponse.getSolrSearchResults(); for (SolrSearchResult solrSearchResult : solrSearchResults) { itemsArrayBuilder.add(solrSearchResult.getType() + ":" + solrSearchResult.getNameSort()); } return okResponse(itemsArrayBuilder); } /** * This method is for integration tests of search and should be disabled * with the boolean within it before release. */ @GET @Path("perms") public Response searchPerms( @QueryParam("key") String apiToken, @QueryParam("id") Long dvObjectId) { boolean searchTestMethodDisabled = false; if (searchTestMethodDisabled) { return errorResponse(Response.Status.BAD_REQUEST, "disabled"); } User user = findUserByApiToken(apiToken); if (user == null) { return errorResponse(Response.Status.UNAUTHORIZED, "Invalid apikey '" + apiToken + "'"); } List<DvObjectSolrDoc> solrDocs = SolrIndexService.determineSolrDocs(dvObjectId); JsonObjectBuilder data = Json.createObjectBuilder(); JsonArrayBuilder permissionsData = Json.createArrayBuilder(); for (DvObjectSolrDoc solrDoc : solrDocs) { JsonObjectBuilder dataDoc = Json.createObjectBuilder(); dataDoc.add(SearchFields.ID, solrDoc.getSolrId()); dataDoc.add(SearchFields.NAME_SORT, solrDoc.getNameOrTitle()); JsonArrayBuilder perms = Json.createArrayBuilder(); for (String perm : solrDoc.getPermissions()) { perms.add(perm); } permissionsData.add(dataDoc); } data.add("perms", permissionsData); DvObject dvObject = dvObjectService.findDvObject(dvObjectId); Set<RoleAssignment> roleAssignments = rolesSvc.rolesAssignments(dvObject); JsonArrayBuilder roleAssignmentsData = Json.createArrayBuilder(); for (RoleAssignment roleAssignment : roleAssignments) { roleAssignmentsData.add(roleAssignment.getRole() + " has been granted to " + roleAssignment.getAssigneeIdentifier() + " on " + roleAssignment.getDefinitionPoint()); } data.add("roleAssignments", roleAssignmentsData); return okResponse(data); } }
package edu.ucdenver.ccp.common.ftp; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.log4j.Logger; import edu.ucdenver.ccp.common.file.FileUtil; public class FTPUtil { private static final Logger logger = Logger.getLogger(FTPUtil.class); private static final int BUFFER_SIZE = 32768000; private static final String ANONYMOUS = "anonymous"; public static enum FileType { ASCII(FTPClient.ASCII_FILE_TYPE), BINARY(FTPClient.BINARY_FILE_TYPE); private final int type; public int type() { return type; } private FileType(int type) { this.type = type; } }; /** * Initializes a FTPClient * * @param ftpServer * @param ftpUsername * @param ftpPassword * @return * @throws SocketException * @throws IOException */ public static FTPClient initializeFtpClient(String ftpServer, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftpClient = connect(ftpServer, -1); return login(ftpServer, ftpUsername, ftpPassword, ftpClient); } /** * Initializes a FTPClient to a specific port * * @param ftpServer * @param port * @param ftpUsername * @param ftpPassword * @return * @throws SocketException * @throws IOException */ public static FTPClient initializeFtpClient(String ftpServer, int port, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftpClient = connect(ftpServer, port); return login(ftpServer, ftpUsername, ftpPassword, ftpClient); } public static FTPClient initializeFtpClient(String ftpServer) throws SocketException, IOException { FTPClient ftpClient = connect(ftpServer, -1); return login(ftpServer, ANONYMOUS, ANONYMOUS, ftpClient); } /** * Makes the FTP connection using the specified port. If port < 0, then the default port is * used. * * @param ftpServer * @param port * @return * @throws SocketException * @throws IOException */ private static FTPClient connect(String ftpServer, int port) throws SocketException, IOException { FTPClient ftpClient = new FTPClient(); if (port > 0) ftpClient.connect(ftpServer, port); else ftpClient.connect(ftpServer); return ftpClient; } /** * Logs into the specified ftp server using the given username and password pairing. * * @param ftpServer * @param ftpUsername * @param ftpPassword * @param ftpClient * @return * @throws IOException */ private static FTPClient login(String ftpServer, String ftpUsername, String ftpPassword, FTPClient ftpClient) throws IOException { ftpClient.login(ftpUsername, ftpPassword); checkFtpConnection(ftpClient, ftpServer, ftpUsername, ftpPassword); logger.info(String.format("Connected to FTP Server: %s.", ftpServer)); return ftpClient; } /** * Checks the FTPClient response code. If the connection was refused, then an IOException is * thrown. * * @param ftpServer * @param ftpUsername * @param ftpPassword * @param ftpClient * @throws IOException */ private static void checkFtpConnection(FTPClient ftpClient, String ftpServer, String ftpUsername, String ftpPassword) throws IOException { if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { closeFtpClient(ftpClient); throw new IOException(String.format("FTP server (%s) refused connection for user:%s password:%s", ftpServer, ftpUsername, ftpPassword)); } } /** * Attempts to close the FTPClient * * @param ftpClient * @throws IOException */ public static void closeFtpClient(FTPClient ftpClient) throws IOException { logger.info("Closing FTP connection."); if (ftpClient != null) { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } } public static File downloadFile(String ftpServer, int port, String remotePath, String fileName, FileType fileType, File workDirectory, String username, String password) throws IOException { FTPClient ftpClient = FTPUtil.initializeFtpClient(ftpServer, port, username, password); FTPUtil.navigateToFtpDirectory(ftpClient, remotePath); File downloadedFile = FTPUtil.downloadFile(ftpClient, fileName, fileType, workDirectory); FTPUtil.closeFtpClient(ftpClient); return downloadedFile; } public static File downloadFile(String ftpServer, String remotePath, String fileName, FileType fileType, File workDirectory) throws IOException { FTPClient ftpClient = FTPUtil.initializeFtpClient(ftpServer, -1, "anonymous", "anonymous"); FTPUtil.navigateToFtpDirectory(ftpClient, remotePath); File downloadedFile = FTPUtil.downloadFile(ftpClient, fileName, fileType, workDirectory); FTPUtil.closeFtpClient(ftpClient); return downloadedFile; } /** * Downloads a file by name from the connected FTP server to the local storage directory. * * @param ftpClient * @param ftpFileName * @param localStorageDirectory * @throws FileNotFoundException * @throws IOException */ public static File downloadFile(FTPClient ftpClient, String ftpFileName, FTPUtil.FileType ftpFileType, File localStorageDirectory) throws FileNotFoundException, IOException { OutputStream localOutputStream = null; File outputFile = FileUtil.appendPathElementsToDirectory(localStorageDirectory, ftpFileName); try { localOutputStream = new FileOutputStream(outputFile); downloadFile(ftpClient, ftpFileName, ftpFileType, localOutputStream); return outputFile; } finally { if (localOutputStream != null) { localOutputStream.close(); } } } /** * Downloads a file by name from the connection FTP server to the OutputStream * * @param ftpClient * @param ftpFileName * @param ftpFileType * @param localOutputStream * @throws IOException */ public static void downloadFile(FTPClient ftpClient, String ftpFileName, FTPUtil.FileType ftpFileType, OutputStream localOutputStream) throws IOException { checkFtpClientConnection(ftpClient); logger.info(String.format("Downloading file: %s", ftpFileName)); ftpClient.setFileType(ftpFileType.type()); ftpClient.enterLocalPassiveMode(); ftpClient.setBufferSize(BUFFER_SIZE); if (!ftpClient.retrieveFile(ftpFileName, localOutputStream)) { throw new IOException(String.format("Download failed for file: %s", ftpFileName)); } } /** * Checks that the FTPClient is connected. If it isn't, an IOException is thrown. * * @param ftpClient * @param ftpFileName * @throws IOException */ private static void checkFtpClientConnection(FTPClient ftpClient) throws IOException { if (!ftpClient.isConnected()) { throw new IOException(String.format("FTP connection expected open, but is closed.")); } } /** * Changes the directory of the FTPClient on the FTP server * * @param ftpClient * @param directoryOnFtpServer * @throws IOException */ public static void navigateToFtpDirectory(FTPClient ftpClient, String directoryOnFtpServer) throws IOException { logger.info(String.format("Changing to new directory on server: %s", directoryOnFtpServer)); ftpClient.changeWorkingDirectory(directoryOnFtpServer); } /** * Downloads all available files from the current FTP directory. * * @param ftpClient * @param fileType * @param localStorageDirectory * @throws IOException */ public static void downloadAllFiles(FTPClient ftpClient, String fileSuffix, FTPUtil.FileType fileType, File localStorageDirectory) throws IOException { downloadAllFiles(ftpClient, new HashSet<String>(), fileSuffix, fileType, localStorageDirectory); } /** * Downloads all available files from the current FTP directory. If a file suffix is specified, * only files with that suffix are considered for download. Files with names in the * fileNamesToLeaveOnServer set are not downloaded. * * @param ftpClient * @param fileNamesToLeaveOnServer * @param fileSuffix * @param fileType * @param localStorageDirectory * @throws IOException */ public static Collection<File> downloadAllFiles(FTPClient ftpClient, Set<String> fileNamesToLeaveOnServer, String fileSuffix, FTPUtil.FileType fileType, File localStorageDirectory) throws IOException { checkFtpClientConnection(ftpClient); Collection<File> downloadedFiles = new ArrayList<File>(); List<FTPFile> filesAvailableForDownload = getFilesAvailableForDownload(ftpClient, fileSuffix); for (FTPFile fileOnFtpServer : filesAvailableForDownload) { if (!fileNamesToLeaveOnServer.contains(fileOnFtpServer.getName())) { downloadedFiles .add(downloadFile(ftpClient, fileOnFtpServer.getName(), fileType, localStorageDirectory)); } } return downloadedFiles; } /** * Downloads all files that are on the FTP server that are not already stored locally in the * specified localStorageDirectory. * * @param ftpClient * @param fileNamesToLeaveOnServer * @param fileSuffix * @param fileType * @param localStorageDirectory * @throws IOException */ public static Collection<File> downloadMissingFiles(FTPClient ftpClient, String fileSuffix, FTPUtil.FileType fileType, File localStorageDirectory) throws IOException { Set<String> locallyStoredFileNames = new HashSet<String>(Arrays.asList(localStorageDirectory.list())); return downloadAllFiles(ftpClient, locallyStoredFileNames, fileSuffix, fileType, localStorageDirectory); } /** * Downloads any file that is not already present in the specified local directory from the * specified FTP server * * @param localStorageDirectory * @param fileSuffix * @param fileType * @param ftpServer * @param ftpUsername * @param ftpPassword * @throws SocketException * @throws IOException */ public static Collection<File> syncLocalDirectoryWithFtpDirectory(FTPClient ftpClient, File localStorageDirectory, String fileSuffix, FileType fileType) throws SocketException, IOException { FileUtil.validateDirectory(localStorageDirectory); return FTPUtil.downloadMissingFiles(ftpClient, fileSuffix, fileType, localStorageDirectory); } /** * Returns the list of files available for download in the current FTP directory. If fileSuffix * is null, all files are returned. Otherwise files that have the specified suffix are returned. * * @param ftpClient * @param fileSuffix * @return * @throws IOException */ private static List<FTPFile> getFilesAvailableForDownload(FTPClient ftpClient, String fileSuffix) throws IOException { if (fileSuffix == null) { return Arrays.asList(ftpClient.listFiles()); } else { return Arrays.asList(ftpClient.listFiles(String.format("*%s", fileSuffix))); } } /** * Pauses the current thread for n seconds depending on the input. This can be useful if a web * resource limits how often you can retrieve files. * * @param seconds */ public static void pause(int seconds) { try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
package org.ovirt.engine.ui.uicommonweb.models.configure.instancetypes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.ovirt.engine.core.common.action.AddVmTemplateParameters; import org.ovirt.engine.core.common.action.UpdateVmTemplateParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VmTemplateParametersBase; import org.ovirt.engine.core.common.businessentities.GraphicsDevice; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.InstanceType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmEntityType; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmWatchdog; import org.ovirt.engine.core.common.businessentities.VmWatchdogType; import org.ovirt.engine.core.common.interfaces.SearchType; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.SearchParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.ObjectUtils; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Cloner; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.builders.BuilderExecutor; import org.ovirt.engine.ui.uicommonweb.builders.vm.HwOnlyCoreUnitToVmBaseBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.MigrationOptionsUnitToVmBaseBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.NameUnitToVmBaseBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.UsbPolicyUnitToVmBaseBuilder; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.help.HelpTag; import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel; import org.ovirt.engine.ui.uicommonweb.models.vms.BaseInterfaceCreatingManager; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModelNetworkAsyncCallback; import org.ovirt.engine.ui.uicommonweb.models.vms.VmBasedWidgetSwitchModeCommand; import org.ovirt.engine.ui.uicommonweb.models.vms.VmModelBehaviorBase; import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.ExistingInstanceTypeModelBehavior; import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.InstanceTypeInterfaceCreatingManager; import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.NewInstanceTypeModelBehavior; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; import com.google.inject.Inject; public class InstanceTypeListModel extends ListWithDetailsModel { private final UICommand newInstanceTypeCommand; private final UICommand editInstanceTypeCommand; private final UICommand deleteInstanceTypeCommand; private final InstanceTypeInterfaceCreatingManager addInstanceTypeNetworkManager = new InstanceTypeInterfaceCreatingManager(new BaseInterfaceCreatingManager.PostVnicCreatedCallback() { @Override public void vnicCreated(Guid vmId) { getWindow().stopProgress(); cancel(); updateActionAvailability(); } @Override public void queryFailed() { getWindow().stopProgress(); cancel(); } }); @Inject public InstanceTypeListModel(final InstanceTypeGeneralModel instanceTypeGeneralModel) { setDetailList(instanceTypeGeneralModel); setDefaultSearchString("Instancetypes:"); //$NON-NLS-1$ setSearchString(getDefaultSearchString()); this.newInstanceTypeCommand = new UICommand("NewInstanceType", this); //$NON-NLS-1$ this.editInstanceTypeCommand = new UICommand("EditInstanceType", this); //$NON-NLS-1$ this.deleteInstanceTypeCommand = new UICommand("DeleteInstanceType", this); //$NON-NLS-1$ setSearchPageSize(1000); updateActionAvailability(); } private void setDetailList(final InstanceTypeGeneralModel instanceTypeGeneralModel) { List<EntityModel> list = new ArrayList<EntityModel>(); list.add(instanceTypeGeneralModel); setDetailModels(list); } @Override protected void syncSearch() { SearchParameters params = new SearchParameters(getSearchString(), SearchType.InstanceType, isCaseSensitiveSearch()); params.setMaxCount(getSearchPageSize()); super.syncSearch(VdcQueryType.Search, params); } private void newInstanceType() { createWindow( new NewInstanceTypeModelBehavior(), "new_instance_type", //$NON-NLS-1$ "OnNewInstanceType", //$NON-NLS-1$ true, ConstantsManager.getInstance().getConstants().newInstanceTypeTitle(), HelpTag.new_instance_type ); } private void editInstanceType() { createWindow( new ExistingInstanceTypeModelBehavior((InstanceType) getSelectedItem()), "edit_instance_type", //$NON-NLS-1$ "OnEditInstanceType", //$NON-NLS-1$ false, ConstantsManager.getInstance().getConstants().editInstanceTypeTitle(), HelpTag.edit_instance_type ); } private void deleteInstanceType() { if (getWindow() != null) { return; } final ConfirmationModel window = new ConfirmationModel(); setConfirmWindow(window); window.startProgress(null); window.setHelpTag(HelpTag.remove_instance_type); window.setHashName("remove_instance_type"); //$NON-NLS-1$ final Guid instanceTypeId = ((InstanceType) getSelectedItem()).getId(); Frontend.getInstance().runQuery(VdcQueryType.GetVmsByInstanceTypeId, new IdQueryParameters(instanceTypeId), new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object parentModel, Object returnValue) { List<VM> vmsAttachedToInstanceType = ((VdcQueryReturnValue) returnValue).getReturnValue(); if (vmsAttachedToInstanceType == null || vmsAttachedToInstanceType.size() == 0) { window.setTitle(ConstantsManager.getInstance().getConstants().removeInstanceTypeTitle()); window.setItems(Arrays.asList(((InstanceType) getSelectedItem()).getName())); } else { List<String> attachedVmsNames = new ArrayList<String>(); for (VM vm : vmsAttachedToInstanceType) { attachedVmsNames.add(vm.getName()); } Collections.sort(attachedVmsNames); window.setItems(attachedVmsNames); window.getLatch().setIsAvailable(true); window.getLatch().setIsChangable(true); window.setNote(ConstantsManager.getInstance().getConstants().vmsAttachedToInstanceTypeNote()); window.setMessage(ConstantsManager.getInstance().getConstants().vmsAttachedToInstanceTypeWarningMessage()); } window.stopProgress(); } })); UICommand tempVar = new UICommand("OnDeleteInstanceType", this); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); window.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); window.getCommands().add(tempVar2); } private void onNewInstanceType() { if (!((UnitVmModel) getWindow()).validateHwPart()) { return; } AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { boolean isNameUnique = (Boolean) returnValue; if (isNameUnique) { postInstanceTypeNameUniqueCheck(); } else { UnitVmModel VmModel = (UnitVmModel) getWindow(); VmModel.getInvalidityReasons().clear(); VmModel.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); VmModel.getName().setIsValid(false); VmModel.setIsValid(false); } } }), ((UnitVmModel) getWindow()).getName().getEntity()); } private void buildVmStatic(VmBase vmBase) { UnitVmModel model = (UnitVmModel) getWindow(); BuilderExecutor.build(model, vmBase, new HwOnlyCoreUnitToVmBaseBuilder(), new NameUnitToVmBaseBuilder(), new UsbPolicyUnitToVmBaseBuilder(), new MigrationOptionsUnitToVmBaseBuilder() ); // from CommonUnitToVmBaseBuilder vmBase.setAutoStartup(model.getIsHighlyAvailable().getEntity()); vmBase.setPriority(model.getPriority().getSelectedItem().getEntity()); } private void postInstanceTypeNameUniqueCheck() { UnitVmModel model = (UnitVmModel) getWindow(); VM vm = new VM(); buildVmStatic(vm.getStaticData()); vm.setVmDescription(model.getDescription().getEntity()); AddVmTemplateParameters addInstanceTypeParameters = new AddVmTemplateParameters(vm, model.getName().getEntity(), model.getDescription().getEntity()); addInstanceTypeParameters.setTemplateType(VmEntityType.INSTANCE_TYPE); addInstanceTypeParameters.setVmTemplateId(null); addInstanceTypeParameters.setPublicUse(true); addInstanceTypeParameters.setSoundDeviceEnabled(model.getIsSoundcardEnabled().getEntity()); addInstanceTypeParameters.setConsoleEnabled(model.getIsConsoleDeviceEnabled().getEntity()); addInstanceTypeParameters.setBalloonEnabled(model.getMemoryBalloonDeviceEnabled().getEntity()); addInstanceTypeParameters.setVirtioScsiEnabled(model.getIsVirtioScsiEnabled().getEntity()); setVmWatchdogToParams(model, addInstanceTypeParameters); setRngDeviceToParams(model, addInstanceTypeParameters); setGraphicsDevicesToParams(model, addInstanceTypeParameters); getWindow().startProgress(null); Frontend.getInstance().runAction( VdcActionType.AddVmTemplate, addInstanceTypeParameters, new UnitVmModelNetworkAsyncCallback(model, addInstanceTypeNetworkManager), this ); } private void onEditInstanceType() { UnitVmModel model = (UnitVmModel) getWindow(); if (!model.validateHwPart()) { return; } VmTemplate instanceType = (VmTemplate) Cloner.clone(selectedItem); instanceType.setTemplateType(VmEntityType.INSTANCE_TYPE); buildVmStatic(instanceType); instanceType.setDescription(model.getDescription().getEntity()); UpdateVmTemplateParameters updateInstanceTypeParameters = new UpdateVmTemplateParameters(instanceType); updateInstanceTypeParameters.setSoundDeviceEnabled(model.getIsSoundcardEnabled().getEntity()); updateInstanceTypeParameters.setConsoleEnabled(model.getIsConsoleDeviceEnabled().getEntity()); updateInstanceTypeParameters.setBalloonEnabled(model.getMemoryBalloonDeviceEnabled().getEntity()); updateInstanceTypeParameters.setVirtioScsiEnabled(model.getIsVirtioScsiEnabled().getEntity()); setVmWatchdogToParams(model, updateInstanceTypeParameters); setRngDeviceToParams(model, updateInstanceTypeParameters); setGraphicsDevicesToParams(model, updateInstanceTypeParameters); getWindow().startProgress(null); Frontend.getInstance().runAction( VdcActionType.UpdateVmTemplate, updateInstanceTypeParameters, new UnitVmModelNetworkAsyncCallback(model, addInstanceTypeNetworkManager, instanceType.getId()), this ); } private void onDeleteInstanceType() { final ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); boolean latchChecked = !model.validate(); if (model.getProgress() != null || latchChecked) { return; } model.startProgress(null); Guid instanceTypeId = ((InstanceType) getSelectedItem()).getId(); Frontend.getInstance().runAction(VdcActionType.RemoveVmTemplate, new VmTemplateParametersBase(instanceTypeId), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { model.stopProgress(); cancel(); } }, this); } private void createWindow(VmModelBehaviorBase<UnitVmModel> behavior, String hashName, String onOkAction, boolean isNew, String title, HelpTag helpTag) { if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(behavior); model.setIsAdvancedModeLocalStorageKey("instance_type_dialog"); //$NON-NLS-1$ setWindow(model); model.setTitle(title); model.setHelpTag(helpTag); model.setHashName(hashName); //$NON-NLS-1$ model.setIsNew(isNew); model.initialize(null); VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand(); switchModeCommand.init(model); model.getCommands().add(switchModeCommand); UICommand newTemplate = new UICommand(onOkAction, this); //$NON-NLS-1$ newTemplate.setTitle(ConstantsManager.getInstance().getConstants().ok()); newTemplate.setIsDefault(true); model.getCommands().add(newTemplate); UICommand cancel = new UICommand("Cancel", this); //$NON-NLS-1$ cancel.setTitle(ConstantsManager.getInstance().getConstants().cancel()); cancel.setIsCancel(true); model.getCommands().add(cancel); } private void cancel() { setWindow(null); setConfirmWindow(null); } protected void updateActionAvailability() { int numOfSelectedItems = getSelectedItems() != null ? getSelectedItems().size() : 0; getEditInstanceTypeCommand().setIsExecutionAllowed(numOfSelectedItems == 1); getDeleteInstanceTypeCommand().setIsExecutionAllowed(numOfSelectedItems == 1); } @Override protected void selectedItemsChanged() { super.selectedItemsChanged(); updateActionAvailability(); } @Override protected String getListName() { return "InstanceTypeListModel"; //$NON-NLS-1$ } @Override public void executeCommand(UICommand command) { super.executeCommand(command); if (command == getNewInstanceTypeCommand()) { newInstanceType(); } else if (ObjectUtils.objectsEqual(command.getName(), "OnNewInstanceType")) { //$NON-NLS-1$ onNewInstanceType(); } else if (command == getEditInstanceTypeCommand()) { editInstanceType(); } else if (ObjectUtils.objectsEqual(command.getName(), "OnEditInstanceType")) { //$NON-NLS-1$ onEditInstanceType(); } else if (command == getDeleteInstanceTypeCommand()) { deleteInstanceType(); } else if (ObjectUtils.objectsEqual(command.getName(), "OnDeleteInstanceType")) { //$NON-NLS-1$ onDeleteInstanceType(); } else if (ObjectUtils.objectsEqual(command.getName(), "Cancel")) { //$NON-NLS-1$ cancel(); } } private void setVmWatchdogToParams(final UnitVmModel model, VmTemplateParametersBase updateVmParams) { VmWatchdogType wdModel = model.getWatchdogModel().getSelectedItem(); updateVmParams.setUpdateWatchdog(true); if (wdModel != null) { VmWatchdog vmWatchdog = new VmWatchdog(); vmWatchdog.setAction(model.getWatchdogAction().getSelectedItem()); vmWatchdog.setModel(wdModel); updateVmParams.setWatchdog(vmWatchdog); } } private void setRngDeviceToParams(UnitVmModel model, VmTemplateParametersBase parameters) { parameters.setUpdateRngDevice(true); parameters.setRngDevice(model.getIsRngEnabled().getEntity() ? model.generateRngDevice() : null); } private void setGraphicsDevicesToParams(final UnitVmModel model, VmTemplateParametersBase params) { if (model.getDisplayType().getSelectedItem() == null || model.getGraphicsType().getSelectedItem() == null) { return; } for (GraphicsType graphicsType : GraphicsType.values()) { params.getGraphicsDevices().put(graphicsType, null); // reset if (model.getGraphicsType().getSelectedItem().getBackingGraphicsType().contains(graphicsType)) { GraphicsDevice d = new GraphicsDevice(graphicsType.getCorrespondingDeviceType()); params.getGraphicsDevices().put(d.getGraphicsType(), d); } } } @Override public UICommand getEditCommand() { return getEditInstanceTypeCommand(); } public UICommand getNewInstanceTypeCommand() { return newInstanceTypeCommand; } public UICommand getEditInstanceTypeCommand() { return editInstanceTypeCommand; } public UICommand getDeleteInstanceTypeCommand() { return deleteInstanceTypeCommand; } }
/** * The GUI that has the Grocery List and allows exporting of the list. * * @author Julia McClellan, Luke Giacalone, Hyun Choi * @version 05/15/2016 */ import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; import java.util.Scanner; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.plaf.nimbus.NimbusLookAndFeel; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import javax.naming.*; public class GroceryListGUI extends JFrame { private static final Dimension SCROLL_PANEL_SIZE = new Dimension(200, 300); private String pw; public GroceryListGUI(final List<Item> groceries) { super("Grocery List"); try { UIManager.setLookAndFeel(new NimbusLookAndFeel()); } catch (UnsupportedLookAndFeelException e) {} JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //adding scroll panel with grocery list c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.CENTER; Box box = Box.createVerticalBox(); for(Item i: groceries) box.add(new JLabel(i.getName() + " : " + i.amountToBuy())); JScrollPane scroll = new JScrollPane(box, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setPreferredSize(SCROLL_PANEL_SIZE); panel.add(scroll, c); //adding export button c.gridy++; JButton export = new JButton("Export"); export.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); //chooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Word Document (.docx)","docx")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("Plain Text Document (.txt)","txt")); int option = chooser.showSaveDialog(null); if(option == JFileChooser.APPROVE_OPTION) { PrintWriter writer = null; try { File file = chooser.getSelectedFile(); if(file.getName().lastIndexOf(".txt") != file.getName().length() - 4) { JOptionPane.showMessageDialog(null, "\".txt\" entension required!", "Error", JOptionPane.ERROR_MESSAGE); return; } file.createNewFile(); writer = new PrintWriter(file); for(Item i: groceries) writer.println(i.getName() + " : " + i.amountToBuy()); writer.close(); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Error in Saving", "Error", JOptionPane.ERROR_MESSAGE); return; } } } }); panel.add(export, c); //adding email button c.gridy++; JButton email = new JButton("Email"); email.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String emailAddr = (String) JOptionPane.showInputDialog(null, "Enter your email address:", "Email My Shopping List", JOptionPane.PLAIN_MESSAGE); if (!isValidEmail(emailAddr)) { throw new IllegalArgumentException(); } String list = "Your shopping list generated at "; list += new SimpleDateFormat("h:mm a 'on' MM/dd/yyyy").format(new java.util.Date()); list += ":\n"; for (Item i: groceries) { list += i.getName() + " : " + i.amountToBuy() + "\n"; } if (!sendEmail(emailAddr, list)) { //attempt to send the email here throw new RuntimeException(); } else { JOptionPane.showMessageDialog(null, "Email sent!", "Emailed list", JOptionPane.INFORMATION_MESSAGE); return; } } catch (RuntimeException e1) { //two different error messages for different cases JOptionPane.showMessageDialog(null, "Sending failed!", "Error", JOptionPane.ERROR_MESSAGE); return; } catch (Throwable e2) { JOptionPane.showMessageDialog(null, "Invalid email address!", "Error", JOptionPane.ERROR_MESSAGE); return; } } }); panel.add(email, c); this.add(panel); this.pack(); this.setResizable(false); this.setVisible(true); } //attempts to send an email, returns the success of such attempt private boolean sendEmail(String emailAddr, String list) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); File file = new File("email.compsci"); pw = ""; try { Scanner scan = new Scanner(file); pw = scan.nextLine(); } catch (Throwable e) { JOptionPane.showMessageDialog(null, "Sending failed!", "Error", JOptionPane.ERROR_MESSAGE); return false; } Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("MXShoppingList", pw); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("MXShoppingList@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddr)); message.setSubject("Your Shopping List"); message.setText(list); Transport.send(message); } catch (Throwable e) { return false; } return true; } //checks if a given string is a valid email address private boolean isValidEmail(String s) { try { InternetAddress email = new InternetAddress(s); email.validate(); } catch (Throwable e) { return false; } return true; } }
package org.springframework.ide.vscode.commons.boot.app.cli.livebean; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.ide.vscode.commons.util.Log; import org.springframework.ide.vscode.commons.util.StringUtil; import com.google.common.collect.ImmutableListMultimap; /** * @author Martin Lippert * @author Kris De Volder */ public class LiveBeansModel { private static final String[] NO_STRINGS = new String[] {}; public static class Builder { private final ImmutableListMultimap.Builder<String, LiveBean> beansViaName = ImmutableListMultimap.builder(); private final ImmutableListMultimap.Builder<String, LiveBean> beansViaType = ImmutableListMultimap.builder(); private final ImmutableListMultimap.Builder<String, LiveBean> beansViaDependency = ImmutableListMultimap.builder(); public LiveBeansModel build() { return new LiveBeansModel(beansViaName.build(), beansViaType.build(), beansViaDependency.build()); } public Builder add(LiveBean bean) { String type = bean.getType(); if (type != null) { beansViaType.put(type, bean); } String name = bean.getId(); if (name != null) { beansViaName.put(name, bean); } String[] deps = bean.getDependencies(); if (deps!=null) { for (String dep : deps) { beansViaDependency.put(dep, bean); } } return this; } } public static LiveBeansModel.Builder builder() { return new Builder(); } interface Parser { LiveBeansModel parse(String json) throws Exception; } private static class Boot15Parser implements Parser { @Override public LiveBeansModel parse(String json) throws Exception { Builder model = LiveBeansModel.builder(); JSONArray mainArray = new JSONArray(json); for (int i = 0; i < mainArray.length(); i++) { JSONObject appContext = mainArray.getJSONObject(i); if (appContext == null) continue; JSONArray beansArray = appContext.optJSONArray("beans"); if (beansArray == null) continue; for (int j = 0; j < beansArray.length(); j++) { JSONObject beanObject = beansArray.getJSONObject(j); if (beanObject == null) continue; LiveBean bean = parseBean(beanObject); if (bean != null) { model.add(bean); } } } return model.build(); } private LiveBean parseBean(JSONObject beansJSON) { String id = beansJSON.optString("bean"); String type = beansJSON.optString("type"); String scope = beansJSON.optString("scope"); String resource = beansJSON.optString("resource"); JSONArray aliasesJSON = beansJSON.optJSONArray("aliases"); String[] aliases; if (aliasesJSON!=null) { aliases = new String[aliasesJSON.length()]; for (int i = 0; i < aliasesJSON.length(); i++) { aliases[i] = aliasesJSON.optString(i); } } else { aliases = NO_STRINGS; } JSONArray dependenciesJSON = beansJSON.getJSONArray("dependencies"); String[] dependencies = new String[dependenciesJSON.length()]; for (int i = 0; i < dependenciesJSON.length(); i++) { dependencies[i] = dependenciesJSON.optString(i); } return new LiveBean(id, aliases, scope, type, resource, dependencies); } } private static class Boot20Parser implements Parser { @Override public LiveBeansModel parse(String json) throws Exception { Builder model = LiveBeansModel.builder(); JSONObject mainObject = new JSONObject(json); mainObject = mainObject.getJSONObject("contexts"); for (String contextId : mainObject.keySet()) { JSONObject contextObject = mainObject.getJSONObject(contextId); JSONObject beansObject = contextObject.getJSONObject("beans"); for (String id : beansObject.keySet()) { JSONObject beanObject = beansObject.getJSONObject(id); LiveBean bean = parseBean(id, contextId, beanObject); if (bean!=null) { model.add(bean); } } } return model.build(); } private LiveBean parseBean(String id, String contextId, JSONObject beansJSON) { String type = beansJSON.optString("type"); String scope = beansJSON.optString("scope"); String resource = beansJSON.optString("resource"); JSONArray aliasesJSON = beansJSON.optJSONArray("aliases"); String[] aliases; if (aliasesJSON==null) { aliases = NO_STRINGS; } else { aliases = new String[aliasesJSON.length()]; for (int i = 0; i < aliasesJSON.length(); i++) { aliases[i] = aliasesJSON.optString(i); } } JSONArray dependenciesJSON = beansJSON.optJSONArray("dependencies"); String[] dependencies; if (dependenciesJSON==null) { dependencies = NO_STRINGS; } else { dependencies = new String[dependenciesJSON.length()]; for (int i = 0; i < dependenciesJSON.length(); i++) { dependencies[i] = dependenciesJSON.optString(i); } } return new LiveBean(id, aliases, scope, type, resource, dependencies); } } private static final Parser[] PARSERS = { new Boot15Parser(), new Boot20Parser(), }; public static LiveBeansModel parse(String json) { List<Exception> exceptions = new ArrayList<>(PARSERS.length); if (StringUtil.hasText(json)) { for (Parser parser : PARSERS) { try { LiveBeansModel model = parser.parse(json); if (model==null) { throw new NullPointerException("Parser returned a null model (it should not!)"); } return model; //good! } catch (Exception e) { exceptions.add(e); } } } //Only getting here if none of the parsers worked... So if at least one parser works, // we won't log any exceptions. for (Exception e : exceptions) { Log.log(e); } return LiveBeansModel.builder().build(); // always return at least an empty model. } private final ImmutableListMultimap<String, LiveBean> beansViaType; private final ImmutableListMultimap<String, LiveBean> beansViaName; private final ImmutableListMultimap<String, LiveBean> beansViaDependency; protected LiveBeansModel( ImmutableListMultimap<String, LiveBean> beansViaName, ImmutableListMultimap<String, LiveBean> beansViaType, ImmutableListMultimap<String, LiveBean> beansViaDependency) { this.beansViaName = beansViaName; this.beansViaType = beansViaType; this.beansViaDependency = beansViaDependency; } public List<LiveBean> getBeansOfType(String fullyQualifiedType) { return beansViaType.get(fullyQualifiedType); } public List<LiveBean> getBeansOfName(String beanName) { return beansViaName.get(beanName); } public List<LiveBean> getBeansDependingOn(String beanName) { return beansViaDependency.get(beanName); } public boolean isEmpty() { return beansViaName.isEmpty(); //Assumes every bean has a name. } public Set<String> getBeanNames() { return beansViaName.keySet(); } }
package edu.usc.ini.pipeline.rest; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import org.jboss.logging.Logger; import edu.usc.ini.pipeline.rest.messages.ConnectMessage; import edu.usc.ini.pipeline.rest.messages.ConnectionEstablished; import edu.usc.ini.pipeline.rest.messages.ConnectionFailed; import edu.usc.ini.pipeline.rest.messages.GetSessionsMessage; import edu.usc.ini.pipeline.rest.messages.IncomingMessage; import edu.usc.ini.pipeline.rest.messages.Message; import edu.usc.ini.pipeline.rest.messages.OutcomingMessage; import edu.usc.ini.pipeline.rest.messages.SessionListMessage; import pipeline.api.PipelineAPI; import pipeline.api.callback.ConnectionCallback; import pipeline.api.callback.SessionListCallback; import pipeline.api.workflow.Connection; import pipeline.api.workflow.Session; public class ApiThread extends Thread implements ConnectionCallback, SessionListCallback { private static final Logger logger = Logger.getLogger(ApiThread.class); private PipelineAPI pipelineApi; private volatile boolean stoped = false; private LinkedBlockingQueue<IncomingMessage> innerQueue; private LinkedBlockingQueue<OutcomingMessage> outcommingQueue; public ApiThread() throws InterruptedException { pipelineApi = new PipelineAPI(); innerQueue = new LinkedBlockingQueue<>(); outcommingQueue = new LinkedBlockingQueue<>(); } public void shutdown() { stoped = true; } public void addMessage(IncomingMessage message) { logger.info("New message "+message.getClass()); try { outcommingQueue.clear(); innerQueue.put(message); } catch (InterruptedException e) { logger.error(e); } } public OutcomingMessage getMessage() { OutcomingMessage outMessage = null; try { outMessage = outcommingQueue.take(); } catch (InterruptedException e) { logger.error(e); } return outMessage; } private void handleMessage(Message message) { logger.info("handleMessage "+message); if (message instanceof ConnectMessage) { ConnectMessage connectMessage = (ConnectMessage) message; Connection connection = new Connection(connectMessage.getUsername(), connectMessage.getPassword(), connectMessage.getServer(), connectMessage.getPort()); logger.info("Call PipelineApi to connect "+connection); pipelineApi.connect(connection , this); } else if (message instanceof GetSessionsMessage) { GetSessionsMessage getSessionsMessage = (GetSessionsMessage) message; Connection connection = getSessionsMessage.getConnection(); pipelineApi.requestSessionList(connection , this); } } public void run() { while (!stoped) { Message message = innerQueue.poll(); if (message != null) { handleMessage(message); } } } private void addOutcommingMessage(OutcomingMessage outcomingMessage) { try { outcommingQueue.put(outcomingMessage); } catch (InterruptedException e) { logger.error(e); } } @Override public void onConnectionEstablished(Connection connection) { logger.info("Connection established"); addOutcommingMessage(new ConnectionEstablished()); } @Override public void onConnectionFailed(Connection connection, String error) { logger.info("Connection failed. "+error); addOutcommingMessage(new ConnectionFailed(error)); } @Override public void onSessionList(List<Session> sessions) { logger.info("Got sessions list "+sessions.size()); addOutcommingMessage(new SessionListMessage(sessions)); } }
package org.innovateuk.ifs.management.competition.setup; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.category.resource.InnovationAreaResource; import org.innovateuk.ifs.category.resource.InnovationSectorResource; import org.innovateuk.ifs.category.service.CategoryRestService; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.competition.publiccontent.resource.FundingType; import org.innovateuk.ifs.competition.resource.*; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.innovateuk.ifs.competition.service.CompetitionSetupRestService; import org.innovateuk.ifs.competition.service.TermsAndConditionsRestService; import org.innovateuk.ifs.management.competition.setup.applicationsubmission.form.ApplicationSubmissionForm; import org.innovateuk.ifs.management.competition.setup.completionstage.form.CompletionStageForm; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupSummaryForm; import org.innovateuk.ifs.management.competition.setup.core.populator.CompetitionSetupFormPopulator; import org.innovateuk.ifs.management.competition.setup.core.service.CompetitionSetupService; import org.innovateuk.ifs.management.competition.setup.fundinginformation.form.AdditionalInfoForm; import org.innovateuk.ifs.management.competition.setup.initialdetail.form.InitialDetailsForm; import org.innovateuk.ifs.management.competition.setup.initialdetail.populator.ManageInnovationLeadsModelPopulator; import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestonesForm; import org.innovateuk.ifs.management.fixtures.CompetitionFundersFixture; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.UserRestService; import org.innovateuk.ifs.user.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.HttpStatus; import org.springframework.test.web.servlet.MvcResult; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.category.builder.InnovationAreaResourceBuilder.newInnovationAreaResource; import static org.innovateuk.ifs.category.builder.InnovationSectorResourceBuilder.newInnovationSectorResource; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_DUPLICATE_FUNDERS; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.innovateuk.ifs.competition.builder.CompetitionTypeResourceBuilder.newCompetitionTypeResource; import static org.innovateuk.ifs.competition.resource.ApplicationFinanceType.STANDARD; import static org.innovateuk.ifs.management.competition.setup.CompetitionSetupController.*; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.COMP_ADMIN; import static org.innovateuk.ifs.user.resource.Role.INNOVATION_LEAD; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Class for testing public functions of {@link CompetitionSetupController} */ @RunWith(MockitoJUnitRunner.Silent.class) public class CompetitionSetupControllerTest extends BaseControllerMockMVCTest<CompetitionSetupController> { private static final Long COMPETITION_ID = 12L; private static final String URL_PREFIX = "/competition/setup"; @Mock private CategoryRestService categoryRestService; @Mock private CompetitionSetupService competitionSetupService; @Mock private CompetitionSetupRestService competitionSetupRestService; @Mock private Validator validator; @Mock private ManageInnovationLeadsModelPopulator manageInnovationLeadsModelPopulator; @Mock private UserService userService; @Mock private UserRestService userRestService; @Mock private CompetitionRestService competitionRestService; @Mock private TermsAndConditionsRestService termsAndConditionsRestService; @Override protected CompetitionSetupController supplyControllerUnderTest() { return new CompetitionSetupController(); } @Before public void setUp() { when(userRestService.findByUserRole(COMP_ADMIN)) .thenReturn( restSuccess(newUserResource() .withFirstName("Comp") .withLastName("Admin") .build(1)) ); when(userRestService.findByUserRole(INNOVATION_LEAD)) .thenReturn( restSuccess(newUserResource() .withFirstName("Comp") .withLastName("Technologist") .build(1)) ); List<InnovationSectorResource> innovationSectorResources = newInnovationSectorResource() .withName("A Innovation Sector") .withId(1L) .build(1); when(categoryRestService.getInnovationSectors()).thenReturn(restSuccess(innovationSectorResources)); List<InnovationAreaResource> innovationAreaResources = newInnovationAreaResource() .withName("A Innovation Area") .withId(2L) .withSector(1L) .build(1); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); List<CompetitionTypeResource> competitionTypeResources = newCompetitionTypeResource() .withId(1L) .withName("Programme") .withCompetitions(singletonList(COMPETITION_ID)) .build(1); when(competitionRestService.getCompetitionTypes()).thenReturn(restSuccess(competitionTypeResources)); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(true); } @Test public void initCompetitionSetupSection() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(FALSE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute(SETUP_READY_KEY, FALSE)) .andExpect(model().attribute(READY_TO_OPEN_KEY, FALSE)); } @Test public void initCompetitionSetupSectionSetupComplete() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute(SETUP_READY_KEY, TRUE)) .andExpect(model().attribute(READY_TO_OPEN_KEY, FALSE)); } @Test public void initCompetitionSetupSectionReadyToOpen() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.READY_TO_OPEN).build(); when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(FALSE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute(SETUP_READY_KEY, FALSE)) .andExpect(model().attribute(READY_TO_OPEN_KEY, TRUE)); } @Test public void editCompetitionSetupSectionInitial() throws Exception { InitialDetailsForm competitionSetupInitialDetailsForm = new InitialDetailsForm(); competitionSetupInitialDetailsForm.setTitle("Test competition"); competitionSetupInitialDetailsForm.setCompetitionTypeId(2L); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withName("Test competition") .withCompetitionCode("Code") .withCompetitionType(2L) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); CompetitionSetupForm compSetupForm = mock(CompetitionSetupForm.class); CompetitionSetupFormPopulator compSetupFormPopulator = mock(CompetitionSetupFormPopulator.class); when(competitionSetupService.getSectionFormPopulator(CompetitionSetupSection.INITIAL_DETAILS)) .thenReturn(compSetupFormPopulator); when(compSetupFormPopulator.populateForm(competition)).thenReturn(compSetupForm); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute("competitionSetupForm", compSetupForm)); verify(competitionSetupService).populateCompetitionSectionModelAttributes( eq(competition), any(), eq(CompetitionSetupSection.INITIAL_DETAILS) ); } @Test public void setSectionAsIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).withName( "Test competition").withCompetitionCode("Code").withCompetitionType(2L).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(anyLong(), any(CompetitionSetupSection.class))).thenReturn(restSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")); } @Test public void generateCompetitionCode() throws Exception { ZonedDateTime time = ZonedDateTime.of(2016, 12, 1, 0, 0, 0, 0, ZoneId.systemDefault()); CompetitionResource competition = newCompetitionResource() .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withName("Test competition") .withCompetitionCode("Code") .withCompetitionType(2L) .withStartDate(time) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.generateCompetitionCode(COMPETITION_ID, time)) .thenReturn(restSuccess("1612-1")); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID + "/generateCompetitionCode?day=01&month=12&year=2016")) .andExpect(status().isOk()) .andExpect(jsonPath("message", is("1612-1"))); } @Test public void submitUnrestrictedSectionInitialDetailsInvalidWithRequiredFieldsEmpty() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("unrestricted", "1")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors( COMPETITION_SETUP_FORM_KEY, "executiveUserId", "title", "innovationLeadUserId", "openingDate", "innovationSectorCategoryId", "innovationAreaCategoryIds", "competitionTypeId", "fundingRule")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = initialDetailsForm.getBindingResult(); bindingResult.getAllErrors(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(10, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("executiveUserId")); assertEquals( "Please select a Portfolio Manager.", bindingResult.getFieldError("executiveUserId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("title")); assertEquals( "Please enter a title.", bindingResult.getFieldError("title").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationLeadUserId")); assertEquals( "Please select an Innovation Lead.", bindingResult.getFieldError("innovationLeadUserId").getDefaultMessage()); assertEquals(bindingResult.getFieldErrorCount("openingDate"), 2); List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream() .map(fieldError -> fieldError.getDefaultMessage()).collect(toList()); assertTrue(errorsOnOpeningDate.contains("Please enter a valid date.")); assertTrue(errorsOnOpeningDate.contains("Please enter a future date.")); assertTrue(bindingResult.hasFieldErrors("innovationSectorCategoryId")); assertEquals( "Please select an innovation sector.", bindingResult.getFieldError("innovationSectorCategoryId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationAreaCategoryIds")); assertEquals( "Please select an innovation area.", bindingResult.getFieldError("innovationAreaCategoryIds").getDefaultMessage()); assertTrue(bindingResult.hasFieldErrors("competitionTypeId")); assertEquals( "Please select a competition type.", bindingResult.getFieldError("competitionTypeId").getDefaultMessage() ); assertEquals( "Enter a valid funding type.", bindingResult.getFieldError("fundingType").getDefaultMessage() ); assertEquals( "Please select a competition funding rule.", bindingResult.getFieldError("fundingRule").getDefaultMessage() ); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitSectionInitialDetailsInvalidWithRequiredFieldsEmpty() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors( COMPETITION_SETUP_FORM_KEY, "executiveUserId", "title", "innovationLeadUserId", "openingDate", "innovationSectorCategoryId", "innovationAreaCategoryIds" )) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = initialDetailsForm.getBindingResult(); bindingResult.getAllErrors(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(6, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("executiveUserId")); assertEquals( "Please select a Portfolio Manager.", bindingResult.getFieldError("executiveUserId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("title")); assertEquals( "Please enter a title.", bindingResult.getFieldError("title").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationLeadUserId")); assertEquals( "Please select an Innovation Lead.", bindingResult.getFieldError("innovationLeadUserId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("openingDate")); assertEquals( "Please enter a valid date.", bindingResult.getFieldError("openingDate").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationSectorCategoryId")); assertEquals( "Please select an innovation sector.", bindingResult.getFieldError("innovationSectorCategoryId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationAreaCategoryIds")); assertEquals( "Please select an innovation area.", bindingResult.getFieldError("innovationAreaCategoryIds").getDefaultMessage() ); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitUnrestrictedSectionInitialDetailsWithInvalidOpenDate() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); Integer invalidDateDay = 1; Integer invalidDateMonth = 1; Integer invalidDateYear = 1999; MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", invalidDateDay.toString()) .param("openingDateMonth", invalidDateMonth.toString()) .param("openingDateYear", invalidDateYear.toString()) .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("unrestricted", "1") .param("fundingRule", FundingRules.STATE_AID.name())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId()); assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay()); assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth()); assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear()); assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId()); assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds()); assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId()); assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId()); assertEquals("My competition", initialDetailsForm.getTitle()); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitUnrestrictedSectionInitialDetailsWithInvalidFieldsExceedRangeMax() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); Integer invalidDateDay = 32; Integer invalidDateMonth = 13; Integer invalidDateYear = 10000; MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", invalidDateDay.toString()) .param("openingDateMonth", invalidDateMonth.toString()) .param("openingDateYear", invalidDateYear.toString()) .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("unrestricted", "1") .param("fundingRule", FundingRules.STATE_AID.name())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId()); assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay()); assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth()); assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear()); assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId()); assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds()); assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId()); assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId()); assertEquals("My competition", initialDetailsForm.getTitle()); BindingResult bindingResult = initialDetailsForm.getBindingResult(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(2, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("openingDate")); List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream() .map(fieldError -> fieldError.getDefaultMessage()).collect(toList()); assertTrue(errorsOnOpeningDate.contains("Please enter a valid date.")); assertTrue(errorsOnOpeningDate.contains("Please enter a future date.")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitUnrestrictedSectionInitialDetailsWithInvalidFieldsExceedRangeMin() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); Integer invalidDateDay = 0; Integer invalidDateMonth = 0; Integer invalidDateYear = 1899; MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", invalidDateDay.toString()) .param("openingDateMonth", invalidDateMonth.toString()) .param("openingDateYear", invalidDateYear.toString()) .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("unrestricted", "1")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = initialDetailsForm.getBindingResult(); assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId()); assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay()); assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth()); assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear()); assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId()); assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds()); assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId()); assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId()); assertEquals("My competition", initialDetailsForm.getTitle()); bindingResult.getAllErrors(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(2, bindingResult.getFieldErrorCount("openingDate")); List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream() .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(toList()); assertTrue(errorsOnOpeningDate.contains("Please enter a valid date.")); assertTrue(errorsOnOpeningDate.contains("Please enter a future date.")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitSectionInitialDetailsWithoutErrors() throws Exception { String redirectUrl = String.format( "%s/%s/section/initial", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.FALSE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS))) .thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS), eq(loggedInUser))) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", "10") .param("openingDateMonth", "10") .param("openingDateYear", "2100") .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("stateAid", "true")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS)); verify(competitionSetupService).saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS), eq(loggedInUser)); } @Test public void submitSectionDetails_redirectsIfInitialDetailsIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.FALSE); List<CompetitionSetupSection> sections = asList( CompetitionSetupSection.ADDITIONAL_INFO, CompetitionSetupSection.PROJECT_ELIGIBILITY, CompetitionSetupSection.COMPLETION_STAGE, CompetitionSetupSection.MILESTONES, CompetitionSetupSection.APPLICATION_FORM, CompetitionSetupSection.ASSESSORS ); for (CompetitionSetupSection section : sections) { mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/" + section.getPath())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/competition/setup/" + competition.getId())); } } @Test public void submitSectionEligibilityWithErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitSectionEligibilityWithoutErrors() throws Exception { String redirectUrl = String.format("%s/%s/section/project-eligibility", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser)) ) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "stream") .param("researchCategoryId", "1", "2", "3") .param("researchCategoriesApplicable", "true") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1", "2", "3") .param("researchParticipationPercentage","30") .param("resubmission", "yes") .param("overrideFundingRules", "false")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)); verify(competitionSetupService).saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser)); } @Test public void submitSectionEligibilityWithoutStreamName() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "") .param("researchCategoryId", "1", "2", "3") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1") .param("researchParticipationAmountId", "1") .param("resubmission", "yes") .param("overrideFundingRules", "false")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "streamName")); verify(competitionSetupService, never()).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser) ); } @Test public void submitSectionEligibilityFailsWithMaxResearchParticipationIfCompetitionHasFullApplicationFinance() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withApplicationFinanceType(STANDARD) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "stream") .param("researchCategoryId", "1", "2", "3") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1", "2", "3") .param("researchParticipationPercentage", "1000") .param("resubmission", "no")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "researchParticipationPercentage")); verify(competitionSetupService, never()).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser) ); } @Test public void submitSectionEligibilitySucceedsWithoutResearchParticipationIfCompetitionHasNoApplicationFinance() throws Exception { String redirectUrl = String.format("%s/%s/section/project-eligibility", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withApplicationFinanceType((ApplicationFinanceType) null) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser)) ) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "stream") .param("researchCategoryId", "1", "2", "3") .param("researchCategoriesApplicable", "true") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1", "2", "3") .param("researchParticipationPercentage","30") .param("resubmission", "no") .param("overrideFundingRules", "false")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY) ); verify(competitionSetupService).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser) ); } @Test public void coFundersForCompetition() throws Exception { String redirectUrl = String.format("%s/%s/section/additional", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withActivityCode("Activity Code") .withCompetitionCode("c123") .withPafCode("p123") .withBudgetCode("b123") .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withFunders(CompetitionFundersFixture.getTestCoFunders()) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class), eq(loggedInUser)) ) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/additional") .param("activityCode", "a123") .param("pafNumber", "p123") .param("competitionCode", "c123") .param("funders[0].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name()) .param("funders[0].funderBudget", "93129") .param("funders[0].coFunder", "false") .param("budgetCode", "b123")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, atLeastOnce()).getNextSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class) ); verify(competitionSetupService, atLeastOnce()).saveCompetitionSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class), eq(loggedInUser) ); verify(validator).validate(any(AdditionalInfoForm.class), any(BindingResult.class)); } @Test public void duplicateFundersForCompetition() throws Exception { String redirectUrl = String.format("%s/%s/section/additional", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withActivityCode("Activity Code") .withCompetitionCode("c123") .withPafCode("p123") .withBudgetCode("b123") .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withFunders(CompetitionFundersFixture.getTestCoFunders()) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class), any(UserResource.class)) ).thenReturn(serviceFailure(new Error(COMPETITION_DUPLICATE_FUNDERS, HttpStatus.BAD_REQUEST))); MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/additional") .param("activityCode", "a123") .param("pafNumber", "p123") .param("competitionCode", "c123") .param("funders[0].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name()) .param("funders[0].funderBudget", "1") .param("funders[0].coFunder", "false") .param("funders[1].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name()) .param("funders[1].funderBudget", "1") .param("funders[1].coFunder", "true") .param("budgetCode", "b123")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(view().name("competition/setup")) .andReturn(); CompetitionSetupForm form = (CompetitionSetupForm) result.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = form.getBindingResult(); assertEquals(1, bindingResult.getGlobalErrorCount()); assertEquals("COMPETITION_DUPLICATE_FUNDERS", bindingResult.getGlobalErrors().get(0).getCode()); } @Test public void submitCompletionStageSectionDetails() throws Exception { String redirectUrl = String.format( "%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(CompletionStageForm.class), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(CompletionStageForm.class), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE), eq(loggedInUser))).thenReturn(serviceSuccess()); // assert that after a successful submission, the view moves on to the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage") .param("selectedCompletionStage", CompetitionCompletionStage.COMPETITION_CLOSE.name())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, times(1)).getNextSetupSection( any(CompletionStageForm.class), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE)); verify(competitionSetupService, times(1)).saveCompetitionSetupSection( createLambdaMatcher(form -> { assertThat(((CompletionStageForm) form).getSelectedCompletionStage()).isEqualTo(CompetitionCompletionStage.COMPETITION_CLOSE); }), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE), eq(loggedInUser)); } @Test public void submitCompletionStageSectionDetailsWithValidationErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage")) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(model().attributeHasFieldErrorCode("competitionSetupForm", "selectedCompletionStage", "NotNull")) .andExpect(view().name("competition/setup")); verify(competitionSetupService, never()).saveCompetitionSetupSection(any(), any(), any(), eq(loggedInUser)); } @Test public void markCompletionStageSectionIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.COMPLETION_STAGE)). thenReturn(restSuccess()); // assert that after successful marking incomplete, the view remains on the editable view of the Completion Stage page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage")); verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.COMPLETION_STAGE); } @Test public void submitApplicationSubmissionSectionDetails() throws Exception { String redirectUrl = String.format( "%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(ApplicationSubmissionForm.class), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(ApplicationSubmissionForm.class), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION), eq(loggedInUser))).thenReturn(serviceSuccess()); // assert that after a successful submission, the view moves on to the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission") .param("alwaysOpen", "true")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, times(1)).getNextSetupSection( any(ApplicationSubmissionForm.class), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION)); verify(competitionSetupService, times(1)).saveCompetitionSetupSection( createLambdaMatcher(form -> { assertThat(((ApplicationSubmissionForm) form).getAlwaysOpen()).isEqualTo(true); }), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION), eq(loggedInUser)); } @Test public void submitApplicationSubmissionSectionDetailsWithValidationErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission")) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(model().attributeHasFieldErrorCode("competitionSetupForm", "alwaysOpen", "NotNull")) .andExpect(view().name("competition/setup")); verify(competitionSetupService, never()).saveCompetitionSetupSection(any(), any(), any(), eq(loggedInUser)); } @Test public void markApplicationSubmissionSectionIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.APPLICATION_SUBMISSION)). thenReturn(restSuccess()); // assert that after successful marking incomplete, the view remains on the editable view of the Completion Stage page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission")); verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.APPLICATION_SUBMISSION); } @Test public void submitMilestonesSectionDetails() throws Exception { String redirectUrl = String.format("%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.saveCompetitionSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES), eq(loggedInUser))).thenReturn(serviceSuccess()); when(competitionSetupService.getNextSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); // assert that after successful submission, the view remains on the read-only view of the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, times(1)).getNextSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES)); verify(competitionSetupService, times(1)).saveCompetitionSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES), eq(loggedInUser)); } @Test public void markMilestonesSectionIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.MILESTONES)). thenReturn(restSuccess()); // assert that after successful marking incomplete, the view remains on the editable view of the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones")); verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.MILESTONES); } @Test public void setCompetitionAsReadyToOpen() throws Exception { when(competitionSetupService.setCompetitionAsReadyToOpen(COMPETITION_ID)).thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/ready-to-open")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/competition/setup/" + COMPETITION_ID)); verify(competitionSetupService, only()).setCompetitionAsReadyToOpen(COMPETITION_ID); } @Test public void setCompetitionAsReadyToOpen_failure() throws Exception { when(competitionSetupService.setCompetitionAsReadyToOpen(COMPETITION_ID)).thenReturn( serviceFailure(new Error("competition.setup.not.ready.to.open", HttpStatus.BAD_REQUEST))); // For re-display of Competition Setup following the failure CompetitionResource competitionResource = newCompetitionResource() .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource)); MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/ready-to-open")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(view().name("competition/setup")) .andReturn(); verify(competitionSetupService).setCompetitionAsReadyToOpen(COMPETITION_ID); CompetitionSetupSummaryForm form = (CompetitionSetupSummaryForm) result.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = form.getBindingResult(); assertEquals(1, bindingResult.getGlobalErrorCount()); assertEquals("competition.setup.not.ready.to.open", bindingResult.getGlobalErrors().get(0).getCode()); } @Test public void submitAssessorsSectionDetailsWithErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitAssessorsSectionDetailsWithoutErrors() throws Exception { String redirectUrl = String.format("%s/%s/section/assessors", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)) ); when(competitionSetupService.saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS), eq(loggedInUser))).thenReturn(serviceSuccess() ); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("averageAssessorScore", "0") .param("assessorCount", "1") .param("assessorPay", "10") .param("hasAssessmentPanel", "0") .param("hasInterviewStage", "0") .param("assessorFinanceView", "OVERVIEW")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS)); verify(competitionSetupService).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS), eq(loggedInUser)); } @Test public void submitAssessorsSectionDetailsWithInvalidAssessorCount() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "") .param("assessorPay", "10")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorCount")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitAssessorsSectionDetailsWithInvalidAssessorPay() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "3") .param("assessorPay", "")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitAssessorsSectionDetailsWithInvalidAssessorPay_Bignumber() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "3") .param("assessorPay", "12345678912334")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void testSubmitAssessorsSectionDetailsWithInvalidAssessorPay_NegativeNumber() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withNonIfs(FALSE) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "3") .param("assessorPay", "-1")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void deleteCompetition() throws Exception { when(competitionSetupService.deleteCompetition(COMPETITION_ID)).thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/delete")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/dashboard")); verify(competitionSetupService, only()).deleteCompetition(COMPETITION_ID); } @Test public void deleteCompetition_failure() throws Exception { when(competitionSetupService.deleteCompetition(COMPETITION_ID)).thenReturn( serviceFailure(new Error(COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED, HttpStatus.BAD_REQUEST))); // For re-display of Competition Setup following the failure CompetitionResource competitionResource = newCompetitionResource() .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource)); MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/delete")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(view().name("competition/setup")) .andReturn(); CompetitionSetupSummaryForm form = (CompetitionSetupSummaryForm) result.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = form.getBindingResult(); assertEquals(1, bindingResult.getGlobalErrorCount()); assertEquals("COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED", bindingResult.getGlobalErrors().get(0).getCode()); } }
package enmasse.systemtest; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static io.vertx.core.json.Json.mapper; public class AddressApiClient { private final HttpClient httpClient; private final Endpoint endpoint; private final boolean isMultitenant; public AddressApiClient(Vertx vertx, Endpoint endpoint, boolean isMultitenant) { this.httpClient = vertx.createHttpClient(); this.endpoint = endpoint; this.isMultitenant = isMultitenant; } public void close() { httpClient.close(); } public void deployInstance(String instanceName) throws JsonProcessingException, InterruptedException { if (isMultitenant) { ObjectNode config = mapper.createObjectNode(); config.put("apiVersion", "v3"); config.put("kind", "Instance"); ObjectNode metadata = config.putObject("metadata"); metadata.put("name", instanceName); ObjectNode spec = config.putObject("spec"); spec.put("namespace", instanceName); CountDownLatch latch = new CountDownLatch(1); HttpClientRequest request; request = httpClient.post(endpoint.getPort(), endpoint.getHost(), "/v3/instance"); request.putHeader("content-type", "application/json"); request.handler(event -> { if (event.statusCode() >= 200 && event.statusCode() < 300) { latch.countDown(); } }); request.end(Buffer.buffer(mapper.writeValueAsBytes(config))); latch.await(30, TimeUnit.SECONDS); } } public void deploy(String instanceName, Destination ... destinations) throws Exception { ObjectNode config = mapper.createObjectNode(); config.put("apiVersion", "v3"); config.put("kind", "AddressList"); ArrayNode items = config.putArray("items"); for (Destination destination : destinations) { ObjectNode entry = items.addObject(); ObjectNode metadata = entry.putObject("metadata"); metadata.put("name", destination.getAddress()); ObjectNode spec = entry.putObject("spec"); spec.put("store_and_forward", destination.isStoreAndForward()); spec.put("multicast", destination.isMulticast()); spec.put("group", destination.getGroup()); destination.getFlavor().ifPresent(e -> spec.put("flavor", e)); } CountDownLatch latch = new CountDownLatch(1); HttpClientRequest request; if (isMultitenant) { request = httpClient.put(endpoint.getPort(), endpoint.getHost(), "/v3/instance/" + instanceName + "/address"); } else { request = httpClient.put(endpoint.getPort(), endpoint.getHost(), "/v3/address"); } request.putHeader("content-type", "application/json"); request.handler(event -> { event.bodyHandler(buffer -> { System.out.println("Got response from rest api: " + buffer.toString()); }); if (event.statusCode() >= 200 && event.statusCode() < 300) { latch.countDown(); } }); request.end(Buffer.buffer(mapper.writeValueAsBytes(config))); if (!latch.await(30, TimeUnit.SECONDS)) { throw new RuntimeException("Timeout deploying address config"); } } }
package org.innovateuk.ifs.management.competition.setup; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.category.resource.InnovationAreaResource; import org.innovateuk.ifs.category.resource.InnovationSectorResource; import org.innovateuk.ifs.category.service.CategoryRestService; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.competition.publiccontent.resource.FundingType; import org.innovateuk.ifs.competition.resource.*; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.innovateuk.ifs.competition.service.CompetitionSetupRestService; import org.innovateuk.ifs.competition.service.TermsAndConditionsRestService; import org.innovateuk.ifs.management.competition.setup.applicationsubmission.form.ApplicationSubmissionForm; import org.innovateuk.ifs.management.competition.setup.completionstage.form.CompletionStageForm; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupSummaryForm; import org.innovateuk.ifs.management.competition.setup.core.populator.CompetitionSetupFormPopulator; import org.innovateuk.ifs.management.competition.setup.core.service.CompetitionSetupService; import org.innovateuk.ifs.management.competition.setup.fundinginformation.form.AdditionalInfoForm; import org.innovateuk.ifs.management.competition.setup.initialdetail.form.InitialDetailsForm; import org.innovateuk.ifs.management.competition.setup.initialdetail.populator.ManageInnovationLeadsModelPopulator; import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestonesForm; import org.innovateuk.ifs.management.fixtures.CompetitionFundersFixture; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.UserRestService; import org.innovateuk.ifs.user.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.HttpStatus; import org.springframework.test.web.servlet.MvcResult; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.category.builder.InnovationAreaResourceBuilder.newInnovationAreaResource; import static org.innovateuk.ifs.category.builder.InnovationSectorResourceBuilder.newInnovationSectorResource; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_DUPLICATE_FUNDERS; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.innovateuk.ifs.competition.builder.CompetitionTypeResourceBuilder.newCompetitionTypeResource; import static org.innovateuk.ifs.competition.resource.ApplicationFinanceType.STANDARD; import static org.innovateuk.ifs.management.competition.setup.CompetitionSetupController.*; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.COMP_ADMIN; import static org.innovateuk.ifs.user.resource.Role.INNOVATION_LEAD; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Class for testing public functions of {@link CompetitionSetupController} */ @RunWith(MockitoJUnitRunner.Silent.class) public class CompetitionSetupControllerTest extends BaseControllerMockMVCTest<CompetitionSetupController> { private static final Long COMPETITION_ID = 12L; private static final String URL_PREFIX = "/competition/setup"; @Mock private CategoryRestService categoryRestService; @Mock private CompetitionSetupService competitionSetupService; @Mock private CompetitionSetupRestService competitionSetupRestService; @Mock private Validator validator; @Mock private ManageInnovationLeadsModelPopulator manageInnovationLeadsModelPopulator; @Mock private UserService userService; @Mock private UserRestService userRestService; @Mock private CompetitionRestService competitionRestService; @Mock private TermsAndConditionsRestService termsAndConditionsRestService; @Override protected CompetitionSetupController supplyControllerUnderTest() { return new CompetitionSetupController(); } @Before public void setUp() { when(userRestService.findByUserRole(COMP_ADMIN)) .thenReturn( restSuccess(newUserResource() .withFirstName("Comp") .withLastName("Admin") .build(1)) ); when(userRestService.findByUserRole(INNOVATION_LEAD)) .thenReturn( restSuccess(newUserResource() .withFirstName("Comp") .withLastName("Technologist") .build(1)) ); List<InnovationSectorResource> innovationSectorResources = newInnovationSectorResource() .withName("A Innovation Sector") .withId(1L) .build(1); when(categoryRestService.getInnovationSectors()).thenReturn(restSuccess(innovationSectorResources)); List<InnovationAreaResource> innovationAreaResources = newInnovationAreaResource() .withName("A Innovation Area") .withId(2L) .withSector(1L) .build(1); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); List<CompetitionTypeResource> competitionTypeResources = newCompetitionTypeResource() .withId(1L) .withName("Programme") .withCompetitions(singletonList(COMPETITION_ID)) .build(1); when(competitionRestService.getCompetitionTypes()).thenReturn(restSuccess(competitionTypeResources)); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(true); } @Test public void initCompetitionSetupSection() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(FALSE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute(SETUP_READY_KEY, FALSE)) .andExpect(model().attribute(READY_TO_OPEN_KEY, FALSE)); } @Test public void initCompetitionSetupSectionSetupComplete() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute(SETUP_READY_KEY, TRUE)) .andExpect(model().attribute(READY_TO_OPEN_KEY, FALSE)); } @Test public void initCompetitionSetupSectionReadyToOpen() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.READY_TO_OPEN).build(); when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(FALSE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute(SETUP_READY_KEY, FALSE)) .andExpect(model().attribute(READY_TO_OPEN_KEY, TRUE)); } @Test public void editCompetitionSetupSectionInitial() throws Exception { InitialDetailsForm competitionSetupInitialDetailsForm = new InitialDetailsForm(); competitionSetupInitialDetailsForm.setTitle("Test competition"); competitionSetupInitialDetailsForm.setCompetitionTypeId(2L); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withName("Test competition") .withCompetitionCode("Code") .withCompetitionType(2L) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); CompetitionSetupForm compSetupForm = mock(CompetitionSetupForm.class); CompetitionSetupFormPopulator compSetupFormPopulator = mock(CompetitionSetupFormPopulator.class); when(competitionSetupService.getSectionFormPopulator(CompetitionSetupSection.INITIAL_DETAILS)) .thenReturn(compSetupFormPopulator); when(compSetupFormPopulator.populateForm(competition)).thenReturn(compSetupForm); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")) .andExpect(model().attribute("competitionSetupForm", compSetupForm)); verify(competitionSetupService).populateCompetitionSectionModelAttributes( eq(competition), any(), eq(CompetitionSetupSection.INITIAL_DETAILS) ); } @Test public void setSectionAsIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).withName( "Test competition").withCompetitionCode("Code").withCompetitionType(2L).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(anyLong(), any(CompetitionSetupSection.class))).thenReturn(restSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")); } @Test public void generateCompetitionCode() throws Exception { ZonedDateTime time = ZonedDateTime.of(2016, 12, 1, 0, 0, 0, 0, ZoneId.systemDefault()); CompetitionResource competition = newCompetitionResource() .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withName("Test competition") .withCompetitionCode("Code") .withCompetitionType(2L) .withStartDate(time) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.generateCompetitionCode(COMPETITION_ID, time)) .thenReturn(restSuccess("1612-1")); mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID + "/generateCompetitionCode?day=01&month=12&year=2016")) .andExpect(status().isOk()) .andExpect(jsonPath("message", is("1612-1"))); } @Test public void submitUnrestrictedSectionInitialDetailsInvalidWithRequiredFieldsEmpty() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("unrestricted", "1")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors( COMPETITION_SETUP_FORM_KEY, "executiveUserId", "title", "innovationLeadUserId", "openingDate", "innovationSectorCategoryId", "innovationAreaCategoryIds", "competitionTypeId", "fundingRule")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = initialDetailsForm.getBindingResult(); bindingResult.getAllErrors(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(10, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("executiveUserId")); assertEquals( "Please select a Portfolio Manager.", bindingResult.getFieldError("executiveUserId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("title")); assertEquals( "Please enter a title.", bindingResult.getFieldError("title").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationLeadUserId")); assertEquals( "Please select an Innovation Lead.", bindingResult.getFieldError("innovationLeadUserId").getDefaultMessage()); assertEquals(bindingResult.getFieldErrorCount("openingDate"), 2); List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream() .map(fieldError -> fieldError.getDefaultMessage()).collect(toList()); assertTrue(errorsOnOpeningDate.contains("Please enter a valid date.")); assertTrue(errorsOnOpeningDate.contains("Please enter a future date.")); assertTrue(bindingResult.hasFieldErrors("innovationSectorCategoryId")); assertEquals( "Please select an innovation sector.", bindingResult.getFieldError("innovationSectorCategoryId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationAreaCategoryIds")); assertEquals( "Please select an innovation area.", bindingResult.getFieldError("innovationAreaCategoryIds").getDefaultMessage()); assertTrue(bindingResult.hasFieldErrors("competitionTypeId")); assertEquals( "Please select a competition type.", bindingResult.getFieldError("competitionTypeId").getDefaultMessage() ); assertEquals( "Enter a valid funding type.", bindingResult.getFieldError("fundingType").getDefaultMessage() ); assertEquals( "Please select a competition funding rule.", bindingResult.getFieldError("fundingRule").getDefaultMessage() ); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitSectionInitialDetailsInvalidWithRequiredFieldsEmpty() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors( COMPETITION_SETUP_FORM_KEY, "executiveUserId", "title", "innovationLeadUserId", "openingDate", "innovationSectorCategoryId", "innovationAreaCategoryIds" )) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = initialDetailsForm.getBindingResult(); bindingResult.getAllErrors(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(6, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("executiveUserId")); assertEquals( "Please select a Portfolio Manager.", bindingResult.getFieldError("executiveUserId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("title")); assertEquals( "Please enter a title.", bindingResult.getFieldError("title").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationLeadUserId")); assertEquals( "Please select an Innovation Lead.", bindingResult.getFieldError("innovationLeadUserId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("openingDate")); assertEquals( "Please enter a valid date.", bindingResult.getFieldError("openingDate").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationSectorCategoryId")); assertEquals( "Please select an innovation sector.", bindingResult.getFieldError("innovationSectorCategoryId").getDefaultMessage() ); assertTrue(bindingResult.hasFieldErrors("innovationAreaCategoryIds")); assertEquals( "Please select an innovation area.", bindingResult.getFieldError("innovationAreaCategoryIds").getDefaultMessage() ); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitUnrestrictedSectionInitialDetailsWithInvalidOpenDate() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); Integer invalidDateDay = 1; Integer invalidDateMonth = 1; Integer invalidDateYear = 1999; MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", invalidDateDay.toString()) .param("openingDateMonth", invalidDateMonth.toString()) .param("openingDateYear", invalidDateYear.toString()) .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("unrestricted", "1") .param("fundingRule", FundingRules.STATE_AID.name())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId()); assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay()); assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth()); assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear()); assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId()); assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds()); assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId()); assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId()); assertEquals("My competition", initialDetailsForm.getTitle()); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitUnrestrictedSectionInitialDetailsWithInvalidFieldsExceedRangeMax() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); Integer invalidDateDay = 32; Integer invalidDateMonth = 13; Integer invalidDateYear = 10000; MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", invalidDateDay.toString()) .param("openingDateMonth", invalidDateMonth.toString()) .param("openingDateYear", invalidDateYear.toString()) .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("unrestricted", "1") .param("fundingRule", FundingRules.STATE_AID.name())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId()); assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay()); assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth()); assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear()); assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId()); assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds()); assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId()); assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId()); assertEquals("My competition", initialDetailsForm.getTitle()); BindingResult bindingResult = initialDetailsForm.getBindingResult(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(2, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("openingDate")); List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream() .map(fieldError -> fieldError.getDefaultMessage()).collect(toList()); assertTrue(errorsOnOpeningDate.contains("Please enter a valid date.")); assertTrue(errorsOnOpeningDate.contains("Please enter a future date.")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitUnrestrictedSectionInitialDetailsWithInvalidFieldsExceedRangeMin() throws Exception { CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); Integer invalidDateDay = 0; Integer invalidDateMonth = 0; Integer invalidDateYear = 1899; MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", invalidDateDay.toString()) .param("openingDateMonth", invalidDateMonth.toString()) .param("openingDateYear", invalidDateYear.toString()) .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("unrestricted", "1")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate")) .andExpect(view().name("competition/setup")) .andReturn(); InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = initialDetailsForm.getBindingResult(); assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId()); assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay()); assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth()); assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear()); assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId()); assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds()); assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId()); assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId()); assertEquals("My competition", initialDetailsForm.getTitle()); bindingResult.getAllErrors(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(2, bindingResult.getFieldErrorCount("openingDate")); List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream() .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(toList()); assertTrue(errorsOnOpeningDate.contains("Please enter a valid date.")); assertTrue(errorsOnOpeningDate.contains("Please enter a future date.")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitSectionInitialDetailsWithoutErrors() throws Exception { String redirectUrl = String.format( "%s/%s/section/initial", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.FALSE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS))) .thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS), eq(loggedInUser))) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial") .param("executiveUserId", "1") .param("openingDateDay", "10") .param("openingDateMonth", "10") .param("openingDateYear", "2100") .param("innovationSectorCategoryId", "1") .param("innovationAreaCategoryIds", "1", "2", "3") .param("competitionTypeId", "1") .param("fundingType", FundingType.GRANT.name()) .param("innovationLeadUserId", "1") .param("title", "My competition") .param("stateAid", "true")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS)); verify(competitionSetupService).saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.INITIAL_DETAILS), eq(loggedInUser)); } @Test public void submitSectionDetails_redirectsIfInitialDetailsIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.FALSE); List<CompetitionSetupSection> sections = asList( CompetitionSetupSection.ADDITIONAL_INFO, CompetitionSetupSection.PROJECT_ELIGIBILITY, CompetitionSetupSection.COMPLETION_STAGE, CompetitionSetupSection.MILESTONES, CompetitionSetupSection.APPLICATION_FORM, CompetitionSetupSection.ASSESSORS ); for (CompetitionSetupSection section : sections) { mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/" + section.getPath())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/competition/setup/" + competition.getId())); } } @Test public void submitSectionEligibilityWithErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitSectionEligibilityWithoutErrors() throws Exception { String redirectUrl = String.format("%s/%s/section/project-eligibility", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser)) ) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "stream") .param("researchCategoryId", "1", "2", "3") .param("researchCategoriesApplicable", "true") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1", "2", "3") .param("researchParticipationAmountId", "1") .param("resubmission", "yes") .param("overrideFundingRules", "false")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)); verify(competitionSetupService).saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser)); } @Test public void submitSectionEligibilityWithoutStreamName() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "") .param("researchCategoryId", "1", "2", "3") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1") .param("researchParticipationAmountId", "1") .param("resubmission", "yes") .param("overrideFundingRules", "false")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "streamName")); verify(competitionSetupService, never()).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser) ); } @Test public void submitSectionEligibilityFailsWithoutResearchParticipationIfCompetitionHasFullApplicationFinance() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withApplicationFinanceType(STANDARD) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "stream") .param("researchCategoryId", "1", "2", "3") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1", "2", "3") .param("researchParticipationAmountId", "") .param("resubmission", "no")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "researchParticipationAmountId")); verify(competitionSetupService, never()).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser) ); } @Test public void submitSectionEligibilitySucceedsWithoutResearchParticipationIfCompetitionHasNoApplicationFinance() throws Exception { String redirectUrl = String.format("%s/%s/section/project-eligibility", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withApplicationFinanceType((ApplicationFinanceType) null) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser)) ) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility") .param("multipleStream", "yes") .param("streamName", "stream") .param("researchCategoryId", "1", "2", "3") .param("researchCategoriesApplicable", "true") .param("singleOrCollaborative", "collaborative") .param("leadApplicantTypes", "1", "2", "3") .param("resubmission", "no") .param("overrideFundingRules", "false")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY) ); verify(competitionSetupService).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.PROJECT_ELIGIBILITY), eq(loggedInUser) ); } @Test public void coFundersForCompetition() throws Exception { String redirectUrl = String.format("%s/%s/section/additional", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withActivityCode("Activity Code") .withCompetitionCode("c123") .withPafCode("p123") .withBudgetCode("b123") .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withFunders(CompetitionFundersFixture.getTestCoFunders()) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class), eq(loggedInUser)) ) .thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/additional") .param("activityCode", "a123") .param("pafNumber", "p123") .param("competitionCode", "c123") .param("funders[0].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name()) .param("funders[0].funderBudget", "93129") .param("funders[0].coFunder", "false") .param("budgetCode", "b123")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, atLeastOnce()).getNextSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class) ); verify(competitionSetupService, atLeastOnce()).saveCompetitionSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class), eq(loggedInUser) ); verify(validator).validate(any(AdditionalInfoForm.class), any(BindingResult.class)); } @Test public void duplicateFundersForCompetition() throws Exception { String redirectUrl = String.format("%s/%s/section/additional", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withActivityCode("Activity Code") .withCompetitionCode("c123") .withPafCode("p123") .withBudgetCode("b123") .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withFunders(CompetitionFundersFixture.getTestCoFunders()) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class)) ).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(AdditionalInfoForm.class), any(CompetitionResource.class), any(CompetitionSetupSection.class), any(UserResource.class)) ).thenReturn(serviceFailure(new Error(COMPETITION_DUPLICATE_FUNDERS, HttpStatus.BAD_REQUEST))); MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/additional") .param("activityCode", "a123") .param("pafNumber", "p123") .param("competitionCode", "c123") .param("funders[0].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name()) .param("funders[0].funderBudget", "1") .param("funders[0].coFunder", "false") .param("funders[1].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name()) .param("funders[1].funderBudget", "1") .param("funders[1].coFunder", "true") .param("budgetCode", "b123")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(view().name("competition/setup")) .andReturn(); CompetitionSetupForm form = (CompetitionSetupForm) result.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = form.getBindingResult(); assertEquals(1, bindingResult.getGlobalErrorCount()); assertEquals("COMPETITION_DUPLICATE_FUNDERS", bindingResult.getGlobalErrors().get(0).getCode()); } @Test public void submitCompletionStageSectionDetails() throws Exception { String redirectUrl = String.format( "%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(CompletionStageForm.class), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(CompletionStageForm.class), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE), eq(loggedInUser))).thenReturn(serviceSuccess()); // assert that after a successful submission, the view moves on to the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage") .param("selectedCompletionStage", CompetitionCompletionStage.COMPETITION_CLOSE.name())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, times(1)).getNextSetupSection( any(CompletionStageForm.class), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE)); verify(competitionSetupService, times(1)).saveCompetitionSetupSection( createLambdaMatcher(form -> { assertThat(((CompletionStageForm) form).getSelectedCompletionStage()).isEqualTo(CompetitionCompletionStage.COMPETITION_CLOSE); }), eq(competition), eq(CompetitionSetupSection.COMPLETION_STAGE), eq(loggedInUser)); } @Test public void submitCompletionStageSectionDetailsWithValidationErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage")) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(model().attributeHasFieldErrorCode("competitionSetupForm", "selectedCompletionStage", "NotNull")) .andExpect(view().name("competition/setup")); verify(competitionSetupService, never()).saveCompetitionSetupSection(any(), any(), any(), eq(loggedInUser)); } @Test public void markCompletionStageSectionIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.COMPLETION_STAGE)). thenReturn(restSuccess()); // assert that after successful marking incomplete, the view remains on the editable view of the Completion Stage page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage")); verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.COMPLETION_STAGE); } @Test public void submitApplicationSubmissionSectionDetails() throws Exception { String redirectUrl = String.format( "%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( any(ApplicationSubmissionForm.class), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); when(competitionSetupService.saveCompetitionSetupSection( any(ApplicationSubmissionForm.class), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION), eq(loggedInUser))).thenReturn(serviceSuccess()); // assert that after a successful submission, the view moves on to the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission") .param("alwaysOpen", "true")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, times(1)).getNextSetupSection( any(ApplicationSubmissionForm.class), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION)); verify(competitionSetupService, times(1)).saveCompetitionSetupSection( createLambdaMatcher(form -> { assertThat(((ApplicationSubmissionForm) form).getAlwaysOpen()).isEqualTo(true); }), eq(competition), eq(CompetitionSetupSection.APPLICATION_SUBMISSION), eq(loggedInUser)); } @Test public void submitApplicationSubmissionSectionDetailsWithValidationErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission")) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(model().attributeHasFieldErrorCode("competitionSetupForm", "alwaysOpen", "NotNull")) .andExpect(view().name("competition/setup")); verify(competitionSetupService, never()).saveCompetitionSetupSection(any(), any(), any(), eq(loggedInUser)); } @Test public void markApplicationSubmissionSectionIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.APPLICATION_SUBMISSION)). thenReturn(restSuccess()); // assert that after successful marking incomplete, the view remains on the editable view of the Completion Stage page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/application-submission")); verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.APPLICATION_SUBMISSION); } @Test public void submitMilestonesSectionDetails() throws Exception { String redirectUrl = String.format("%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.saveCompetitionSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES), eq(loggedInUser))).thenReturn(serviceSuccess()); when(competitionSetupService.getNextSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))); // assert that after successful submission, the view remains on the read-only view of the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService, times(1)).getNextSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES)); verify(competitionSetupService, times(1)).saveCompetitionSetupSection( any(MilestonesForm.class), eq(competition), eq(CompetitionSetupSection.MILESTONES), eq(loggedInUser)); } @Test public void markMilestonesSectionIncomplete() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.MILESTONES)). thenReturn(restSuccess()); // assert that after successful marking incomplete, the view remains on the editable view of the Milestones page mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones/edit")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones")); verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.MILESTONES); } @Test public void setCompetitionAsReadyToOpen() throws Exception { when(competitionSetupService.setCompetitionAsReadyToOpen(COMPETITION_ID)).thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/ready-to-open")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/competition/setup/" + COMPETITION_ID)); verify(competitionSetupService, only()).setCompetitionAsReadyToOpen(COMPETITION_ID); } @Test public void setCompetitionAsReadyToOpen_failure() throws Exception { when(competitionSetupService.setCompetitionAsReadyToOpen(COMPETITION_ID)).thenReturn( serviceFailure(new Error("competition.setup.not.ready.to.open", HttpStatus.BAD_REQUEST))); // For re-display of Competition Setup following the failure CompetitionResource competitionResource = newCompetitionResource() .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource)); MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/ready-to-open")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(view().name("competition/setup")) .andReturn(); verify(competitionSetupService).setCompetitionAsReadyToOpen(COMPETITION_ID); CompetitionSetupSummaryForm form = (CompetitionSetupSummaryForm) result.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = form.getBindingResult(); assertEquals(1, bindingResult.getGlobalErrorCount()); assertEquals("competition.setup.not.ready.to.open", bindingResult.getGlobalErrors().get(0).getCode()); } @Test public void submitAssessorsSectionDetailsWithErrors() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")) .andExpect(status().isOk()) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitAssessorsSectionDetailsWithoutErrors() throws Exception { String redirectUrl = String.format("%s/%s/section/assessors", URL_PREFIX, COMPETITION_ID); CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); when(competitionSetupService.getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)) ); when(competitionSetupService.saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS), eq(loggedInUser))).thenReturn(serviceSuccess() ); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("averageAssessorScore", "0") .param("assessorCount", "1") .param("assessorPay", "10") .param("hasAssessmentPanel", "0") .param("hasInterviewStage", "0") .param("assessorFinanceView", "OVERVIEW")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(redirectUrl)); verify(competitionSetupService).getNextSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS)); verify(competitionSetupService).saveCompetitionSetupSection( isA(CompetitionSetupForm.class), eq(competition), eq(CompetitionSetupSection.ASSESSORS), eq(loggedInUser)); } @Test public void submitAssessorsSectionDetailsWithInvalidAssessorCount() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "") .param("assessorPay", "10")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorCount")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitAssessorsSectionDetailsWithInvalidAssessorPay() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "3") .param("assessorPay", "")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void submitAssessorsSectionDetailsWithInvalidAssessorPay_Bignumber() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "3") .param("assessorPay", "12345678912334")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void testSubmitAssessorsSectionDetailsWithInvalidAssessorPay_NegativeNumber() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(COMPETITION_ID) .withNonIfs(FALSE) .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .build(); when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.TRUE); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition)); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors") .param("assessorCount", "3") .param("assessorPay", "-1")) .andExpect(status().isOk()) .andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay")) .andExpect(view().name("competition/setup")); verify(competitionSetupRestService, never()).update(competition); } @Test public void deleteCompetition() throws Exception { when(competitionSetupService.deleteCompetition(COMPETITION_ID)).thenReturn(serviceSuccess()); mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/delete")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/dashboard")); verify(competitionSetupService, only()).deleteCompetition(COMPETITION_ID); } @Test public void deleteCompetition_failure() throws Exception { when(competitionSetupService.deleteCompetition(COMPETITION_ID)).thenReturn( serviceFailure(new Error(COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED, HttpStatus.BAD_REQUEST))); // For re-display of Competition Setup following the failure CompetitionResource competitionResource = newCompetitionResource() .withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP) .withId(COMPETITION_ID) .build(); when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource)); MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/delete")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().errorCount(1)) .andExpect(view().name("competition/setup")) .andReturn(); CompetitionSetupSummaryForm form = (CompetitionSetupSummaryForm) result.getModelAndView().getModel() .get(COMPETITION_SETUP_FORM_KEY); BindingResult bindingResult = form.getBindingResult(); assertEquals(1, bindingResult.getGlobalErrorCount()); assertEquals("COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED", bindingResult.getGlobalErrors().get(0).getCode()); } }
public class HealthcarePlan { private String name; private int checkups; private int hygiene; private int repair; private double monthlyCost; public HealthcarePlan (String streetName,int checks,int hygienes,int repairs, double cost) { streetName = name; checks = checkups; hygienes = hygiene; repairs= repair; cost = monthlyCost; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCheckups() { return checkups; } public void setCheckups(int checkups) { this.checkups = checkups; } public int getHygiene() { return hygiene; } public void setHygiene(int hygiene) { this.hygiene = hygiene; } public int getRepair() { return repair; } public void setRepair(int repair) { this.repair = repair; } public double getMonthlyCost() { return monthlyCost; } public void setMonthlyCost(double monthlyCost) { this.monthlyCost = monthlyCost; } }
package fredboat.commandmeta; import fredboat.commandmeta.abs.ICommandOwnerRestricted; import fredboat.commandmeta.abs.Command; import fredboat.commandmeta.abs.ICommand; import fredboat.commandmeta.abs.IMusicBackupCommand; import fredboat.commandmeta.abs.IMusicCommand; import fredboat.util.BotConstants; import fredboat.util.DiscordUtil; import fredboat.util.TextUtils; import java.util.ArrayList; import java.util.HashMap; import net.dv8tion.jda.Permission; import net.dv8tion.jda.entities.Guild; import net.dv8tion.jda.entities.Message; import net.dv8tion.jda.entities.TextChannel; import net.dv8tion.jda.entities.User; import net.dv8tion.jda.utils.PermissionUtil; public class CommandManager { public static HashMap<String, ICommand> commands = new HashMap<>(); public static ICommand defaultCmd = new UnknownCommand(); public static int commandsExecuted = 0; public static void prefixCalled(Command invoked, Guild guild, TextChannel channel, User invoker, Message message) { //String[] args = message.getRawContent().replace("\n", " ").split(" "); String[] args = commandToArguments(message.getRawContent()); commandsExecuted++; if (invoked instanceof ICommandOwnerRestricted) { //This command is restricted to only Frederikam //Check if invoker is actually Frederikam if (!invoker.getId().equals(BotConstants.OWNER_ID)) { channel.sendMessage(TextUtils.prefaceWithMention(invoker, " you are not allowed to use that command!")); return; } } if (invoked instanceof IMusicBackupCommand && DiscordUtil.isMusicBot() && DiscordUtil.isMainBotPresent(guild)) { System.out.println("Ignored command because main bot is present"); return; } if (invoked instanceof IMusicCommand && PermissionUtil.checkPermission(channel, guild.getJDA().getSelfInfo(), Permission.MESSAGE_WRITE) == false) { System.out.println("Ignored command because it was a music command, and this bot cannot write in that channel"); return; } try { invoked.onInvoke(guild, channel, invoker, message, args); } catch (Exception e) { TextUtils.handleException(e, channel, invoker); } } public static String[] commandToArguments(String cmd) { ArrayList<String> a = new ArrayList<>(); int argi = 0; boolean isInQuote = false; for (Character ch : cmd.toCharArray()) { if (Character.isWhitespace(ch) && isInQuote == false) { String arg = null; try { arg = a.get(argi); } catch (IndexOutOfBoundsException e) { } if (arg != null) { argi++;//On to the next arg }//else ignore } else if (ch.equals('"')) { isInQuote = !isInQuote; } else { a = writeToArg(a, argi, ch); } } String[] newA = new String[a.size()]; int i = 0; for (String str : a) { newA[i] = str; i++; } return newA; } private static ArrayList<String> writeToArg(ArrayList<String> a, int argi, char ch) { String arg = null; try { arg = a.get(argi); } catch (IndexOutOfBoundsException e) { } if (arg == null) { a.add(argi, String.valueOf(ch)); } else { a.set(argi, arg + ch); } return a; } }
package function.cohort.vargeno; import function.annotation.base.Annotation; import function.annotation.base.AnnotationLevelFilterCommand; import function.annotation.base.EffectManager; import function.annotation.base.GeneManager; import function.annotation.base.PolyphenManager; import function.annotation.base.TranscriptManager; import function.cohort.base.CohortLevelFilterCommand; import function.external.exac.ExAC; import function.external.gnomad.GnomADExome; import function.external.gnomad.GnomADGenome; import function.variant.base.VariantLevelFilterCommand; import function.variant.base.VariantManager; import global.Data; import global.Index; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; import org.apache.commons.csv.CSVRecord; import utils.FormatManager; import utils.MathManager; /** * * @author nick */ public class VariantLite { private String variantID; private String chr; private int pos; private String ref; private String alt; private boolean isSNV; private ExAC exac; private GnomADExome gnomADExome; private GnomADGenome gnomADGenome; private StringJoiner allGeneTranscriptSJ = new StringJoiner(";"); private List<String> geneList = new ArrayList(); private Annotation mostDamagingAnnotation = new Annotation(); private int[] qcFailSample = new int[2]; private float looAF; private CSVRecord record; public VariantLite(CSVRecord record) { this.record = record; variantID = record.get(ListVarGenoLite.VARIANT_ID_HEADER); String[] tmp = variantID.split("-"); chr = tmp[0]; pos = Integer.valueOf(tmp[1]); ref = tmp[2]; alt = tmp[3]; isSNV = ref.length() == alt.length(); exac = new ExAC(chr, pos, ref, alt, record); gnomADExome = new GnomADExome(chr, pos, ref, alt, record); gnomADGenome = new GnomADGenome(chr, pos, ref, alt, record); String allAnnotation = record.get(ListVarGenoLite.ALL_ANNOTATION_HEADER); processAnnotation( allAnnotation, chr, pos, allGeneTranscriptSJ, geneList, mostDamagingAnnotation); qcFailSample[Index.CASE] = FormatManager.getInteger(record.get(ListVarGenoLite.QC_FAIL_CASE_HEADER)); qcFailSample[Index.CTRL] = FormatManager.getInteger(record.get(ListVarGenoLite.QC_FAIL_CTRL_HEADER)); looAF = FormatManager.getFloat(record.get(ListVarGenoLite.LOO_AF_HEADER)); } private void processAnnotation( String allAnnotation, String chr, int pos, StringJoiner allGeneTranscriptSJ, List<String> geneList, Annotation mostDamagingAnnotation) { for (String annotation : allAnnotation.split(";")) { String[] values = annotation.split("\\|"); String effect = values[0]; String geneName = values[1]; String stableIdStr = values[2]; int stableId = getIntStableId(stableIdStr); String HGVS_c = values[3]; String HGVS_p = values[4]; float polyphenHumdiv = FormatManager.getFloat(values[5]); float polyphenHumvar = FormatManager.getFloat(values[6]); // --effect filter applied // --polyphen-humdiv filter applied // --gene or --gene-boundary filter applied if (EffectManager.isEffectContained(effect) && PolyphenManager.isValid(polyphenHumdiv, effect, AnnotationLevelFilterCommand.polyphenHumdiv) && GeneManager.isValid(geneName, chr, pos)) { if (mostDamagingAnnotation.effect == null) { mostDamagingAnnotation.effect = effect; mostDamagingAnnotation.stableId = stableId; mostDamagingAnnotation.HGVS_c = HGVS_c; mostDamagingAnnotation.HGVS_p = HGVS_p; mostDamagingAnnotation.geneName = geneName; } StringJoiner geneTranscriptSJ = new StringJoiner("|"); geneTranscriptSJ.add(effect); geneTranscriptSJ.add(geneName); geneTranscriptSJ.add(stableIdStr); geneTranscriptSJ.add(HGVS_c); geneTranscriptSJ.add(HGVS_p); geneTranscriptSJ.add(FormatManager.getFloat(polyphenHumdiv)); geneTranscriptSJ.add(FormatManager.getFloat(polyphenHumvar)); allGeneTranscriptSJ.add(geneTranscriptSJ.toString()); if (!geneList.contains(geneName)) { geneList.add(geneName); } mostDamagingAnnotation.polyphenHumdiv = MathManager.max(mostDamagingAnnotation.polyphenHumdiv, polyphenHumdiv); mostDamagingAnnotation.polyphenHumvar = MathManager.max(mostDamagingAnnotation.polyphenHumvar, polyphenHumvar); boolean isCCDS = TranscriptManager.isCCDSTranscript(chr, stableId); if (isCCDS) { mostDamagingAnnotation.polyphenHumdivCCDS = MathManager.max(mostDamagingAnnotation.polyphenHumdivCCDS, polyphenHumdiv); mostDamagingAnnotation.polyphenHumvarCCDS = MathManager.max(mostDamagingAnnotation.polyphenHumvarCCDS, polyphenHumvar); mostDamagingAnnotation.hasCCDS = true; } } } } private int getIntStableId(String value) { if(value.equals(Data.STRING_NA)) { return Data.INTEGER_NA; }else { return Integer.valueOf(value.substring(4)); // remove ENST } } public boolean isValid() throws SQLException { if (VariantLevelFilterCommand.isExcludeMultiallelicVariant && VariantManager.isMultiallelicVariant(chr, pos)) { // exclude Multiallelic site > 1 variant return false; } else if (VariantLevelFilterCommand.isExcludeMultiallelicVariant2 && VariantManager.isMultiallelicVariant2(chr, pos)) { // exclude Multiallelic site > 2 variants return false; } return exac.isValid() && gnomADExome.isValid() && gnomADGenome.isValid() && !geneList.isEmpty() && CohortLevelFilterCommand.isMaxLooAFValid(looAF) && isMaxQcFailSampleValid(); } private boolean isMaxQcFailSampleValid() { int totalQCFailSample = qcFailSample[Index.CASE] + qcFailSample[Index.CTRL]; return CohortLevelFilterCommand.isMaxQcFailSampleValid(totalQCFailSample); } public String getVariantID() { return variantID; } public CSVRecord getRecord() { return record; } public Annotation getMostDamagingAnnotation() { return mostDamagingAnnotation; } public String getAllAnnotation() { return allGeneTranscriptSJ.toString(); } public List<String> getGeneList() { return geneList; } public boolean isSNV() { return isSNV; } }
package org.carewebframework.rpms.api.terminology; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.carewebframework.common.StrUtil; import org.carewebframework.vista.api.util.VistAUtil; import org.carewebframework.vista.mbroker.BrokerSession; import org.carewebframework.vista.mbroker.FMDate; /** * Static convenience class for accessing terminology services. */ public class TermUtil { private static final String BMX_DELIMITER = "\036"; private static final String BMX_EOD = "\037"; private static final Map<String, TermSubset> subsets = new HashMap<>(); private static final BrokerSession brokerSession = VistAUtil.getBrokerSession(); public static TermSubset getSubset(String id) { if (id == null) { id = "36"; // SNOMED-CT is the default } if (!subsets.containsKey(id)) { initSubset(id); } return subsets.get(id); } private static void initSubset(String id) { synchronized (subsets) { if (!subsets.containsKey(id)) { TermSubset subset = new TermSubset(id, callBMXRPC("BSTS GET SUBSET LIST", id)); subsets.put(id, subset); } } } /** * Perform lookup of SNOMED CT terms. * * @param text Text of term to lookup. * @param synonym If true, lookup synonyms. Otherwise, lookup only preferred terms. * @param date Reference date for lookup. * @param max Maximum hits to return. * @param filters Subset filters to apply. * @return List of matching terms. */ public static List<TermMatch> lookupSCT(String text, boolean synonym, FMDate date, Long max, String... filters) { text = text.replace("|^", ""); String filter = filters == null ? "" : StrUtil.fromList(Arrays.asList(filters), "~"); String searchType = synonym ? "S" : "F"; String dateStr = date == null ? "" : date.getFMDate(); List<String> results = callBMXRPC("BSTS SNOMED SEARCH", text, searchType, "", filter, dateStr, max); List<TermMatch> matches = new ArrayList<>(results.size()); // Note, ignore first entry as it is a fixed header. for (int i = 1; i < results.size(); i++) { matches.add(new TermMatch(results.get(i))); } return matches; } /** * Call a BMX-style RPC. * * @param rpcName Remote procedure name. * @param args Argument list. * @return Returned list data. */ private static List<String> callBMXRPC(String rpcName, Object... args) { String arg = args == null ? null : StrUtil.toDelimitedStr("|", args); List<String> result = StrUtil.toList(brokerSession.callRPC(rpcName, arg), BMX_DELIMITER); int last = result.size() - 1; if (last >= 0 && BMX_EOD.equals(result.get(last))) { result.remove(last); } return result; } /** * Enforce static class. */ private TermUtil() { } }
package gov.nasa.jpl.mbee.ems; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import gov.nasa.jpl.graphs.DirectedEdgeVector; import gov.nasa.jpl.graphs.DirectedGraphHashSet; import gov.nasa.jpl.graphs.algorithms.TopologicalSort; import gov.nasa.jpl.mbee.ems.validation.PropertyValueType; import gov.nasa.jpl.mbee.lib.Debug; import gov.nasa.jpl.mbee.lib.Utils; import org.apache.log4j.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.openapi.uml.ModelElementsManager; import com.nomagic.magicdraw.openapi.uml.ReadOnlyElementException; import com.nomagic.uml2.ext.jmi.helpers.ModelHelper; import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper; import com.nomagic.uml2.ext.magicdraw.classes.mdassociationclasses.AssociationClass; import com.nomagic.uml2.ext.magicdraw.classes.mddependencies.Dependency; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKind; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKindEnum; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Association; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Classifier; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.DirectedRelationship; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ElementValue; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Expression; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Generalization; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceValue; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralBoolean; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralInteger; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralReal; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralString; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralUnlimitedNatural; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.OpaqueExpression; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Package; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Type; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification; import com.nomagic.uml2.ext.magicdraw.commonbehaviors.mdsimpletime.DurationInterval; import com.nomagic.uml2.ext.magicdraw.commonbehaviors.mdsimpletime.TimeExpression; import com.nomagic.uml2.ext.magicdraw.commonbehaviors.mdsimpletime.TimeInterval; import com.nomagic.uml2.ext.magicdraw.compositestructures.mdinternalstructures.ConnectableElement; import com.nomagic.uml2.ext.magicdraw.compositestructures.mdinternalstructures.Connector; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; import com.nomagic.uml2.impl.ElementsFactory; public class ImportUtility { public static Logger log = Logger.getLogger(ImportUtility.class); public static boolean outputError = true; public static final Set<String> VALUESPECS = new HashSet<String>(Arrays.asList( new String[] {"LiteralInteger", "LiteralString", "LiteralBoolean", "LiteralUnlimitedNatural", "Expression", "InstanceValue", "ElementValue", "OpaqueExpression", "Interval", "LiteralReal", "Duration", "DurationInterval", "TimeInterval", "TimeExpression", "StringExpression"} )); public static Map<String, List<JSONObject>> getCreationOrder(List<JSONObject> newElements) { Map<String, List<JSONObject>> returns = new HashMap<String, List<JSONObject>>(); DirectedGraphHashSet<JSONObject, DirectedEdgeVector<JSONObject>> graph = new DirectedGraphHashSet<JSONObject, DirectedEdgeVector<JSONObject>>(); Map<String, JSONObject> id2ob = new HashMap<String, JSONObject>(); for (JSONObject ob: newElements) { String sysmlid = (String)ob.get("sysmlid"); if (sysmlid == null) continue; id2ob.put(sysmlid, ob); graph.addVertex(ob); } Map<String, JSONObject> fail = new HashMap<String, JSONObject>(); for (JSONObject ob: newElements) { String sysmlid = (String)ob.get("sysmlid"); String ownerid = (String)ob.get("owner"); Element newE = ExportUtility.getElementFromID(sysmlid); Element ownerE = ExportUtility.getElementFromID(ownerid); if (ownerE == null && !id2ob.containsKey(ownerid)) { fail.put(sysmlid, ob); continue; } if (newE != null || ownerE != null) continue; JSONObject newj = id2ob.get(sysmlid); JSONObject ownerj = id2ob.get(ownerid); if (newj != null && ownerj != null) graph.addEdge(newj, ownerj); } SortedSet<JSONObject> reverse = (new TopologicalSort()).topological_sort(graph); List<JSONObject> toposort = new ArrayList<JSONObject>(reverse); Set<JSONObject> fails = new HashSet<JSONObject>(); fails.addAll(fail.values()); int size = fails.size()-1; while (fails.size() > size) { size = fails.size(); Set<DirectedEdgeVector<JSONObject>> edges = graph.findEdgesWithTargetVertices(fails); for (DirectedEdgeVector<JSONObject> edge: edges) { fails.add(edge.getSourceVertex()); } } toposort.removeAll(fails); returns.put("create", toposort); returns.put("fail", new ArrayList<JSONObject>(fails)); return returns; } public static Element createElement(JSONObject ob, boolean updateRelations) throws ImportException { Project project = Application.getInstance().getProject(); ElementsFactory ef = project.getElementsFactory(); project.getCounter().setCanResetIDForObject(true); String ownerId = (String) ob.get("owner"); if (ownerId == null || ownerId.isEmpty()) return null; if (ExportUtility.getElementFromID(ownerId) == null) return null; // For all new elements the should be the following fields // should be present: name, owner, and documentation String sysmlID = (String) ob.get("sysmlid"); Element existing = ExportUtility.getElementFromID(sysmlID); if (existing != null && !updateRelations) return existing; //maybe jms feedback JSONObject specialization = (JSONObject) ob.get("specialization"); String elementType = "Element"; if (specialization != null) { elementType = (String) specialization.get("type"); } Element newE = existing; try { if (elementType.equalsIgnoreCase("view")) { if (newE == null) { Class view = ef.createClassInstance(); newE = view; } Stereotype sysmlView = Utils.getViewClassStereotype(); StereotypesHelper.addStereotype(newE, sysmlView); setViewConstraint(newE, specialization); } else if (elementType.equalsIgnoreCase("viewpoint")) { if (newE == null) { Class view = ef.createClassInstance(); newE = view; } Stereotype sysmlView = Utils.getViewpointStereotype(); StereotypesHelper.addStereotype(newE, sysmlView); } else if (elementType.equalsIgnoreCase("Property")) { JSONArray vals = (JSONArray) specialization.get("value"); Boolean isSlot = (Boolean) specialization.get("isSlot"); if ((isSlot != null) && (isSlot == true)) { if (newE == null) { Slot newSlot = ef.createSlotInstance(); newE = newSlot; } if (specialization.containsKey("value")) setSlotValues((Slot)newE, vals); } else { if (newE == null) { Property newProperty = ef.createPropertyInstance(); newE = newProperty; } if (specialization.containsKey("value")) setPropertyDefaultValue((Property)newE, vals); if (specialization.containsKey("propertyType")) setProperty((Property)newE, specialization); } } else if (elementType.equalsIgnoreCase("Dependency") || elementType.equalsIgnoreCase("Expose") || elementType.equalsIgnoreCase("DirectedRelationship") || elementType.equalsIgnoreCase("Characterizes")) { if (newE == null) { Dependency newDependency = ef.createDependencyInstance(); newE = newDependency; } setRelationshipEnds((Dependency)newE, specialization); if (elementType.equalsIgnoreCase("Characterizes")) { Stereotype character = Utils.getCharacterizesStereotype(); StereotypesHelper.addStereotype((Dependency)newE, character); } else if (elementType.equalsIgnoreCase("Expose")) { Stereotype expose = Utils.getExposeStereotype(); StereotypesHelper.addStereotype((Dependency)newE, expose); } } else if (elementType.equalsIgnoreCase("Generalization") || elementType.equalsIgnoreCase("Conform")) { if (newE == null) { Generalization newGeneralization = ef.createGeneralizationInstance(); newE = newGeneralization; } setRelationshipEnds((Generalization)newE, specialization); if (elementType.equalsIgnoreCase("Conform")) { Stereotype conform = Utils.getSysML14ConformsStereotype(); StereotypesHelper.addStereotype((Generalization)newE, conform); } } else if (elementType.equalsIgnoreCase("Package")) { if (newE == null) { Package newPackage = ef.createPackageInstance(); newE = newPackage; } } else if (elementType.equalsIgnoreCase("Constraint")) { if (newE == null) { Constraint c = ef.createConstraintInstance(); newE = c; } setConstraintSpecification((Constraint)newE, specialization); } else if (elementType.equalsIgnoreCase("Product")) { if (newE == null) { Class prod = ef.createClassInstance(); newE = prod; } Stereotype product = Utils.getDocumentStereotype(); StereotypesHelper.addStereotype(newE, product); setViewConstraint(newE, specialization); } else if (elementType.equalsIgnoreCase("Association")) { if (newE == null) { Association ac = ef.createAssociationInstance(); newE = ac; } try { setAssociation((Association)newE, specialization); } catch (Exception ex) { if (newE instanceof AssociationClass && updateRelations) { newE.dispose(); return null; } } } else if (elementType.equalsIgnoreCase("Connector")) { if (newE == null) { Connector conn = ef.createConnectorInstance(); newE = conn; } setConnectorEnds((Connector)newE, specialization); } else if (elementType.equalsIgnoreCase("InstanceSpecification")) { if (newE == null) { InstanceSpecification is = ef.createInstanceSpecificationInstance(); newE = is; } setInstanceSpecification((InstanceSpecification)newE, specialization); } else if (newE == null) { Class newElement = ef.createClassInstance(); newE = newElement; } setName(newE, ob); setOwner(newE, ob); setDocumentation(newE, ob); setOwnedAttribute(newE, ob); newE.setID(sysmlID); } catch (ImportException ex) { setName(newE, ob); setOwner(newE, ob); setDocumentation(newE, ob); newE.setID(sysmlID); throw ex; } return newE; } public static void updateElement(Element e, JSONObject o) throws ImportException { setName(e, o); setDocumentation(e, o); setOwnedAttribute(e, o); JSONObject spec = (JSONObject)o.get("specialization"); if (spec != null) { try { String type = (String)spec.get("type"); if (type != null && type.equals("Property") && e instanceof Property) { setProperty((Property)e, spec); if (spec.containsKey("value")) setPropertyDefaultValue((Property)e, (JSONArray)spec.get("value")); // if (spec.containsKey("propertyType")) // setProperty((Property)e, spec); } if (type != null && type.equals("Property") && e instanceof Slot && spec.containsKey("value")) setSlotValues((Slot)e, (JSONArray)spec.get("value")); if (type != null && e instanceof DirectedRelationship) setRelationshipEnds((DirectedRelationship)e, spec); if (type != null && e instanceof Constraint && type.equals("Constraint")) setConstraintSpecification((Constraint)e, spec); if (type != null && e instanceof Connector && type.equals("Connector")) setConnectorEnds((Connector)e, spec); if (type != null && e instanceof Association && type.equals("Association")) { try { setAssociation((Association)e, spec); } catch (Exception ex) { } } if (type != null && e instanceof InstanceSpecification && type.equals("InstanceSpecification")) setInstanceSpecification((InstanceSpecification)e, spec); if (type != null && e instanceof Class && (type.equals("View") || type.equals("Product")) && spec.containsKey("contents")) setViewConstraint(e, spec); } catch (ReferenceException ex) { throw new ImportException(e, o, ex.getMessage()); } catch (ImportException ex) { throw new ImportException(e, o, ex.getMessage()); } } } public static void setViewConstraint(Element e, JSONObject specialization) throws ImportException { Constraint c = Utils.getViewConstraint(e); if (c == null) { c = Application.getInstance().getProject().getElementsFactory().createConstraintInstance(); c.setOwner(e); c.getConstrainedElement().add(e); } if (specialization.containsKey("contents")) { if (specialization.get("contents") == null) { c.setSpecification(null); } else { try { c.setSpecification(createValueSpec((JSONObject)specialization.get("contents"), c.getSpecification())); } catch (ReferenceException ex) { throw new ImportException(e, specialization, "View constraint: " + ex.getMessage()); } } } if (specialization.containsKey("displayedElements")) { JSONArray des = (JSONArray)specialization.get("displayedElements"); if (des != null) StereotypesHelper.setStereotypePropertyValue(e, Utils.getViewClassStereotype(), "elements", des.toJSONString()); } } public static void setName(Element e, JSONObject o) { if (!o.containsKey("name")) return; String name = (String)o.get("name"); setName(e, name); } public static void setName(Element e, String name) { if (e instanceof NamedElement && name != null) ((NamedElement)e).setName(ExportUtility.unescapeHtml(name)); } public static void setOwner(Element e, JSONObject o) { if (!o.containsKey("owner")) return; String ownerId = (String) o.get("owner"); if ((ownerId == null) || (ownerId.isEmpty())) { Utils.guilog("[ERROR] Owner not specified for mms sync add"); return; } Element owner = ExportUtility.getElementFromID(ownerId); if (owner == null) { if (outputError) Utils.guilog("[ERROR] Owner not found for mms sync add"); return; } e.setOwner(owner); } public static void setDocumentation(Element e, JSONObject o) { if (!o.containsKey("documentation")) return; String doc = (String)o.get("documentation"); setDocumentation(e, doc); } public static void setDocumentation(Element e, String doc) { if (doc != null) ModelHelper.setComment(e, Utils.addHtmlWrapper(doc)); } public static void setOwnedAttribute(Element e, JSONObject o) { if (e instanceof Class && o.containsKey("ownedAttribute")) { Class c = (Class)e; JSONArray attr = (JSONArray)o.get("ownedAttribute"); List<Property> ordered = new ArrayList<Property>(); for (Object a: attr) { if (a instanceof String) { Element prop = ExportUtility.getElementFromID((String)a); if (prop instanceof Property) ordered.add((Property)prop); } } //if (ordered.size() < c.getOwnedAttribute().size()) // return; //some prevention of accidental model corruption, if property can be left without an owner c.getOwnedAttribute().clear(); c.getOwnedAttribute().addAll(ordered); } } public static void setInstanceSpecification(InstanceSpecification is, JSONObject specialization) throws ImportException { JSONObject spec = (JSONObject)specialization.get("instanceSpecificationSpecification"); if (spec != null) { try { is.setSpecification(createValueSpec(spec, is.getSpecification())); } catch (ReferenceException ex) { throw new ImportException(is, specialization, "Specification: " + ex.getMessage()); } } else is.setSpecification(null); if (specialization.containsKey("classifier")) { JSONArray classifier = (JSONArray)specialization.get("classifier"); if (classifier == null || classifier.isEmpty()) { log.info("[IMPORT/AUTOSYNC CORRUPTION PREVENTED] instance spec classifier is empty: " + is.getID()); return; } List<Classifier> newClassifiers = new ArrayList<Classifier>(); for (Object id: classifier) { Element e = ExportUtility.getElementFromID((String)id); if (e instanceof Classifier) { newClassifiers.add((Classifier)e); } else { throw new ImportException(is, specialization, (String)id + " is not a classifier"); } } is.getClassifier().clear(); is.getClassifier().addAll(newClassifiers); } } public static void setRelationshipEnds(DirectedRelationship dr, JSONObject specialization) { String sourceId = (String) specialization.get("source"); String targetId = (String) specialization.get("target"); Element source = ExportUtility.getElementFromID(sourceId); Element target = ExportUtility.getElementFromID(targetId); if (source != null && target != null) { ModelHelper.setSupplierElement(dr, target); ModelHelper.setClientElement(dr, source); } else { log.info("[IMPORT/AUTOSYNC CORRUPTION PREVENTED] directed relationship missing source or target: " + dr.getID()); } } public static void setPropertyDefaultValue(Property p, JSONArray values) throws ReferenceException { if (values != null && values.size() > 0) p.setDefaultValue(createValueSpec((JSONObject)values.get(0), p.getDefaultValue())); if (values != null && values.isEmpty()) p.setDefaultValue(null); } public static void setProperty(Property p, JSONObject spec) { // fix the property type here String ptype = (String)spec.get("propertyType"); if (ptype != null) { Type t = (Type)ExportUtility.getElementFromID(ptype); if (t != null) p.setType(t); else log.info("[IMPORT/AUTOSYNC PROPERTY TYPE] prevent mistaken null type"); //something bad happened } // set aggregation here AggregationKind aggr = null; if (spec.get("aggregation") != null) aggr = AggregationKindEnum.getByName(((String)spec.get("aggregation")).toLowerCase()); if (aggr != null) { p.setAggregation(aggr); } ElementsFactory ef = Application.getInstance().getProject().getElementsFactory(); Long spmin = (Long) spec.get("multiplicityMin"); if ( spmin != null){ try{ ValueSpecification pmin = p.getLowerValue(); if (pmin == null) pmin = ef.createLiteralIntegerInstance(); if (pmin instanceof LiteralInteger) ((LiteralInteger)pmin).setValue(spmin.intValue()); if (pmin instanceof LiteralUnlimitedNatural) ((LiteralUnlimitedNatural)pmin).setValue(spmin.intValue()); p.setLowerValue(pmin); } catch (NumberFormatException en){} } Long spmax = (Long) spec.get("multiplicityMax"); if ( spmax != null){ try{ ValueSpecification pmax = p.getUpperValue(); if (pmax == null) pmax = ef.createLiteralUnlimitedNaturalInstance(); if (pmax instanceof LiteralInteger) ((LiteralInteger)pmax).setValue(spmax.intValue()); if (pmax instanceof LiteralUnlimitedNatural) ((LiteralUnlimitedNatural)pmax).setValue(spmax.intValue()); p.setUpperValue(pmax); } catch (NumberFormatException en){} } JSONArray redefineds = (JSONArray) spec.get("redefines"); Collection<Property> redefinedps = p.getRedefinedProperty(); if (redefineds != null && redefineds.size() != 0) { //for now prevent accidental removal of things in case server doesn't have the right reference redefinedps.clear(); for (Object redefined: redefineds){ Property redefinedp = (Property) ExportUtility.getElementFromID((String)redefined); if (redefinedp != null) redefinedps.add(redefinedp); } } } public static void setPropertyType(Property p, Type type) { p.setType(type); } public static void setSlotValues(Slot s, JSONArray values) throws ReferenceException { if (values == null) return; List<ValueSpecification> originals = new ArrayList<ValueSpecification>(s.getValue()); List<ValueSpecification> origs = new ArrayList<ValueSpecification>(originals); try { s.getValue().clear(); for (Object o: values) { ValueSpecification vs = null; if (originals.size() > 0) vs = createValueSpec((JSONObject)o, originals.remove(0)); else vs = createValueSpec((JSONObject)o, null); if (vs != null) s.getValue().add(vs); } } catch (ReferenceException ex) { s.getValue().clear(); s.getValue().addAll(origs); throw ex; } } public static void setConstraintSpecification(Constraint c, JSONObject spec) throws ImportException { if (!spec.containsKey("specification")) return; JSONObject sp = (JSONObject)spec.get("specification"); if (sp != null) { try { c.setSpecification(createValueSpec(sp, c.getSpecification())); } catch (ReferenceException ex) { throw new ImportException(c, spec, "Constraint Specification: " + ex.getMessage()); } } } public static void setConnectorEnds(Connector c, JSONObject spec) { JSONArray webSourcePath = (JSONArray)spec.get("sourcePath"); JSONArray webTargetPath = (JSONArray)spec.get("targetPath"); String webSource = null; String webTarget = null; if (webSourcePath != null && !webSourcePath.isEmpty()) webSource = (String)webSourcePath.remove(webSourcePath.size()-1); if (webTargetPath != null && !webTargetPath.isEmpty()) webTarget = (String)webTargetPath.remove(webTargetPath.size()-1); Element webSourceE = ExportUtility.getElementFromID(webSource); Element webTargetE = ExportUtility.getElementFromID(webTarget); if (webSourceE instanceof ConnectableElement && webTargetE instanceof ConnectableElement) { c.getEnd().get(0).setRole((ConnectableElement)webSourceE); c.getEnd().get(1).setRole((ConnectableElement)webTargetE); } else { log.info("[IMPORT/AUTOSYNC CORRUPTION PREVENTED] connector missing source or target: " + c.getID()); } Stereotype nestedend = StereotypesHelper.getStereotype(Application.getInstance().getProject(), "NestedConnectorEnd"); if (webSourcePath != null && !webSourcePath.isEmpty()) { List<Property> evs = createPropertyPath((List<String>)webSourcePath); StereotypesHelper.setStereotypePropertyValue(c.getEnd().get(0), nestedend, "propertyPath", evs); } if (webTargetPath != null && !webTargetPath.isEmpty()) { List<Property> evs = createPropertyPath((List<String>)webTargetPath); StereotypesHelper.setStereotypePropertyValue(c.getEnd().get(1), nestedend, "propertyPath", evs); } String type = (String)spec.get("connectorType"); Element asso = ExportUtility.getElementFromID(type); if (asso instanceof Association) c.setType((Association)asso); } public static void setAssociation(Association a, JSONObject spec) throws ImportException { String webSourceId = (String)spec.get("source"); String webTargetId = (String)spec.get("target"); Element webSource = ExportUtility.getElementFromID(webSourceId); Element webTarget = ExportUtility.getElementFromID(webTargetId); Property modelSource = null; Property modelTarget = null; // String webSourceA = (String)spec.get("sourceAggregation"); // String webTargetA = (String)spec.get("targetAggregation"); List<Property> todelete = new ArrayList<Property>(); int i = 0; if (webSource == null || webTarget == null) { log.info("[IMPORT/AUTOSYNC CORRUPTION PREVENTED] association missing source or target: " + a.getID()); throw new ImportException(a, spec, "Association missing ends"); } for (Property end: a.getMemberEnd()) { if (end != webSource && end != webTarget) todelete.add(end); else if (i == 0) { modelSource = end; } else { modelTarget = end; } i++; } /*for (Property p: todelete) { //this used to be needed to prevent model corruption in 2.1? not needed in 18.0 (2.2)? corruption changes if asso is new or existing try { ModelElementsManager.getInstance().removeElement(p); //TODO propagate to alfresco? } catch (ReadOnlyElementException e) { e.printStackTrace(); } }*/ if (modelSource == webSource && modelTarget == webTarget) return; //don't need to mess with it a.getMemberEnd().clear(); //if (modelSource == null && webSource instanceof Property) { a.getMemberEnd().add(0, (Property)webSource); modelSource = (Property)webSource; //if (modelTarget == null && webTarget instanceof Property) { a.getMemberEnd().add((Property)webTarget); modelTarget = (Property)webTarget; // if (modelSource != null && webSourceA != null) { // AggregationKindEnum agg = AggregationKindEnum.getByName(webSourceA.toLowerCase()); // modelSource.setAggregation(agg); // if (modelTarget != null && webTargetA != null) { // AggregationKindEnum agg = AggregationKindEnum.getByName(webTargetA.toLowerCase()); // modelTarget.setAggregation(agg); } public static List<ValueSpecification> createElementValues(List<String> ids) { List<ValueSpecification> result = new ArrayList<ValueSpecification>(); ElementsFactory ef = Application.getInstance().getProject().getElementsFactory(); for (String id: ids) { Element e = ExportUtility.getElementFromID(id); if (e == null) continue; ElementValue ev = ef.createElementValueInstance(); ev.setElement(e); result.add(ev); } return result; } public static List<Property> createPropertyPath(List<String> ids) { List<Property> result = new ArrayList<Property>(); for (String id: ids) { Element e = ExportUtility.getElementFromID(id); if (e == null || !(e instanceof Property)) continue; result.add((Property)e); } return result; } public static ValueSpecification createValueSpec(JSONObject o, ValueSpecification v) throws ReferenceException { ElementsFactory ef = Application.getInstance().getProject().getElementsFactory(); String valueType = (String)o.get("type"); ValueSpecification newval = null; PropertyValueType propValueType = PropertyValueType.valueOf(valueType); switch ( propValueType ) { case LiteralString: if (v != null && v instanceof LiteralString) newval = v; else newval = ef.createLiteralStringInstance(); String s = (String)o.get("string"); if (s != null) ((LiteralString)newval).setValue(Utils.addHtmlWrapper(s)); break; case LiteralInteger: if (v != null && v instanceof LiteralInteger) newval = v; else newval = ef.createLiteralIntegerInstance(); Long l = (Long)o.get("integer"); if (l != null) ((LiteralInteger)newval).setValue(l.intValue()); break; case LiteralBoolean: if (v != null && v instanceof LiteralBoolean) newval = v; else newval = ef.createLiteralBooleanInstance(); Boolean b = (Boolean)o.get("boolean"); if (b != null) ((LiteralBoolean)newval).setValue(b); break; case LiteralUnlimitedNatural: if (v != null && v instanceof LiteralUnlimitedNatural) newval = v; else newval = ef.createLiteralUnlimitedNaturalInstance(); Long ll = (Long)o.get("naturalValue"); if (ll != null) ((LiteralUnlimitedNatural)newval).setValue(ll.intValue()); break; case LiteralReal: Double value; if (o.get("double") instanceof Long) value = Double.parseDouble(((Long)o.get("double")).toString()); else value = (Double)o.get("double"); if (v != null && v instanceof LiteralReal) newval = v; else newval = ef.createLiteralRealInstance(); if (value != null) ((LiteralReal)newval).setValue(value); break; case ElementValue: Element find = ExportUtility.getElementFromID((String)o.get("element")); if (find == null) { if (outputError) { //Utils.guilog("Element with id " + o.get("element") + " not found!"); throw new ReferenceException(v, o, "Element with id " + o.get("element") + " for ElementValue not found!"); } break; } if (v != null && v instanceof ElementValue) newval = v; else newval = ef.createElementValueInstance(); ((ElementValue)newval).setElement(find); break; case InstanceValue: Element findInst = ExportUtility.getElementFromID((String)o.get("instance")); if (findInst == null){ if (outputError) { //Utils.guilog("Element with id " + o.get("instance") + " not found!"); throw new ReferenceException(v, o, "Instance with id " + o.get("instance") + " for InstanceValue not found!"); } break; } if (!(findInst instanceof InstanceSpecification)) { if (outputError) { //Utils.guilog("Element with id " + o.get("instance") + " is not an instance spec, cannot be put into an InstanceValue."); throw new ReferenceException(v, o, "Element with id " + o.get("instance") + " is not an instance spec, cannot be put into an InstanceValue."); } break; } if (v != null && v instanceof InstanceValue) newval = v; else newval = ef.createInstanceValueInstance(); ((InstanceValue)newval).setInstance((InstanceSpecification)findInst); break; case Expression: if (v != null && v instanceof Expression) newval = v; else newval = ef.createExpressionInstance(); if (!o.containsKey("operand") || !(o.get("operand") instanceof JSONArray)) break; ((Expression)newval).getOperand().clear(); for (Object op: (JSONArray)o.get("operand")) { ValueSpecification operand = createValueSpec((JSONObject)op, null); if (operand != null) ((Expression)newval).getOperand().add(operand); } break; case OpaqueExpression: if (v != null && v instanceof OpaqueExpression) newval = v; else newval = ef.createOpaqueExpressionInstance(); if (!o.containsKey("expressionBody") || !(o.get("expressionBody") instanceof JSONArray)) break; ((OpaqueExpression)newval).getBody().clear(); for (Object op: (JSONArray)o.get("expressionBody")) { if (op instanceof String) ((OpaqueExpression)newval).getBody().add((String)op); } break; case TimeExpression: if (v != null && v instanceof TimeExpression) newval = v; else newval = ef.createTimeExpressionInstance(); break; case DurationInterval: if (v != null && v instanceof DurationInterval) newval = v; else newval = ef.createDurationIntervalInstance(); break; case TimeInterval: if (v != null && v instanceof TimeInterval) newval = v; else newval = ef.createTimeIntervalInstance(); break; default: log.error("Bad PropertyValueType: " + valueType); }; return newval; } }
package fr.openwide.core.spring.notification.model; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.IDN; import java.nio.charset.Charset; import java.util.Collection; import java.util.List; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.collect.FluentIterable; import fr.openwide.core.spring.util.StringUtils; public class NotificationRecipient implements Serializable { private static final long serialVersionUID = -1021739893358432630L; private static final Logger LOGGER = LoggerFactory.getLogger(NotificationRecipient.class); private static final Function<String, NotificationRecipient> EMAIL_TO_NOTIFICATION_RECIPIENT_FUNCTION = new Function<String, NotificationRecipient>() { @Override public NotificationRecipient apply(String email) { if (!StringUtils.hasText(email)) { return null; } try { return NotificationRecipient.of(email); } catch (AddressException e) { LOGGER.warn(String.format("Ignoring address %1$s", email), e); return null; } } }; private InternetAddress address; private NotificationRecipient(InternetAddress address) { this.address = address; } public InternetAddress getAddress() { return address; } public static NotificationRecipient of(String email) throws AddressException { return new NotificationRecipient(normalizeEmail(email)); } public static List<NotificationRecipient> of(Collection<String> emails) { return FluentIterable.from(emails).transform(EMAIL_TO_NOTIFICATION_RECIPIENT_FUNCTION).filter(Predicates.notNull()).toList(); } public static NotificationRecipient of(INotificationRecipient recipient, Charset charset) throws AddressException { return new NotificationRecipient(getInternetAddress(recipient.getEmail(), recipient.getFullName(), charset)); } private static InternetAddress normalizeEmail(String email) throws AddressException { return getInternetAddress(email, null, null); } private static InternetAddress getInternetAddress(String email, String fullName, Charset charset) throws AddressException { if (!StringUtils.hasText(email)) { throw new AddressException("Email address is empty"); } List<String> emailParts = Splitter.on('@').omitEmptyStrings().trimResults().splitToList(StringUtils.lowerCase(email)); if (emailParts.size() != 2) { throw new AddressException("Invalid email address", email); } String idnEmail = emailParts.get(0) + '@' + IDN.toASCII(emailParts.get(1)); try { InternetAddress internetAddress = new InternetAddress(idnEmail, fullName, charset != null ? charset.name() : null); internetAddress.validate(); return internetAddress; } catch (UnsupportedEncodingException e) { throw new AddressException(String.format("Unable to parse the address %1$s <$2$s>: invalid encoding", fullName, idnEmail)); } } @Override public String toString() { if (address == null) { return "<null>"; } StringBuilder sb = new StringBuilder(); if (StringUtils.hasText(address.getPersonal())) { sb.append(address.getPersonal()).append(" "); } sb.append("<").append(address.getAddress()).append(">"); return sb.toString(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof NotificationRecipient)) { return false; } return address.equals(((NotificationRecipient) obj).getAddress()); } @Override public int hashCode() { return new HashCodeBuilder().append(address).toHashCode(); } }
package graphql.execution; import graphql.ExceptionWhileDataFetching; import graphql.ExecutionResult; import graphql.ExecutionResultImpl; import graphql.GraphQLException; import graphql.language.Field; import graphql.schema.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static graphql.introspection.Introspection.SchemaMetaFieldDef; import static graphql.introspection.Introspection.TypeMetaFieldDef; import static graphql.introspection.Introspection.TypeNameMetaFieldDef; public abstract class ExecutionStrategy { private static final Logger log = LoggerFactory.getLogger(ExecutionStrategy.class); protected ValuesResolver valuesResolver = new ValuesResolver(); protected FieldCollector fieldCollector = new FieldCollector(); public abstract ExecutionResult execute(ExecutionContext executionContext, GraphQLObjectType parentType, Object source, Map<String, List<Field>> fields); protected ExecutionResult resolveField(ExecutionContext executionContext, GraphQLObjectType parentType, Object source, List<Field> fields) { GraphQLFieldDefinition fieldDef = getFieldDef(executionContext.getGraphQLSchema(), parentType, fields.get(0)); if (fieldDef == null) return null; Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldDef.getArguments(), fields.get(0).getArguments(), executionContext.getVariables()); DataFetchingEnvironment environment = new DataFetchingEnvironment( source, argumentValues, executionContext.getRoot(), fields, fieldDef.getType(), parentType, executionContext.getGraphQLSchema() ); Object resolvedValue = null; try { resolvedValue = fieldDef.getDataFetcher().get(environment); } catch (Exception e) { log.info("Exception while fetching data", e); executionContext.addError(new ExceptionWhileDataFetching(e)); } return completeValue(executionContext, fieldDef.getType(), fields, resolvedValue); } protected ExecutionResult completeValue(ExecutionContext executionContext, GraphQLType fieldType, List<Field> fields, Object result) { if (fieldType instanceof GraphQLNonNull) { GraphQLNonNull graphQLNonNull = (GraphQLNonNull) fieldType; ExecutionResult completed = completeValue(executionContext, graphQLNonNull.getWrappedType(), fields, result); if (completed == null) { throw new GraphQLException("Cannot return null for non-nullable type: " + fields); } return completed; } else if (result == null) { return null; } else if (fieldType instanceof GraphQLList) { return completeValueForList(executionContext, (GraphQLList) fieldType, fields, (List<Object>) result); } else if (fieldType instanceof GraphQLScalarType) { return completeValueForScalar((GraphQLScalarType) fieldType, result); } else if (fieldType instanceof GraphQLEnumType) { return completeValueForEnum((GraphQLEnumType) fieldType, result); } GraphQLObjectType resolvedType; if (fieldType instanceof GraphQLInterfaceType) { resolvedType = resolveType((GraphQLInterfaceType) fieldType, result); } else if (fieldType instanceof GraphQLUnionType) { resolvedType = resolveType((GraphQLUnionType) fieldType, result); } else { resolvedType = (GraphQLObjectType) fieldType; } Map<String, List<Field>> subFields = new LinkedHashMap<>(); List<String> visitedFragments = new ArrayList<>(); for (Field field : fields) { if (field.getSelectionSet() == null) continue; fieldCollector.collectFields(executionContext, resolvedType, field.getSelectionSet(), visitedFragments, subFields); } // Calling this from the executionContext so that you can shift from the simple execution strategy for mutations // back to the desired strategy. return executionContext.getExecutionStrategy().execute(executionContext, resolvedType, result, subFields); } protected GraphQLObjectType resolveType(GraphQLInterfaceType graphQLInterfaceType, Object value) { GraphQLObjectType result = graphQLInterfaceType.getTypeResolver().getType(value); if (result == null) { throw new GraphQLException("could not determine type"); } return result; } protected GraphQLObjectType resolveType(GraphQLUnionType graphQLUnionType, Object value) { GraphQLObjectType result = graphQLUnionType.getTypeResolver().getType(value); if (result == null) { throw new GraphQLException("could not determine type"); } return result; } protected ExecutionResult completeValueForEnum(GraphQLEnumType enumType, Object result) { return new ExecutionResultImpl(enumType.getCoercing().coerce(result), null); } protected ExecutionResult completeValueForScalar(GraphQLScalarType scalarType, Object result) { return new ExecutionResultImpl(scalarType.getCoercing().coerce(result), null); } protected ExecutionResult completeValueForList(ExecutionContext executionContext, GraphQLList fieldType, List<Field> fields, List<Object> result) { List<Object> completedResults = new ArrayList<>(); for (Object item : result) { ExecutionResult completedValue = completeValue(executionContext, fieldType.getWrappedType(), fields, item); completedResults.add(completedValue != null ? completedValue.getData() : null); } return new ExecutionResultImpl(completedResults, null); } protected GraphQLFieldDefinition getFieldDef(GraphQLSchema schema, GraphQLObjectType parentType, Field field) { if (schema.getQueryType() == parentType) { if (field.getName().equals(SchemaMetaFieldDef.getName())) { return SchemaMetaFieldDef; } if (field.getName().equals(TypeMetaFieldDef.getName())) { return TypeMetaFieldDef; } } if (field.getName().equals(TypeNameMetaFieldDef.getName())) { return TypeNameMetaFieldDef; } GraphQLFieldDefinition fieldDefinition = parentType.getFieldDefinition(field.getName()); if (fieldDefinition == null) { throw new GraphQLException("unknown field " + field.getName()); } return fieldDefinition; } }
package info.danidiaz.util; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; /** * <p>An implementation of a doubly linked list.<p> * * <p>Some methods which the standard interfaces designate as optional have not * been implemented and throw {@link UnsupportedOperationException}. In * particular random-access methods, which are bound to be inefficient for * linked lists.</p> * */ public final class DoublyLinkedList<E> implements List<E>, Deque<E> { private Node<E> first; private Node<E> last; public DoublyLinkedList() { super(); } @Override public void addFirst(E e) { final Node<E> newFirst = new Node<>(e,first,null); if (isEmpty()) { last = newFirst; } else { first.setPrevious(newFirst); } first = newFirst; } @Override public void addLast(E e) { final Node<E> newLast = new Node<>(e,null,last); if (isEmpty()) { first = newLast; } else { last.setNext(newLast); } last = newLast; } @Override public Iterator<E> descendingIterator() { // TODO Auto-generated method stub return null; } @Override public E element() { if (isEmpty()) { throw new NoSuchElementException(); } return first.getValue(); } @Override public E getFirst() { return element(); } @Override public E getLast() { // TODO Auto-generated method stub return null; } @Override public boolean offer(E e) { // TODO Auto-generated method stub return false; } @Override public boolean offerFirst(E e) { // TODO Auto-generated method stub return false; } @Override public boolean offerLast(E e) { // TODO Auto-generated method stub return false; } @Override public E peek() { // TODO Auto-generated method stub return null; } @Override public E peekFirst() { // TODO Auto-generated method stub return null; } @Override public E peekLast() { // TODO Auto-generated method stub return null; } @Override public E poll() { // TODO Auto-generated method stub return null; } @Override public E pollFirst() { // TODO Auto-generated method stub return null; } @Override public E pollLast() { // TODO Auto-generated method stub return null; } @Override public E pop() { // TODO Auto-generated method stub return null; } @Override public void push(E e) { // TODO Auto-generated method stub } @Override public E remove() { // TODO Auto-generated method stub return null; } @Override public E removeFirst() { // TODO Auto-generated method stub return null; } @Override public boolean removeFirstOccurrence(Object o) { // TODO Auto-generated method stub return false; } @Override public E removeLast() { // TODO Auto-generated method stub return null; } @Override public boolean removeLastOccurrence(Object o) { // TODO Auto-generated method stub return false; } @Override public boolean add(E e) { // TODO Auto-generated method stub return false; } @Override public void add(int index, E element) { // TODO Auto-generated method stub } @Override public boolean addAll(Collection<? extends E> c) { // TODO Auto-generated method stub return false; } @Override public boolean addAll(int index, Collection<? extends E> c) { // TODO Auto-generated method stub return false; } @Override public void clear() { first = null; last = null; } @Override public boolean contains(Object o) { // TODO Auto-generated method stub return false; } @Override public boolean containsAll(Collection<?> c) { // TODO Auto-generated method stub return false; } @Override public E get(int index) { // TODO Auto-generated method stub return null; } @Override public int indexOf(Object o) { // TODO Auto-generated method stub return 0; } @Override public boolean isEmpty() { return first == null; } @Override public Iterator<E> iterator() { return listIterator(); } @Override public int lastIndexOf(Object o) { // TODO Auto-generated method stub return 0; } @Override public ListIterator<E> listIterator() { return new DoublyLinkedListIterator(); } @Override public ListIterator<E> listIterator(int index) { final ListIterator<E> iter = listIterator(); for (int i=0;i<index;i++) { if (i < index-1 && !iter.hasNext()) { throw new IndexOutOfBoundsException(); } } return iter; } /** Unsupported. * @throws UnsupportedOperationException always */ @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } /** Unsupported. * @throws UnsupportedOperationException always */ @Override public E remove(int index) { throw new UnsupportedOperationException(); } /** Unsupported. * @throws UnsupportedOperationException always */ @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** Unsupported. * @throws UnsupportedOperationException always */ @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** Unsupported. * @throws UnsupportedOperationException always */ @Override public E set(int index, E element) { throw new UnsupportedOperationException(); } @Override public int size() { final ListIterator<E> iter = listIterator(); while (iter.hasNext()) { iter.next(); } return iter.nextIndex(); } @Override public List<E> subList(int fromIndex, int toIndex) { // TODO Auto-generated method stub return null; } @Override public Object[] toArray() { return null; } @Override public <T> T[] toArray(T[] a) { // TODO Auto-generated method stub return null; } private final static class Node<E> { private E value; private Node<E> next; private Node<E> previous; public Node(E value, Node<E> next, Node<E> previous) { super(); this.value = value; this.next = next; this.previous = previous; } public Node<E> getNext() { return next; } public void setNext(Node<E> next) { this.next = next; } public Node<E> getPrevious() { return previous; } public void setPrevious(Node<E> previous) { this.previous = previous; } public E getValue() { return value; } public void setValue(E e) { value = e; } } private final class DoublyLinkedListIterator implements ListIterator<E> { private int index; private Node<E> iterPrevious; private Node<E> iterNext; // See https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#remove() // for an explanation of the necessity of keeping track of the last movement. private Node<E> lastMovement; public DoublyLinkedListIterator() { super(); this.index = 0; this.iterPrevious = null; this.iterNext = DoublyLinkedList.this.first; this.lastMovement = null; } @Override public void add(E arg0) { index++; final Node<E> node = new Node<E>(arg0,iterPrevious,iterNext); if (iterPrevious==null) { DoublyLinkedList.this.first = node; } if (iterNext==null) { DoublyLinkedList.this.last = node; } lastMovement = null; iterPrevious = node; } @Override public boolean hasNext() { return iterNext != null; } @Override public boolean hasPrevious() { return iterPrevious != null; } @Override public E next() { if (iterNext == null) { throw new NoSuchElementException(); } index++; final E result = iterNext.getValue(); lastMovement = iterNext; iterPrevious = iterNext; iterNext = iterNext.getNext(); return result; } @Override public int nextIndex() { return index; } @Override public E previous() { if (iterPrevious == null) { throw new NoSuchElementException(); } index final E result = iterPrevious.getValue(); lastMovement = iterPrevious; iterNext = iterPrevious; iterPrevious = iterPrevious.getPrevious(); return result; } @Override public int previousIndex() { return index-1; } @Override public void remove() { if (lastMovement == null) { throw new IllegalStateException(); } if (lastMovement == iterPrevious) { // last movement was forwards index iterPrevious = iterPrevious.getPrevious(); if (iterPrevious == null) { // removal put us an the beginning DoublyLinkedList.this.first = iterNext; } else { iterPrevious.setNext(iterNext); } if (iterNext == null) { // we were at end of list DoublyLinkedList.this.last = iterPrevious; } else { iterNext.setPrevious(iterPrevious); } } else if (lastMovement == iterNext) { // last movement was backwards iterNext = iterNext.getNext(); if (iterNext == null) { // removal put us at the end DoublyLinkedList.this.last = iterPrevious; } else { iterNext.setPrevious(iterPrevious); } if (iterPrevious == null) { // we were at the beginning of list DoublyLinkedList.this.first = iterNext; } else { iterPrevious.setNext(iterNext); } } lastMovement = null; } @Override public void set(E e) { if (lastMovement == null) { throw new IllegalStateException(); } lastMovement.setValue(e); } } }
package org.pentaho.cdf; import java.io.OutputStream; import java.lang.reflect.Method; import java.security.InvalidParameterException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DefaultValue; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.cdf.context.ContextEngine; import org.pentaho.cdf.environment.CdfEngine; import org.pentaho.cdf.render.CdfHtmlRenderer; import org.pentaho.cdf.render.XcdfRenderer; import org.pentaho.cdf.util.Parameter; import org.pentaho.platform.api.engine.IParameterProvider; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.engine.core.system.PentahoSystem; import pt.webdetails.cpf.SimpleContentGenerator; import pt.webdetails.cpf.Util; import pt.webdetails.cpf.audit.CpfAuditHelper; import pt.webdetails.cpf.utils.CharsetHelper; import pt.webdetails.cpf.utils.MimeTypes; public class CdfContentGenerator extends SimpleContentGenerator { private static final long serialVersionUID = 319509966121604058L; private static final Log logger = LogFactory.getLog( CdfContentGenerator.class ); private static final String PLUGIN_ID = CdfEngine.getEnvironment().getPluginId(); public String RELATIVE_URL; @Override public void createContent() throws Exception { IParameterProvider pathParams; IParameterProvider requestParams = null; String filePath = ""; String template = ""; logger.info( "[Timing] CDF content generator took over: " + ( new SimpleDateFormat( "HH:mm:ss.SSS" ) ).format( new Date() ) ); try { if ( parameterProviders.get( Parameter.PATH ) != null ) { pathParams = parameterProviders.get( Parameter.PATH ); requestParams = parameterProviders.get( IParameterProvider.SCOPE_REQUEST ); filePath = pathParams.getStringParameter( Parameter.PATH, null ); template = requestParams.getStringParameter( Parameter.TEMPLATE, null ); Object parameter = pathParams.getParameter( "httprequest" ); if ( parameter != null && ( (HttpServletRequest) parameter ).getContextPath() != null ) { RELATIVE_URL = ( (HttpServletRequest) parameter ).getContextPath(); } } else { RELATIVE_URL = CdfEngine.getEnvironment().getApplicationBaseUrl(); /* * If we detect an empty string, things will break. If we detect an absolute url, things will *probably* break. * In either of these cases, we'll resort to Catalina's context, and its getContextPath() method for better * results. */ if ( "".equals( RELATIVE_URL ) || RELATIVE_URL.matches( "^http: Object context = PentahoSystem.getApplicationContext().getContext(); Method getContextPath = context.getClass().getMethod( "getContextPath", null ); if ( getContextPath != null ) { RELATIVE_URL = getContextPath.invoke( context, null ).toString(); } } } if ( RELATIVE_URL.endsWith( "/" ) ) { RELATIVE_URL = RELATIVE_URL.substring( 0, RELATIVE_URL.length() - 1 ); } OutputStream out = getResponseOutputStream( MimeTypes.HTML ); // If callbacks is properly setup, we assume we're being called from another plugin if ( this.callbacks != null && callbacks.size() > 0 && HashMap.class.isInstance( callbacks.get( 0 ) ) ) { HashMap<String, Object> iface = (HashMap<String, Object>) callbacks.get( 0 ); out = (OutputStream) iface.get( "output" ); filePath = "/" + (String) iface.get( "method" ); this.userSession = this.userSession != null ? this.userSession : (IPentahoSession) iface.get( "usersession" ); } // make sure we have a workable state if ( outputHandler == null ) { error( Messages.getErrorString( "CdfContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER" ) ); //$NON-NLS-1$ throw new InvalidParameterException( Messages.getString( "CdfContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER" ) ); //$NON-NLS-1$ } else if ( out == null ) { error( Messages.getErrorString( "CdfContentGenerator.ERROR_0003_NO_OUTPUT_STREAM" ) ); //$NON-NLS-1$ throw new InvalidParameterException( Messages.getString( "CdfContentGenerator.ERROR_0003_NO_OUTPUT_STREAM" ) ); //$NON-NLS-1$ } if ( filePath.isEmpty() ) { logger.error( "Calling cdf with an empty method" ); } if ( requestParams != null ) { renderXcdfDashboard( out, requestParams, FilenameUtils.separatorsToUnix( filePath ), template ); } } catch ( Exception e ) { logger.error( "Error creating cdf content: ", e ); } } public void renderXcdfDashboard( final OutputStream out, final IParameterProvider requestParams, String xcdfFilePath, String defaultTemplate ) throws Exception { long start = System.currentTimeMillis(); UUID uuid = CpfAuditHelper.startAudit( PLUGIN_ID, xcdfFilePath, getObjectName(), this.userSession, this, requestParams ); try { XcdfRenderer renderer = new XcdfRenderer(); boolean success = renderer.determineDashboardTemplating( xcdfFilePath, defaultTemplate ); if ( success ) { String templatePath = Util.joinPath( FilenameUtils.getPath( xcdfFilePath ), renderer.getTemplate() ); renderHtmlDashboard( out, templatePath, renderer.getStyle(), renderer.getMessagesBaseFilename() ); setResponseHeaders( MimeTypes.HTML, 0, null ); } else { out.write( "Unable to render dashboard".getBytes( CharsetHelper.getEncoding() ) ); //$NON-NLS-1$ //$NON-NLS-2$ } long end = System.currentTimeMillis(); CpfAuditHelper.endAudit( PLUGIN_ID, xcdfFilePath, getObjectName(), this.userSession, this, start, uuid, end ); } catch ( Exception e ) { e.printStackTrace(); long end = System.currentTimeMillis(); CpfAuditHelper.endAudit( PLUGIN_ID, xcdfFilePath, getObjectName(), this.userSession, this, start, uuid, end ); throw e; } } public void renderHtmlDashboard( final OutputStream out, final String xcdfPath, String defaultTemplate, String dashboardsMessagesBaseFilename ) throws Exception { HttpServletRequest request = ( (HttpServletRequest) parameterProviders.get( Parameter.PATH ).getParameter( "httprequest" ) ); CdfHtmlRenderer renderer = new CdfHtmlRenderer(); renderer.execute( out, xcdfPath, defaultTemplate, dashboardsMessagesBaseFilename, Parameter.asHashMap( request ), userSession.getName() ); } public String getPluginName() { return PLUGIN_ID; } public String getContext( @QueryParam( Parameter.PATH ) @DefaultValue( StringUtils.EMPTY ) String path, @QueryParam( Parameter.ACTION ) @DefaultValue( StringUtils.EMPTY ) String action, @DefaultValue( StringUtils.EMPTY ) @QueryParam( Parameter.VIEW_ID ) String viewId, @Context HttpServletRequest servletRequest ) { return ContextEngine.getInstance().getContext( path, viewId, action, Parameter.asHashMap( servletRequest ) ); } }
package info.ganglia.jmxetric; import info.ganglia.gmetric4j.GMonitor; import java.lang.instrument.Instrumentation; // import java.util.logging.Logger; /** * JMXetricAgent is a JVM agent that will sample MBean attributes on a periodic basis, * publishing the value of those attributes to the Ganglia gmond process. * <br> * Use:<br> * <code>java -javaagent:path/jmxetric.jar=args yourmainclass</code> * <br> * Example:<br> * <code>java -javaagent:/opt/jmxetric_0_1/jmxetric.jar=host="localhost",port="8649",config=/opt/jmxetric_0_1/jmxetric.xml yourmainclass</code> * <br> * Arguments can be:<br> * <table> * <tr><th>Argument</th><th>Default</th><th>Description</th></tr> * <tr><td>host</td><td></td><td>Host address for ganglia</td></tr> * <tr><td>port</td><td></td><td>Port for ganglia</td></tr> * <tr><td>config</td><td>jmxetric.xml</td><td>Config file path</td></tr> * </table> */ public class JMXetricAgent extends GMonitor { // private static Logger log = // Logger.getLogger(JMXetricAgent.class.getName()); /** * A log running, trivial main method for test purposes * premain method * @param args Not used */ public static void main(String[] args) throws Exception { while( true ) { Thread.sleep(1000*60*5); System.out.println("Test wakeup"); } } /** * The JVM agent entry point * @param agentArgs * @param inst */ public static void premain(String agentArgs, Instrumentation inst) { System.out.println(STARTUP_NOTICE) ; JMXetricAgent a = null ; try { a = new JMXetricAgent(); XMLConfigurationService.configure(a, agentArgs); a.start(); } catch ( Exception ex ) { // log.severe("Exception starting JMXetricAgent"); ex.printStackTrace(); } } private static final String STARTUP_NOTICE="JMXetricAgent instrumented JVM, see https://github.com/ganglia/jmxetric"; }
package io.mycat.server.response; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Strings; import io.mycat.MycatServer; import io.mycat.backend.mysql.PacketUtil; import io.mycat.config.ErrorCode; import io.mycat.config.Fields; import io.mycat.config.MycatConfig; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.UserConfig; import io.mycat.net.mysql.EOFPacket; import io.mycat.net.mysql.FieldPacket; import io.mycat.net.mysql.ResultSetHeaderPacket; import io.mycat.net.mysql.RowDataPacket; import io.mycat.server.ServerConnection; import io.mycat.server.parser.ServerParse; import io.mycat.server.util.SchemaUtil; import io.mycat.util.StringUtil; /** * show tables impl * @author yanglixue * */ public class ShowTables { private static final int FIELD_COUNT = 1; private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT); private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT]; private static final EOFPacket eof = new EOFPacket(); private static final String SCHEMA_KEY = "schemaName"; private static final String LIKE_KEY = "like"; private static final Pattern pattern = Pattern.compile("^\\s*(SHOW)\\s+(TABLES)(\\s+(FROM)\\s+([a-zA-Z_0-9]+))?(\\s+(LIKE\\s+'(.*)'))?\\s*",Pattern.CASE_INSENSITIVE); /** * response method. * @param c */ public static void response(ServerConnection c,String stmt,int type) { String showSchemal= SchemaUtil.parseShowTableSchema(stmt) ; String cSchema =showSchemal==null? c.getSchema():showSchemal; SchemaConfig schema = MycatServer.getInstance().getConfig().getSchemas().get(cSchema); if(schema != null) { //schemashow tables mysql String node = schema.getDataNode(); if(!Strings.isNullOrEmpty(node)) { c.execute(stmt, ServerParse.SHOW); return; } } else { c.writeErrMessage(ErrorCode.ER_NO_DB_ERROR,"No database selected"); return; } //schemaSchemaConfig Map<String,String> parm = buildFields(c,stmt); java.util.Set<String> tableSet = getTableSet(c, parm); int i = 0; byte packetId = 0; header.packetId = ++packetId; fields[i] = PacketUtil.getField("Tables in " + parm.get(SCHEMA_KEY), Fields.FIELD_TYPE_VAR_STRING); fields[i++].packetId = ++packetId; eof.packetId = ++packetId; ByteBuffer buffer = c.allocate(); // write header buffer = header.write(buffer, c,true); // write fields for (FieldPacket field : fields) { buffer = field.write(buffer, c,true); } // write eof buffer = eof.write(buffer, c,true); // write rows packetId = eof.packetId; for (String name : tableSet) { RowDataPacket row = new RowDataPacket(FIELD_COUNT); row.add(StringUtil.encode(name.toLowerCase(), c.getCharset())); row.packetId = ++packetId; buffer = row.write(buffer, c,true); } // write last eof EOFPacket lastEof = new EOFPacket(); lastEof.packetId = ++packetId; buffer = lastEof.write(buffer, c,true); // post write c.write(buffer); } public static Set<String> getTableSet(ServerConnection c, String stmt) { Map<String,String> parm = buildFields(c,stmt); return getTableSet(c, parm); } private static Set<String> getTableSet(ServerConnection c, Map<String, String> parm) { TreeSet<String> tableSet = new TreeSet<String>(); MycatConfig conf = MycatServer.getInstance().getConfig(); Map<String, UserConfig> users = conf.getUsers(); UserConfig user = users == null ? null : users.get(c.getUser()); if (user != null) { Map<String, SchemaConfig> schemas = conf.getSchemas(); for (String name:schemas.keySet()){ if (null !=parm.get(SCHEMA_KEY) && parm.get(SCHEMA_KEY).toUpperCase().equals(name.toUpperCase()) ){ if(null==parm.get("LIKE_KEY")){ tableSet.addAll(schemas.get(name).getTables().keySet()); }else{ String p = "^" + parm.get("LIKE_KEY").replaceAll("%", ".*"); Pattern pattern = Pattern.compile(p,Pattern.CASE_INSENSITIVE); Matcher ma ; for (String tname : schemas.get(name).getTables().keySet()){ ma=pattern.matcher(tname); if(ma.matches()){ tableSet.add(tname); } } } } }; } return tableSet; } /** * build fields * @param c * @param stmt */ private static Map<String,String> buildFields(ServerConnection c,String stmt) { Map<String,String> map = new HashMap<String, String>(); Matcher ma = pattern.matcher(stmt); if(ma.find()){ String schemaName=ma.group(5); if (null !=schemaName && (!"".equals(schemaName)) && (!"null".equals(schemaName))){ map.put(SCHEMA_KEY, schemaName); } String like = ma.group(8); if (null !=like && (!"".equals(like)) && (!"null".equals(like))){ map.put("LIKE_KEY", like); } } if(null==map.get(SCHEMA_KEY)){ map.put(SCHEMA_KEY, c.getSchema()); } return map; } }
package kr.jm.utils.collections; import kr.jm.utils.datastructure.JMMap; import kr.jm.utils.helper.JMOptional; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; /** * The type Jm nested map. * * @param <K1> the type parameter * @param <K2> the type parameter * @param <V> the type parameter */ public class JMNestedMap<K1, K2, V> implements Map<K1, Map<K2, V>> { private Map<K1, Map<K2, V>> nestedMap; /** * Instantiates a new Jm nested map. */ public JMNestedMap() { this(false); } /** * Instantiates a new Jm nested map. * * @param map the map */ public JMNestedMap(Map<K1, Map<K2, V>> map) { this(false, map); } public JMNestedMap(boolean isWeak) { this.nestedMap = isWeak ? new WeakHashMap<>() : new ConcurrentHashMap<>(); } public JMNestedMap(boolean isWeak, Map<K1, Map<K2, V>> map) { this.nestedMap = isWeak ? new WeakHashMap<>(map) : new ConcurrentHashMap<>(map); } /* * (non-Javadoc) * * @see java.util.Map#size() */ @Override public int size() { return nestedMap.size(); } /* * (non-Javadoc) * * @see java.util.Map#isEmpty() */ @Override public boolean isEmpty() { return nestedMap.isEmpty(); } /* * (non-Javadoc) * * @see java.util.Map#containsKey(java.lang.Object) */ @Override public boolean containsKey(Object key) { return nestedMap.containsKey(key); } /* * (non-Javadoc) * * @see java.util.Map#containsValue(java.lang.Object) */ @Override public boolean containsValue(Object value) { return nestedMap.containsValue(value); } @Override public Map<K2, V> get(Object key) { return nestedMap.get(key); } @Override public Map<K2, V> put(K1 key, Map<K2, V> value) { return nestedMap.put(key, value); } @Override public Map<K2, V> remove(Object key) {return nestedMap.remove(key);} @Override public void putAll(Map<? extends K1, ? extends Map<K2, V>> m) { nestedMap.putAll(m); } @Override public void clear() {nestedMap.clear();} @Override public Set<K1> keySet() {return nestedMap.keySet();} @Override public Collection<Map<K2, V>> values() {return nestedMap.values();} @Override public Set<Entry<K1, Map<K2, V>>> entrySet() {return nestedMap.entrySet();} @Override public boolean equals(Object o) {return nestedMap.equals(o);} @Override public int hashCode() {return nestedMap.hashCode();} @Override public String toString() { return nestedMap.toString(); } /** * Put v. * * @param key1 the key 1 * @param key2 the key 2 * @param value the value * @return the v */ public V put(K1 key1, K2 key2, V value) { return getOrPutGetNew(key1).put(key2, value); } /** * Get v. * * @param key1 the key 1 * @param key2 the key 2 * @return the v */ public V get(K1 key1, K2 key2) { return JMOptional.getOptional(nestedMap, key1).map(map -> map.get(key2)) .orElse(null); } /** * Gets or put get new. * * @param key1 the key 1 * @param key2 the key 2 * @param newValueSupplier the new value supplier * @return the or put get new */ public V getOrPutGetNew(K1 key1, K2 key2, Supplier<V> newValueSupplier) { return JMMap .getOrPutGetNew(getOrPutGetNew(key1), key2, newValueSupplier); } /** * Gets or put get new. * * @param key1 the key 1 * @return the or put get new */ public Map<K2, V> getOrPutGetNew(K1 key1) { return getOrPutGetNew(key1, ConcurrentHashMap::new); } /** * Gets or put get new. * * @param key1 the key 1 * @param newMapSupplier the new map supplier * @return the or put get new */ public Map<K2, V> getOrPutGetNew(K1 key1, Supplier<Map<K2, V>> newMapSupplier) { return JMMap.getOrPutGetNew(nestedMap, key1, newMapSupplier); } }
package main.java.com.bag.client; import bftsmart.communication.client.ReplyReceiver; import bftsmart.reconfiguration.util.RSAKeyLoader; import bftsmart.tom.ServiceProxy; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.core.messages.TOMMessageType; import bftsmart.tom.util.TOMUtil; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import main.java.com.bag.operations.CreateOperation; import main.java.com.bag.operations.DeleteOperation; import main.java.com.bag.operations.IOperation; import main.java.com.bag.operations.UpdateOperation; import main.java.com.bag.util.*; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Class handling the client. */ public class TestClient extends ServiceProxy implements BAGClient, ReplyReceiver, Closeable, AutoCloseable { /** * Should the transaction runNetty in secure mode? */ private boolean secureMode = true; /** * The place the local config file is. This + the cluster id will contain the concrete cluster config location. */ private static final String LOCAL_CONFIG_LOCATION = "local%d/config"; /** * The place the global config files is. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * Sets to log reads, updates, deletes and node creations. */ private ArrayList<NodeStorage> readsSetNode; private ArrayList<RelationshipStorage> readsSetRelationship; private ArrayList<IOperation> writeSet; /** * Amount of responses. */ private int responses = 0; /** * Defines if the client is currently committing. */ private boolean isCommitting = false; /** * Local timestamp of the current transaction. */ private long localTimestamp = -1; /** * The id of the local server process the client is communicating with. */ private int serverProcess; /** * Lock object to let the thread wait for a read return. */ private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>(); /** * The last object in read queue. */ public static final Object FINISHED_READING = new Object(); /** * Id of the local cluster. */ private final int localClusterId; /** * Checks if its the first read of the client. */ private boolean firstRead = true; /** * The proxy to use during communication with the globalCluster. */ private ServiceProxy globalProxy; /** * Create a threadsafe version of kryo. */ private KryoFactory factory = () -> { Kryo kryo = new Kryo(); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); kryo.register(CreateOperation.class, 250); kryo.register(DeleteOperation.class, 300); kryo.register(UpdateOperation.class, 350); return kryo; }; public TestClient(final int processId, final int serverId, final int localClusterId) { super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId)); if(localClusterId != -1) { globalProxy = new ServiceProxy(100 + getProcessId(), "global/config"); } secureMode = true; this.serverProcess = serverId; this.localClusterId = localClusterId; initClient(); Log.getLogger().warn("Starting client " + processId); } /** * Initiates the client maps and registers necessary operations. */ private void initClient() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Get the blocking queue. * @return the queue. */ @Override public BlockingQueue<Object> getReadQueue() { return readQueue; } /** * write requests. (Only reach database on commit) */ @Override public void write(final Object identifier, final Object value) { if(identifier == null && value == null) { Log.getLogger().warn("Unsupported write operation"); return; } //Must be a create request. if(identifier == null) { handleCreateRequest(value); return; } //Must be a delete request. if(value == null) { handleDeleteRequest(identifier); return; } handleUpdateRequest(identifier, value); } /** * Fills the updateSet in the case of an update request. * @param identifier the value to write to. * @param value what should be written. */ private void handleUpdateRequest(Object identifier, Object value) { //todo edit create request if equal. if(identifier instanceof NodeStorage && value instanceof NodeStorage) { writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value)); } else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage) { writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value)); } else { Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa"); } } /** * Fills the createSet in the case of a create request. * @param value object to fill in the createSet. */ private void handleCreateRequest(Object value) { if(value instanceof NodeStorage) { writeSet.add(new CreateOperation<>((NodeStorage) value)); } else if(value instanceof RelationshipStorage) { readsSetNode.add(((RelationshipStorage) value).getStartNode()); readsSetNode.add(((RelationshipStorage) value).getEndNode()); writeSet.add(new CreateOperation<>((RelationshipStorage) value)); } } /** * Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet. * @param identifier the object to delete. */ private void handleDeleteRequest(Object identifier) { if(identifier instanceof NodeStorage) { writeSet.add(new DeleteOperation<>((NodeStorage) identifier)); } else if(identifier instanceof RelationshipStorage) { writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier)); } } /** * ReadRequests.(Directly read database) send the request to the db. * @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage */ @Override public void read(final Object...identifiers) { long timeStampToSend = firstRead ? -1 : localTimestamp; for(final Object identifier: identifiers) { if (identifier instanceof NodeStorage) { //this sends the message straight to server 0 not to the others. sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else if (identifier instanceof RelationshipStorage) { sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else { Log.getLogger().warn("Unsupported identifier: " + identifier.toString()); } } firstRead = false; } /** * Receiving read requests replies here * @param reply the received message. */ @Override public void replyReceived(final TOMMessage reply) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().info("reply"); if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST) { final Input input = new Input(reply.getContent()); switch(kryo.readObject(input, String.class)) { case Constants.READ_MESSAGE: processReadReturn(input); break; case Constants.GET_PRIMARY: case Constants.COMMIT_RESPONSE: processCommitReturn(reply.getContent()); break; default: Log.getLogger().info("Unexpected message type!"); break; } input.close(); } else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST) { Log.getLogger().info("Commit return" + reply.getReqType().name()); processCommitReturn(reply.getContent()); } else { Log.getLogger().info("Receiving other type of request." + reply.getReqType().name()); } pool.release(kryo); super.replyReceived(reply); } /** * Processes the return of a read request. Filling the readsets. * @param input the received bytes in an input.. */ private void processReadReturn(final Input input) { if(input == null) { Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!"); return; } Log.getLogger().info("Process read return!"); final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final String result = kryo.readObject(input, String.class); this.localTimestamp = kryo.readObject(input, Long.class); if(Constants.ABORT.equals(result)) { input.close(); pool.release(kryo); resetSets(); readQueue.add(FINISHED_READING); return; } final List nodes = kryo.readObject(input, ArrayList.class); final List relationships = kryo.readObject(input, ArrayList.class); if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage) { for (final NodeStorage storage : (ArrayList<NodeStorage>) nodes) { final NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties()); try { tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for node", e); } readsSetNode.add(tempStorage); } } if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage) { for (final RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships) { final RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode()); try { tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for relationship", e); } readsSetRelationship.add(tempStorage); } } readQueue.add(FINISHED_READING); input.close(); pool.release(kryo); } private void processCommitReturn(final byte[] result) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); if(result == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return; } final Input input = new Input(result); final String type = kryo.readObject(input, String.class); if(!Constants.COMMIT_RESPONSE.equals(type)) { Log.getLogger().warn("Incorrect response to commit message"); input.close(); return; } final String decision = kryo.readObject(input, String.class); localTimestamp = kryo.readObject(input, Long.class); Log.getLogger().info("Processing commit return: " + localTimestamp); if(Constants.COMMIT.equals(decision)) { Log.getLogger().info("Transaction succesfully committed"); } else { Log.getLogger().info("Transaction commit denied - transaction being aborted"); } Log.getLogger().info("Reset after commit"); resetSets(); input.close(); pool.release(kryo); } /** * Commit reaches the server, if secure commit send to all, else only send to one */ @Override public void commit() { firstRead = true; final boolean readOnly = isReadOnly(); Log.getLogger().info("Starting commit"); if (readOnly && !secureMode) { //verifyReadSet(); Log.getLogger().warn(String.format("Read only unsecure Transaction with local transaction id: %d successfully committed", localTimestamp)); firstRead = true; resetSets(); return; } Log.getLogger().info("Starting commit process for: " + this.localTimestamp); final byte[] bytes = serializeAll(); if (readOnly) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().warn(getProcessId() + " Commit with snapshotId: " + this.localTimestamp); final byte[] answer; if(localClusterId == -1) { //List of all view processes /*final int[] currentViewProcesses = this.getViewManager().getCurrentViewProcesses(); //The servers we will actually contact final int[] servers = new int[3]; //final int spare = servers[new Random().nextInt(currentViewProcesses.length)]; int i = 0; for(final int processI : currentViewProcesses) { if(i < servers.length) { servers[i] = processI; i++; } } isCommitting = true; Log.getLogger().info("Sending to: " + Arrays.toString(servers)); //sendMessageToTargets(bytes, 0, servers, TOMMessageType.UNORDERED_REQUEST);*/ answer = invokeUnordered(bytes); } else { answer = globalProxy.invokeUnordered(bytes); } Log.getLogger().info(getProcessId() + "Committed with snapshotId " + this.localTimestamp); final Input input = new Input(answer); final String messageType = kryo.readObject(input, String.class); if (!Constants.COMMIT_RESPONSE.equals(messageType)) { Log.getLogger().warn("Incorrect response type to client from server!" + getProcessId()); resetSets(); firstRead = true; return; } final boolean commit = Constants.COMMIT.equals(kryo.readObject(input, String.class)); if (commit) { localTimestamp = kryo.readObject(input, Long.class); resetSets(); firstRead = true; Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp)); return; } return; } if (localClusterId == -1) { Log.getLogger().info("Distribute commit with snapshotId: " + this.localTimestamp); this.invokeOrdered(bytes); } else { Log.getLogger().info("Commit with snapshotId directly to global cluster. TimestampId: " + this.localTimestamp); Log.getLogger().info("WriteSet: " + writeSet.size() + " readSetNode: " + readsSetNode.size() + " readSetRs: " + readsSetRelationship.size()); processCommitReturn(globalProxy.invokeOrdered(bytes)); } } /** * Method verifies readSet signatures. */ private void verifyReadSet() { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); for(final NodeStorage storage: readsSetNode) { for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet()) { if(!entry.getKey().contains("signature")) { continue; } final int key = Integer.parseInt(entry.getKey().replace("signature","")); Log.getLogger().warn("Verifying the keys of the nodes"); final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false); try { if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8"))) { Log.getLogger().warn("Signature of server: " + key + " doesn't match"); } else { Log.getLogger().info("Signature matches of server: " + entry.getKey()); } } catch (final Exception e) { Log.getLogger().error("Unable to load public key on client", e); } } } Log.getLogger().warn("Verifying the keys of the relationships"); for(final RelationshipStorage storage: readsSetRelationship) { for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet()) { if(!entry.getKey().contains("signature")) { continue; } final int key = Integer.parseInt(entry.getKey().replace("signature","")); Log.getLogger().warn("Verifying the keys of the nodes"); final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false); try { if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8"))) { Log.getLogger().warn("Signature of server: " + key + " doesn't match"); } else { Log.getLogger().info("Signature matches of server: " + entry.getKey()); } } catch (final Exception e) { Log.getLogger().error("Unable to load public key on client", e); } } } pool.release(kryo); } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String request) { KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); Kryo kryo = pool.borrow(); Output output = new Output(0, 256); kryo.writeObject(output, request); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final Output output = new Output(0, 100024); kryo.writeObject(output, reason); kryo.writeObject(output, localTimestamp); for(final Object identifier: args) { if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage) { kryo.writeObject(output, identifier); } } byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes all sets and returns it in byte format. * @return the data in byte format. */ private byte[] serializeAll() { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final Output output = new Output(0, 400024); kryo.writeObject(output, Constants.COMMIT_MESSAGE); //Write the timeStamp to the server kryo.writeObject(output, localTimestamp); //Write the readSet. kryo.writeObject(output, readsSetNode); kryo.writeObject(output, readsSetRelationship); //Write the writeSet. kryo.writeObject(output, writeSet); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Resets all the read and write sets. */ private void resetSets() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); isCommitting = false; responses = 0; final Random random = new Random(); int randomNumber = random.nextInt(100); if(randomNumber <= 70) { serverProcess = 0; return; } if(randomNumber <= 100) { serverProcess = 1; } else { serverProcess = 3; } } /** * Checks if the transaction has made any changes to the update sets. * @return true if not. */ private boolean isReadOnly() { return writeSet.isEmpty(); } @Override public boolean isCommitting() { return isCommitting; } /** * Get the primary of the cluster. * @param kryo the kryo instance. * @return the primary id. */ private int getPrimary(final Kryo kryo) { byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST); if(response == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return -1; } final Input input = new Input(response); kryo.readObject(input, String.class); final int primaryId = kryo.readObject(input, Integer.class); Log.getLogger().info("Received id: " + primaryId); input.close(); return primaryId; } }
package main.java.com.bag.client; import bftsmart.communication.client.ReplyReceiver; import bftsmart.tom.ServiceProxy; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.core.messages.TOMMessageType; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import main.java.com.bag.operations.CreateOperation; import main.java.com.bag.operations.DeleteOperation; import main.java.com.bag.operations.Operation; import main.java.com.bag.operations.UpdateOperation; import main.java.com.bag.util.*; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Class handling the client. */ public class TestClient extends ServiceProxy implements ReplyReceiver, Closeable, AutoCloseable { /** * Should the transaction runNetty in secure mode? */ private boolean secureMode = false; /** * The place the local config file is. This + the cluster id will contain the concrete cluster config location. */ private static final String LOCAL_CONFIG_LOCATION = "local%d/config"; /** * The place the global config files is. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * Sets to log reads, updates, deletes and node creations. */ private ArrayList<NodeStorage> readsSetNode; private ArrayList<RelationshipStorage> readsSetRelationship; private ArrayList<Operation> writeSet; /** * Local timestamp of the current transaction. */ private long localTimestamp = -1; /** * The id of the local server process the client is communicating with. */ private final int serverProcess; /** * Lock object to let the thread wait for a read return. */ private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>(); /** * The last object in read queue. */ public static final Object FINISHED_READING = new Object(); /** * Id of the local cluster. */ private final int localClusterId; /** * Create a threadsafe version of kryo. */ private KryoFactory factory = () -> { Kryo kryo = new Kryo(); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); kryo.register(CreateOperation.class, 250); kryo.register(DeleteOperation.class, 300); kryo.register(UpdateOperation.class, 350); return kryo; }; public TestClient(final int processId, final int serverId, final int localClusterId) { super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId)); secureMode = true; this.serverProcess = serverId; this.localClusterId = localClusterId; initClient(); } /** * Initiates the client maps and registers necessary operations. */ private void initClient() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Get the blocking queue. * @return the queue. */ public BlockingQueue<Object> getReadQueue() { return readQueue; } /** * write requests. (Only reach database on commit) */ public void write(final Object identifier, final Object value) { if(identifier == null && value == null) { Log.getLogger().warn("Unsupported write operation"); return; } //Must be a create request. if(identifier == null) { handleCreateRequest(value); return; } //Must be a delete request. if(value == null) { handleDeleteRequest(identifier); return; } handleUpdateRequest(identifier, value); } /** * Fills the updateSet in the case of an update request. * @param identifier the value to write to. * @param value what should be written. */ private void handleUpdateRequest(Object identifier, Object value) { //todo edit create request if equal. if(identifier instanceof NodeStorage && value instanceof NodeStorage) { writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value)); } else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage) { writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value)); } else { Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa"); } } /** * Fills the createSet in the case of a create request. * @param value object to fill in the createSet. */ private void handleCreateRequest(Object value) { if(value instanceof NodeStorage) { writeSet.add(new CreateOperation<>((NodeStorage) value)); } else if(value instanceof RelationshipStorage) { readsSetNode.add(((RelationshipStorage) value).getStartNode()); readsSetNode.add(((RelationshipStorage) value).getEndNode()); writeSet.add(new CreateOperation<>((RelationshipStorage) value)); } } /** * Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet. * @param identifier the object to delete. */ private void handleDeleteRequest(Object identifier) { //todo we can delete creates here. if(identifier instanceof NodeStorage) { writeSet.add(new DeleteOperation<>((NodeStorage) identifier)); } else if(identifier instanceof RelationshipStorage) { writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier)); } } /** * ReadRequests.(Directly read database) send the request to the db. * @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage */ public void read(Object...identifiers) { for(Object identifier: identifiers) { if (identifier instanceof NodeStorage) { //this sends the message straight to server 0 not to the others. sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, localTimestamp, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else if (identifier instanceof RelationshipStorage) { sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, localTimestamp, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else { Log.getLogger().warn("Unsupported identifier: " + identifier.toString()); } } } /** * Receiving read requests replies here * @param reply the received message. */ @Override public void replyReceived(final TOMMessage reply) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().info("reply"); if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST) { final Input input = new Input(reply.getContent()); switch(kryo.readObject(input, String.class)) { case Constants.READ_MESSAGE: processReadReturn(input); break; case Constants.GET_PRIMARY: super.replyReceived(reply); break; default: Log.getLogger().info("Unexpected message type!"); break; } input.close(); } else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST) { Log.getLogger().info("Commit return"); processCommitReturn(reply.getContent()); } else { Log.getLogger().info("Receiving other type of request." + reply.getReqType().name()); } super.replyReceived(reply); } /** * Processes the return of a read request. Filling the readsets. * @param input the received bytes in an input.. */ private void processReadReturn(final Input input) { if(input == null) { Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!"); return; } final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); this.localTimestamp = kryo.readObject(input, Long.class); List nodes = kryo.readObject(input, ArrayList.class); List relationships = kryo.readObject(input, ArrayList.class); if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage) { for (NodeStorage storage : (ArrayList<NodeStorage>) nodes) { NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties()); try { tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for node", e); } readsSetNode.add(tempStorage); readQueue.add(tempStorage); } } if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage) { for (RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships) { RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode()); try { tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for relationship", e); } readsSetRelationship.add(tempStorage); readQueue.add(tempStorage); } } readQueue.add(FINISHED_READING); input.close(); pool.release(kryo); } private void processCommitReturn(final byte[] result) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); if(result == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return; } final Input input = new Input(result); final String type = kryo.readObject(input, String.class); if(!Constants.COMMIT_RESPONSE.equals(type)) { Log.getLogger().warn("Incorrect response to commit message"); input.close(); return; } final String decision = kryo.readObject(input, String.class); localTimestamp = kryo.readObject(input, Long.class); if(Constants.COMMIT.equals(decision)) { Log.getLogger().info("Transaction succesfully committed"); } else { Log.getLogger().info("Transaction commit denied - transaction being aborted"); } resetSets(); input.close(); pool.release(kryo); } /** * Commit reaches the server, if secure commit send to all, else only send to one */ public void commit() { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().info("Starting commit"); final boolean readOnly = isReadOnly(); byte[] bytes = serializeAll(); if(localClusterId == -1) { Log.getLogger().info("Commit with snapshotId: " + this.localTimestamp); invokeOrdered(bytes); return; } final int primaryId = getPrimary(kryo); if(primaryId == -1) { Log.getLogger().warn("Wrong primaryId!!!"); return; } Log.getLogger().info("Committing to primary replica: " + primaryId); if(readOnly && !secureMode) { Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp)); resetSets(); } else { sendMessageToTargets(bytes , 0, new int[] {primaryId}, TOMMessageType.UNORDERED_REQUEST); } } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String request) { KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); Kryo kryo = pool.borrow(); Output output = new Output(0, 256); kryo.writeObject(output, request); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); //Todo probably will need a bigger buffer in the future. size depending on the set size? final Output output = new Output(0, 10024); kryo.writeObject(output, reason); kryo.writeObject(output, localTimestamp); for(final Object identifier: args) { if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage) { kryo.writeObject(output, identifier); } } byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes all sets and returns it in byte format. * @return the data in byte format. */ private byte[] serializeAll() { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); //Todo probably will need a bigger buffer in the future. size depending on the set size? final Output output = new Output(0, 100240); kryo.writeObject(output, Constants.COMMIT_MESSAGE); //Write the timeStamp to the server kryo.writeObject(output, localTimestamp); //Write the readSet. kryo.writeObject(output, readsSetNode); kryo.writeObject(output, readsSetRelationship); //Write the writeSet. kryo.writeObject(output, writeSet); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Resets all the read and write sets. */ private void resetSets() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Checks if the transaction has made any changes to the update sets. * @return true if not. */ private boolean isReadOnly() { return writeSet.isEmpty(); } /** * Get the primary of the cluster. * @param kryo the kryo instance. * @return the primary id. */ private int getPrimary(final Kryo kryo) { byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST); if(response == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return -1; } final Input input = new Input(response); kryo.readObject(input, String.class); final int primaryId = kryo.readObject(input, Integer.class); Log.getLogger().info("Received id: " + primaryId); input.close(); return primaryId; } }
package org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.birt.report.designer.internal.ui.editors.parts.DeferredGraphicalViewer; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.layer.TableBorderLayer; import org.eclipse.birt.report.designer.internal.ui.layout.FixTableLayout; import org.eclipse.birt.report.designer.internal.ui.layout.ITableLayoutOwner; import org.eclipse.birt.report.designer.internal.ui.layout.TableLayout; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.command.ViewsContentEvent; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.draw2d.FreeformLayer; import org.eclipse.draw2d.FreeformLayeredPane; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LayeredPane; import org.eclipse.gef.EditPart; import org.eclipse.gef.LayerConstants; import org.eclipse.gef.editparts.LayerManager; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Display; /** *Abstract class for the table editpart. */ public abstract class AbstractTableEditPart extends ReportElementEditPart implements LayerConstants, ITableLayoutOwner { public static final String BORDER_LAYER = "Table Border layer"; //$NON-NLS-1$ protected FreeformLayeredPane innerLayers; protected LayeredPane printableLayers; /**Constractor * @param model */ public AbstractTableEditPart( Object model ) { super( model ); } /** * Returns the layer indicated by the key. Searches all layered panes. * * @see LayerManager#getLayer(Object) */ public IFigure getLayer( Object key ) { if ( innerLayers == null ) return null; IFigure layer = innerLayers.getLayer( key ); if ( layer != null ) return layer; if ( printableLayers == null ) return null; return printableLayers.getLayer( key ); } /** * this layer may be a un-useful layer. * * @return the layered pane containing all printable content */ protected LayeredPane getPrintableLayers( ) { if ( printableLayers == null ) printableLayers = createPrintableLayers( ); return printableLayers; } /** * Creates a layered pane and the layers that should be printed. * * @see org.eclipse.gef.print.PrintGraphicalViewerOperation * @return a new LayeredPane containing the printable layers */ protected LayeredPane createPrintableLayers( ) { FreeformLayeredPane layeredPane = new FreeformLayeredPane( ); FreeformLayer layer = new FreeformLayer( ); layer.setLayoutManager( new TableLayout( this ) ); layeredPane.add( layer, PRIMARY_LAYER ); layeredPane.add( new TableBorderLayer( this ), BORDER_LAYER ); return layeredPane; } /** * The contents' Figure will be added to the PRIMARY_LAYER. * * @see org.eclipse.gef.GraphicalEditPart#getContentPane() */ public IFigure getContentPane( ) { return getLayer( PRIMARY_LAYER ); } /* (non-Javadoc) * @see org.eclipse.birt.report.designer.internal.ui.layout.ITableLayoutOwner#reLayout() */ public void reLayout( ) { notifyModelChange( ); getFigure( ).invalidateTree( ); // getFigure( ).getUpdateManager( ).addInvalidFigure( getFigure( ) ); getFigure( ).revalidate( ); } /** * Get the cell on give position. * * @param rowNumber * @param columnNumber */ public abstract AbstractCellEditPart getCell( int rowNumber, int columnNumber ); protected void contentChange( Map info ) { Object action = info.get(GraphicsViewModelEventProcessor.CONTENT_EVENTTYPE ); if (action instanceof Integer) { int intValue = ((Integer)action).intValue( ); if (intValue == ViewsContentEvent.ADD || intValue == ViewsContentEvent.SHIFT || intValue == ViewsContentEvent.REMOVE) { if (((ReportItemHandle)getModel()).getViews( ).size( ) > 0) { final Object tempModel = getModel( ); final DeferredGraphicalViewer viewer = (DeferredGraphicalViewer)getViewer( ); markDirty( true ); EditPart part = getParent( ); ((ReportElementEditPart)getParent( )).removeChild( this ); part.refresh( ); removeGuideFeedBack( ); Display.getCurrent( ).asyncExec( new Runnable( ) { public void run( ) { Object part = viewer.getEditPartRegistry( ).get( tempModel ); if (part != null) { viewer.setSelection( new StructuredSelection( part ) ); } } } ); return; } else { ((ReportElementEditPart)getParent( )).contentChange( info ); return; } } } List old = new ArrayList(getChildren( )); super.contentChange( info ); List newChildren = getChildren( ); for (int i=0; i<old.size( ); i++) { if (newChildren.contains( old.get( i ) )) { ((AbstractCellEditPart)old.get( i )).updateExistPart( ); } } } @Override protected void updateLayoutPreference( ) { super.updateLayoutPreference( ); if (!(((DesignElementHandle)getModel()).getModuleHandle( ) instanceof ReportDesignHandle)) { return ; } ReportDesignHandle handle = (ReportDesignHandle)((DesignElementHandle)getModel()).getModuleHandle( ); String str = handle.getLayoutPreference( ); if (DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_AUTO_LAYOUT.equals( str )) { getContentPane( ).setLayoutManager( new TableLayout(this)); } else if (DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_FIXED_LAYOUT.equals( str )) { getContentPane( ).setLayoutManager(new FixTableLayout(this)); } } }
package main.java.com.bag.client; import bftsmart.communication.client.ReplyReceiver; import bftsmart.tom.ServiceProxy; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.core.messages.TOMMessageType; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import main.java.com.bag.operations.CreateOperation; import main.java.com.bag.operations.DeleteOperation; import main.java.com.bag.operations.Operation; import main.java.com.bag.operations.UpdateOperation; import main.java.com.bag.util.*; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Class handling the client. */ public class TestClient extends ServiceProxy implements BAGClient, ReplyReceiver, Closeable, AutoCloseable { /** * Should the transaction runNetty in secure mode? */ private boolean secureMode = true; /** * The place the local config file is. This + the cluster id will contain the concrete cluster config location. */ private static final String LOCAL_CONFIG_LOCATION = "local%d/config"; /** * The place the global config files is. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * Sets to log reads, updates, deletes and node creations. */ private ArrayList<NodeStorage> readsSetNode; private ArrayList<RelationshipStorage> readsSetRelationship; private ArrayList<Operation> writeSet; /** * Local timestamp of the current transaction. */ private long localTimestamp = -1; /** * The id of the local server process the client is communicating with. */ private final int serverProcess; /** * Lock object to let the thread wait for a read return. */ private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>(); /** * The last object in read queue. */ public static final Object FINISHED_READING = new Object(); /** * Id of the local cluster. */ private final int localClusterId; /** * Checks if its the first read of the client. */ private boolean firstRead = true; /** * The proxy to use during communication with the globalCluster. */ private ServiceProxy globalProxy; /** * Create a threadsafe version of kryo. */ private KryoFactory factory = () -> { Kryo kryo = new Kryo(); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); kryo.register(CreateOperation.class, 250); kryo.register(DeleteOperation.class, 300); kryo.register(UpdateOperation.class, 350); return kryo; }; public TestClient(final int processId, final int serverId, final int localClusterId) { super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId)); if(localClusterId != -1) { globalProxy = new ServiceProxy(100 + getProcessId(), "global/config"); } secureMode = true; this.serverProcess = serverId; this.localClusterId = localClusterId; initClient(); System.out.println("Starting client " + processId); } /** * Initiates the client maps and registers necessary operations. */ private void initClient() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Get the blocking queue. * @return the queue. */ @Override public BlockingQueue<Object> getReadQueue() { return readQueue; } /** * write requests. (Only reach database on commit) */ @Override public void write(final Object identifier, final Object value) { if(identifier == null && value == null) { Log.getLogger().warn("Unsupported write operation"); return; } //Must be a create request. if(identifier == null) { handleCreateRequest(value); return; } //Must be a delete request. if(value == null) { handleDeleteRequest(identifier); return; } handleUpdateRequest(identifier, value); } /** * Fills the updateSet in the case of an update request. * @param identifier the value to write to. * @param value what should be written. */ private void handleUpdateRequest(Object identifier, Object value) { //todo edit create request if equal. if(identifier instanceof NodeStorage && value instanceof NodeStorage) { writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value)); } else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage) { writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value)); } else { Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa"); } } /** * Fills the createSet in the case of a create request. * @param value object to fill in the createSet. */ private void handleCreateRequest(Object value) { if(value instanceof NodeStorage) { writeSet.add(new CreateOperation<>((NodeStorage) value)); } else if(value instanceof RelationshipStorage) { readsSetNode.add(((RelationshipStorage) value).getStartNode()); readsSetNode.add(((RelationshipStorage) value).getEndNode()); writeSet.add(new CreateOperation<>((RelationshipStorage) value)); } } /** * Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet. * @param identifier the object to delete. */ private void handleDeleteRequest(Object identifier) { //todo we can delete creates here. if(identifier instanceof NodeStorage) { writeSet.add(new DeleteOperation<>((NodeStorage) identifier)); } else if(identifier instanceof RelationshipStorage) { writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier)); } } /** * ReadRequests.(Directly read database) send the request to the db. * @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage */ @Override public void read(final Object...identifiers) { long timeStampToSend = firstRead ? -1 : localTimestamp; for(final Object identifier: identifiers) { if (identifier instanceof NodeStorage) { //this sends the message straight to server 0 not to the others. sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else if (identifier instanceof RelationshipStorage) { sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else { Log.getLogger().warn("Unsupported identifier: " + identifier.toString()); } } firstRead = false; } /** * Receiving read requests replies here * @param reply the received message. */ @Override public void replyReceived(final TOMMessage reply) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().info("reply"); if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST) { final Input input = new Input(reply.getContent()); switch(kryo.readObject(input, String.class)) { case Constants.READ_MESSAGE: processReadReturn(input); break; case Constants.GET_PRIMARY: case Constants.COMMIT_RESPONSE: super.replyReceived(reply); break; default: Log.getLogger().info("Unexpected message type!"); break; } input.close(); } else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST) { Log.getLogger().info("Commit return"); processCommitReturn(reply.getContent()); } else { Log.getLogger().info("Receiving other type of request." + reply.getReqType().name()); } super.replyReceived(reply); } /** * Processes the return of a read request. Filling the readsets. * @param input the received bytes in an input.. */ private void processReadReturn(final Input input) { if(input == null) { Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!"); return; } final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final String result = kryo.readObject(input, String.class); this.localTimestamp = kryo.readObject(input, Long.class); if(Constants.ABORT.equals(result)) { input.close(); pool.release(kryo); resetSets(); readQueue.add(FINISHED_READING); return; } final List nodes = kryo.readObject(input, ArrayList.class); final List relationships = kryo.readObject(input, ArrayList.class); if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage) { for (NodeStorage storage : (ArrayList<NodeStorage>) nodes) { NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties()); try { tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for node", e); } readsSetNode.add(tempStorage); } } if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage) { for (RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships) { RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode()); try { tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for relationship", e); } readsSetRelationship.add(tempStorage); } } readQueue.add(FINISHED_READING); input.close(); pool.release(kryo); } private void processCommitReturn(final byte[] result) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); if(result == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return; } final Input input = new Input(result); final String type = kryo.readObject(input, String.class); if(!Constants.COMMIT_RESPONSE.equals(type)) { Log.getLogger().warn("Incorrect response to commit message"); input.close(); return; } final String decision = kryo.readObject(input, String.class); localTimestamp = kryo.readObject(input, Long.class); if(Constants.COMMIT.equals(decision)) { Log.getLogger().info("Transaction succesfully committed"); } else { Log.getLogger().info("Transaction commit denied - transaction being aborted"); } resetSets(); input.close(); pool.release(kryo); } /** * Commit reaches the server, if secure commit send to all, else only send to one */ @Override public void commit() { firstRead = true; final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().info("Starting commit"); final boolean readOnly = isReadOnly(); if (readOnly && !secureMode) { Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp)); firstRead = true; resetSets(); return; } final byte[] bytes = serializeAll(); if (readOnly) { Log.getLogger().info("Commit with snapshotId: " + this.localTimestamp); final byte[] answer = localClusterId == -1 ? this.invokeOrdered(bytes) : globalProxy.invokeOrdered(bytes); final Input input = new Input(answer); final String messageType = kryo.readObject(input, String.class); if (!Constants.COMMIT_RESPONSE.equals(messageType)) { Log.getLogger().warn("Incorrect response type to client from server!" + getProcessId()); resetSets(); firstRead = true; return; } final boolean commit = Constants.COMMIT.equals(kryo.readObject(input, String.class)); if (commit) { localTimestamp = kryo.readObject(input, Long.class); resetSets(); firstRead = true; Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp)); return; } Log.getLogger().info(String.format("Read-only Transaction with local transaction id: %d resend to the server", localTimestamp)); } if (localClusterId == -1) { Log.getLogger().info("Distribute commit with snapshotId: " + this.localTimestamp); invokeOrdered(bytes); } else { Log.getLogger().info("Commit with snapshotId directly to global cluster. TimestampId: " + this.localTimestamp); processCommitReturn(globalProxy.invokeOrdered(bytes)); } } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String request) { KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); Kryo kryo = pool.borrow(); Output output = new Output(0, 256); kryo.writeObject(output, request); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final Output output = new Output(0, 100024); kryo.writeObject(output, reason); kryo.writeObject(output, localTimestamp); for(final Object identifier: args) { if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage) { kryo.writeObject(output, identifier); } } byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes all sets and returns it in byte format. * @return the data in byte format. */ private byte[] serializeAll() { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final Output output = new Output(0, 400024); kryo.writeObject(output, Constants.COMMIT_MESSAGE); //Write the timeStamp to the server kryo.writeObject(output, localTimestamp); //Write the readSet. kryo.writeObject(output, readsSetNode); kryo.writeObject(output, readsSetRelationship); //Write the writeSet. kryo.writeObject(output, writeSet); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Resets all the read and write sets. */ private void resetSets() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Checks if the transaction has made any changes to the update sets. * @return true if not. */ private boolean isReadOnly() { return writeSet.isEmpty(); } /** * Get the primary of the cluster. * @param kryo the kryo instance. * @return the primary id. */ private int getPrimary(final Kryo kryo) { byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST); if(response == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return -1; } final Input input = new Input(response); kryo.readObject(input, String.class); final int primaryId = kryo.readObject(input, Integer.class); Log.getLogger().info("Received id: " + primaryId); input.close(); return primaryId; } }
package TobleMiner.MineFightWeapons.Weapons.Definitions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Item; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDamageByBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.ItemDespawnEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import TobleMiner.MineFight.Debug.Debugger; import TobleMiner.MineFight.GameEngine.Match.Match; import TobleMiner.MineFight.GameEngine.Player.PVPPlayer; import TobleMiner.MineFight.Weapon.Weapon; import TobleMiner.MineFightWeapons.Main; import TobleMiner.MineFightWeapons.Weapons.Stationary.IMS.WpIMS; public class IMS implements Weapon { private HashMap<Match, List<WpIMS>> imssByMatch = new HashMap<>(); private HashMap<Item, WpIMS> imsByItem = new HashMap<>(); private HashMap<PVPPlayer, List<WpIMS>> imssByPlayer = new HashMap<>(); @Override public void getRequiredEvents(List<Class<?>> events) { events.add(PlayerDropItemEvent.class); events.add(PlayerPickupItemEvent.class); events.add(EntityDamageEvent.class); events.add(EntityDamageByBlockEvent.class); events.add(EntityDamageByEntityEvent.class); events.add(EntityCombustEvent.class); events.add(ItemDespawnEvent.class); } @Override public void onEvent(Match m, Event event) { if(event instanceof PlayerDropItemEvent) { PlayerDropItemEvent pdie = (PlayerDropItemEvent)event; if(pdie.getItemDrop().getItemStack().getType() != this.getMaterial(m.getWorld()) || pdie.getItemDrop().getItemStack().getDurability() != this.getSubId(m.getWorld())) return; Debugger.writeDebugOut("ims dropped by " + pdie.getPlayer().getName()); PVPPlayer player = m.getPlayerExact(pdie.getPlayer()); if(player == null || !player.isSpawned()) { Debugger.writeDebugOut("ims not created: Player not spawned: " + pdie.getPlayer().getName()); pdie.setCancelled(true); return; } Item item = pdie.getItemDrop(); if(Main.papi.getProtections().isLocProtected(item.getLocation()) && !Main.config.ims.ignoreProtection(item.getWorld())) { Debugger.writeDebugOut("ims not created: Area protected: " + pdie.getPlayer().getName()); pdie.setCancelled(true); return; } Debugger.writeDebugOut("ims created: " + pdie.getPlayer().getName()); WpIMS ims = new WpIMS(m, item, player); this.imssByPlayer.get(player).add(ims); this.imsByItem.put(item, ims); this.imssByMatch.get(m).add(ims); if(this.imssByPlayer.get(player).size() > Main.config.ims.getLimit(m.getWorld())) { List<WpIMS> imss = new ArrayList<>(this.imssByPlayer.get(player)); if(imss.size() > 0) { WpIMS tims = imss.get(0); tims.remove(); this.remove(tims); } } pdie.setCancelled(false); } else if(event instanceof PlayerPickupItemEvent) { PlayerPickupItemEvent ppie = (PlayerPickupItemEvent)event; if(ppie.getItem().getItemStack().getType() != this.getMaterial(m.getWorld())) return; PVPPlayer player = m.getPlayerExact(ppie.getPlayer()); if(player == null || !player.isSpawned()) { Debugger.writeDebugOut(String.format("%s hasn't spawned. No pickup.", ppie.getPlayer().getName())); ppie.setCancelled(true); return; } WpIMS ims = this.imsByItem.get(ppie.getItem()); if(ims == null) return; ppie.setCancelled(true); Debugger.writeDebugOut(String.format("%s is trying to pickup ims: Owner: %s", ppie.getPlayer().getName(), ims.owner.thePlayer.getName())); if(player != ims.owner) { if(player.getTeam() != ims.owner.getTeam() && Main.config.ims.canEnemyPickup(m.getWorld()) && player.thePlayer.isSneaking()) { Debugger.writeDebugOut(String.format("%s is picking up a hostile ims.", ppie.getPlayer().getName())); ppie.setCancelled(false); this.remove(ims); } } else { Debugger.writeDebugOut(String.format("%s found his own ims.", ppie.getPlayer().getName())); } } else if(event instanceof EntityDamageEvent) { EntityDamageEvent ede = (EntityDamageEvent)event; if(ede.getEntity() instanceof Item) { Item item = (Item)ede.getEntity(); if(item.getItemStack().getType() != this.getMaterial(m.getWorld())) return; WpIMS ims = this.imsByItem.get(item); if(ims == null) return; Debugger.writeDebugOut("ims damaged"); ede.setCancelled(true); if(ede.getCause() == DamageCause.BLOCK_EXPLOSION || ede.getCause() == DamageCause.ENTITY_EXPLOSION) { Debugger.writeDebugOut("ims damaged by explosion. Exploding."); this.remove(ims); ims.remove(); return; } } } else if(event instanceof EntityCombustEvent) { EntityCombustEvent ice = (EntityCombustEvent)event; if(ice.getEntity() instanceof Item) { Item item = (Item)ice.getEntity(); if(item.getItemStack().getType() != this.getMaterial(m.getWorld())) return; WpIMS ims = this.imsByItem.get(item); if(ims == null) return; ice.setCancelled(true); ims.remove(); return; } } else if(event instanceof ItemDespawnEvent) { ItemDespawnEvent ide = (ItemDespawnEvent)event; Item item = (Item)ide.getEntity(); if(item.getItemStack().getType() != this.getMaterial(m.getWorld())) return; WpIMS ims = this.imsByItem.get(item); if(ims == null) return; ide.setCancelled(true); } } @Override public void onKill(Match m, PVPPlayer killer, PVPPlayer killed) { //nop } @Override public void onDeath(Match m, PVPPlayer killed, PVPPlayer killer) { if(Main.config.ims.despawnOnDeath(m.getWorld())) { List<WpIMS> imss = new ArrayList<>(this.imssByPlayer.get(killed)); for(WpIMS ims : imss) { this.remove(ims); ims.remove(); } } } @Override public void onRespawn(Match m, PVPPlayer player) { //nop } @Override public void matchCreated(Match m) { imssByMatch.put(m, new ArrayList<WpIMS>()); } @Override public void matchEnded(Match m) { imssByMatch.remove(m); } @Override public void onTick() { //nop } @Override public void onJoin(Match m, PVPPlayer player) { Debugger.writeDebugOut("Creating ims-entry for " + player.thePlayer.getName()); imssByPlayer.put(player, new ArrayList<WpIMS>()); } @Override public void onLeave(Match m, PVPPlayer player) { Debugger.writeDebugOut("Removing ims-entry for " + player.thePlayer.getName()); List<WpIMS> imss = imssByPlayer.get(player); for(WpIMS ims : imss) { imsByItem.remove(ims.item); ims.remove(); imssByMatch.get(m).remove(ims); } imssByPlayer.remove(player); } @Override public void onTeamchange(Match m, PVPPlayer player) { Debugger.writeDebugOut("Removing ims due to teamchange: " + player.thePlayer.getName()); List<WpIMS> imss = new ArrayList<>(this.imssByPlayer.get(player)); for(WpIMS ims : imss) { this.remove(ims); ims.remove(); } } @Override public Material getMaterial(World w) { return Main.config.ims.getMaterial(w); } @Override public short getSubId(World w) { return Main.config.ims.getSubid(w); } private void remove(WpIMS ims) { if(ims.item != null) this.imsByItem.remove(ims.item); this.imssByMatch.get(ims.owner.getMatch()).remove(ims); this.imssByPlayer.get(ims.owner).remove(ims); } }
package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; public class BitbucketPullRequestActivityDeserializer implements JsonDeserializer<BitbucketPullRequestBaseActivity> { @Override public BitbucketPullRequestBaseActivity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); if (asComment(jsonObject) != null) { return context.deserialize(asComment(jsonObject), BitbucketPullRequestCommentActivity.class); } else if (asUpdate(jsonObject) != null) { return context.deserialize(asUpdate(jsonObject), BitbucketPullRequestUpdateActivity.class); } else if (asLike(jsonObject) != null) { return context.deserialize(asLike(jsonObject), BitbucketPullRequestLikeActivity.class); } return null; } public static Map<Class<?>, JsonDeserializer<?>> asMap() { Map<Class<?>, JsonDeserializer<?>> deserializers = new HashMap<Class<?>, JsonDeserializer<?>>(); deserializers.put(BitbucketPullRequestBaseActivity.class, new BitbucketPullRequestActivityDeserializer ()); return deserializers; } private JsonElement asComment(JsonObject jsonObject) { return jsonObject.get("comment"); } private JsonElement asLike(JsonObject jsonObject) { return jsonObject.get("like"); } private JsonElement asUpdate(JsonObject jsonObject) { return jsonObject.get("update"); } }
package mho.haskellesque.math; import mho.haskellesque.iterables.Exhaustive; import mho.haskellesque.iterables.IndexedIterable; import mho.haskellesque.tuples.Pair; import mho.haskellesque.tuples.Quadruple; import mho.haskellesque.tuples.Triple; import java.math.BigInteger; import java.util.List; import java.util.Optional; import java.util.function.Function; import static mho.haskellesque.iterables.IterableUtils.*; import static mho.haskellesque.ordering.Ordering.*; public class Combinatorics { public static BigInteger factorial(int n) { return productBigInteger(range(BigInteger.ONE, BigInteger.valueOf(n).add(BigInteger.ONE))); } public static BigInteger factorial(BigInteger n) { return productBigInteger(range(BigInteger.ONE, n.add(BigInteger.ONE))); } public static BigInteger subfactorial(int n) { if (n == 0) return BigInteger.ONE; BigInteger a = BigInteger.ONE; BigInteger b = BigInteger.ZERO; BigInteger c = b; for (int i = 1; i < n; i++) { c = BigInteger.valueOf(i).multiply(a.add(b)); a = b; b = c; } return c; } public static BigInteger subfactorial(BigInteger n) { if (n.equals(BigInteger.ZERO)) return BigInteger.ONE; BigInteger a = BigInteger.ONE; BigInteger b = BigInteger.ZERO; BigInteger c = b; for (BigInteger i = BigInteger.ONE; lt(i, n); i = i.add(BigInteger.ONE)) { c = i.multiply(a.add(b)); a = b; b = c; } return c; } public static <S, T> Iterable<Pair<S, T>> cartesianPairs(Iterable<S> fsts, Iterable<T> snds) { return concatMap(p -> zip(repeat(p.fst), p.snd), zip(fsts, repeat(snds))); } public static <A, B, C> Iterable<Triple<A, B, C>> cartesianTriples( Iterable<A> as, Iterable<B> bs, Iterable<C> cs ) { return map( p -> new Triple<>(p.fst, p.snd.fst, p.snd.snd), cartesianPairs(as, (Iterable<Pair<B, C>>) cartesianPairs(bs, cs)) ); } public static <A, B, C, D> Iterable<Quadruple<A, B, C, D>> cartesianQuadruples( Iterable<A> as, Iterable<B> bs, Iterable<C> cs, Iterable<D> ds ) { return map( p -> new Quadruple<>(p.fst.fst, p.fst.snd, p.snd.fst, p.snd.snd), cartesianPairs( (Iterable<Pair<A, B>>)cartesianPairs(as, bs), (Iterable<Pair<C, D>>) cartesianPairs(cs, ds) ) ); } public static <S, T> Iterable<Pair<S, T>> exponentialPairs(Iterable<S> fsts, Iterable<T> snds) { IndexedIterable<S> fstii = new IndexedIterable<>(fsts); IndexedIterable<T> sndii = new IndexedIterable<>(snds); Function<BigInteger, Optional<Pair<S, T>>> f = bi -> { Pair<BigInteger, BigInteger> p = BasicMath.exponentialDemux(bi); assert p.fst != null; Optional<S> optFst = fstii.get(p.fst.intValue()); if (!optFst.isPresent()) return Optional.empty(); assert p.snd != null; Optional<T> optSnd = sndii.get(p.snd.intValue()); if (!optSnd.isPresent()) return Optional.empty(); return Optional.of(new Pair<S, T>(optFst.get(), optSnd.get())); }; return map( Optional::get, filter( Optional<Pair<S, T>>::isPresent, (Iterable<Optional<Pair<S, T>>>) map(bi -> f.apply(bi), Exhaustive.BIG_INTEGERS) ) ); } public static <T> Iterable<Pair<T, T>> exponentialPairs(Iterable<T> xs) { IndexedIterable<T> ii = new IndexedIterable<>(xs); Function<BigInteger, Optional<Pair<T, T>>> f = bi -> { Pair<BigInteger, BigInteger> p = BasicMath.exponentialDemux(bi); assert p.fst != null; Optional<T> optFst = ii.get(p.fst.intValue()); if (!optFst.isPresent()) return Optional.empty(); assert p.snd != null; Optional<T> optSnd = ii.get(p.snd.intValue()); if (!optSnd.isPresent()) return Optional.empty(); return Optional.of(new Pair<T, T>(optFst.get(), optSnd.get())); }; return map( Optional::get, filter( Optional<Pair<T, T>>::isPresent, (Iterable<Optional<Pair<T, T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <S, T> Iterable<Pair<S, T>> pairs(Iterable<S> fsts, Iterable<T> snds) { IndexedIterable<S> fstii = new IndexedIterable<>(fsts); IndexedIterable<T> sndii = new IndexedIterable<>(snds); Function<BigInteger, Optional<Pair<S, T>>> f = bi -> { List<BigInteger> p = BasicMath.demux(2, bi); assert p.get(0) != null; Optional<S> optFst = fstii.get(p.get(0).intValue()); if (!optFst.isPresent()) return Optional.empty(); assert p.get(1) != null; Optional<T> optSnd = sndii.get(p.get(1).intValue()); if (!optSnd.isPresent()) return Optional.empty(); return Optional.of(new Pair<S, T>(optFst.get(), optSnd.get())); }; return map( Optional::get, filter( Optional<Pair<S, T>>::isPresent, (Iterable<Optional<Pair<S, T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } }
package io.spacedog.server; import java.util.Map; import java.util.Optional; import com.google.common.collect.Maps; import com.google.common.net.HttpHeaders; import io.spacedog.http.SpaceBackend; import io.spacedog.model.Settings; import io.spacedog.utils.AuthorizationHeader; import io.spacedog.utils.Credentials; import io.spacedog.utils.Exceptions; import io.spacedog.utils.Optional7; import io.spacedog.utils.SpaceHeaders; import net.codestory.http.Context; import net.codestory.http.constants.Methods; /** * Context credentials should only be accessed from public static check methods * from this class. */ public class SpaceContext { private static ThreadLocal<SpaceContext> threadLocal = new ThreadLocal<>(); private String uri; private Context context; private SpaceBackend backend; private boolean isTest; private Debug debug; private Credentials credentials; private boolean authorizationChecked; private Map<String, Settings> settings; private SpaceContext(String uri, Context context) { this.uri = uri; this.context = context; this.isTest = Boolean.parseBoolean( context().header(SpaceHeaders.SPACEDOG_TEST)); this.debug = new Debug(Boolean.parseBoolean( context().header(SpaceHeaders.SPACEDOG_DEBUG))); this.credentials = Credentials.GUEST; this.backend = backend( context.request().header(HttpHeaders.HOST)); } private static SpaceBackend backend(String hostAndPort) { ServerConfiguration conf = Start.get().configuration(); // first try to match api backend SpaceBackend api = conf.apiBackend(); Optional7<SpaceBackend> backend = api.checkAndInstantiate(hostAndPort); if (backend.isPresent()) return backend.get(); // second try to match webapp backend Optional<SpaceBackend> webApp = conf.wwwBackend(); if (webApp.isPresent()) { backend = webApp.get().checkAndInstantiate(hostAndPort); if (backend.isPresent()) return backend.get(); } return api.instanciate(); } public Context context() { return context; } public static SpaceFilter filter() { // uri is already checked by SpaceFilter default matches method return (uri, context, nextFilter) -> { if (threadLocal.get() == null) { try { threadLocal.set(new SpaceContext(uri, context)); return nextFilter.get(); } finally { threadLocal.set(null); } } else // means there is another filter higher in the stack managing // the space context return nextFilter.get(); }; } public static SpaceContext get() { SpaceContext context = threadLocal.get(); if (context == null) throw Exceptions.runtime("no thread local context set"); return context; } public static boolean isTest() { return get().isTest; } public static boolean isWww() { return backend().webApp(); } public static boolean isDebug() { return get().debug.isTrue(); } public static Debug debug() { return get().debug; } public static SpaceBackend backend() { SpaceContext context = threadLocal.get(); return context == null ? Start.get().configuration().apiBackend() : context.backend; } public static String backendId() { return backend().backendId(); } public boolean isJsonContent() { String contentType = context.header(SpaceHeaders.CONTENT_TYPE); return SpaceHeaders.isJsonContent(contentType); } public static Settings getSettings(String settingsId) { SpaceContext context = get(); return context.settings == null ? null : context.settings.get(settingsId); } public static void setSettings(String settingsId, Settings settings) { SpaceContext context = get(); if (context.settings == null) context.settings = Maps.newHashMap(); context.settings.put(settingsId, settings); } // Check credentials static methods public static SpaceFilter checkAuthorizationFilter() { return (uri, context, nextFilter) -> { get().checkAuthorizationHeader(); return nextFilter.get(); }; } public static Credentials credentials() { return get().credentials; } // Implementation private void checkAuthorizationHeader() { if (!authorizationChecked) { authorizationChecked = true; SpaceContext.debug().credentialCheck(); String headerValue = context.header(SpaceHeaders.AUTHORIZATION); if (headerValue != null) { Credentials userCredentials = null; AuthorizationHeader authHeader = new AuthorizationHeader(headerValue, true); if (authHeader.isBasic()) { userCredentials = CredentialsService.get() .checkUsernamePassword(authHeader.username(), authHeader.password()); } else if (authHeader.isBearer()) { userCredentials = CredentialsService.get() .checkToken(authHeader.token()); } userCredentials.checkReallyEnabled(); checkPasswordMustChange(userCredentials, context); credentials = userCredentials; } } } private void checkPasswordMustChange(Credentials credentials, Context context) { if (credentials.passwordMustChange()) { if (!(Methods.PUT.equals(context.method()) && "/1/credentials/me/password".equals(uri))) throw Exceptions.passwordMustChange(credentials); } } }
package ru.job4j.array; import java.util.Arrays; /** * RotateArray class. * * @author Kuzmin Danila (mailto:bus1d0@mail.ru) * @version $Id$ * @since 0.1 */ public class RotateArray { /** * Invert arrays on 90 degrees. * * @param arrayToChange - array to rotate. * @return rotate array. */ public int[][] rotate(int[][] arrayToChange) { int lengthOfLine; int lengthOfArray = arrayToChange[0].length; int[][] changedArray = new int[lengthOfArray][lengthOfArray]; for (int i = 0; i < lengthOfArray; i++) { changedArray[i] = Arrays.copyOf(arrayToChange[i], lengthOfArray); } for (int i = 0; i < lengthOfArray; i++) { lengthOfLine = lengthOfArray - 1 - 2 * i; for (int j = 0; j < lengthOfLine; j++) { changedArray[j][lengthOfLine - i] = arrayToChange[i][j]; changedArray[lengthOfLine - i][lengthOfLine - j] = arrayToChange[j][lengthOfLine - i]; changedArray[lengthOfLine - j][i] = arrayToChange[lengthOfLine - i][lengthOfLine - j]; changedArray[i][j] = arrayToChange[lengthOfLine - j][i]; } } return changedArray; } }
package pl.edu.icm.coansys.citations.coansys; import java.io.File; import java.util.List; import org.apache.commons.lang3.tuple.Pair; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.testng.annotations.Test; import pl.edu.icm.coansys.commons.hadoop.LocalSequenceFileUtils; import pl.edu.icm.oozierunner.OozieRunner; /** * @author madryk */ public class CoansysCitationMatchingWorkflowIT { @Test public void testCoansysCitationMatchingWorkflow() throws Exception { // given OozieRunner oozieRunner = new OozieRunner(); // execute File workflowOutputData = oozieRunner.run(); // assert List<Pair<Text, BytesWritable>> actualOutputDocIdPicOuts = LocalSequenceFileUtils.readSequenceFile(workflowOutputData, Text.class, BytesWritable.class); List<Pair<Text, BytesWritable>> expectedOutputDocIdPicOuts = LocalSequenceFileUtils.readSequenceFile(new File("src/test/resources/expectedOutput"), Text.class, BytesWritable.class); PicOutAssert.assertDocIdPicOutsEquals(expectedOutputDocIdPicOuts, actualOutputDocIdPicOuts); } }
package net.malisis.core.util; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; /** * @author Ordinastie * */ public class BlockPosUtils { public static BlockPos rotate(BlockPos pos, int rotation) { int[] cos = { 1, 0, -1, 0 }; int[] sin = { 0, 1, 0, -1 }; int a = -rotation & 3; int newX = (pos.getX() * cos[a]) - (pos.getZ() * sin[a]); int newZ = (pos.getX() * sin[a]) + (pos.getZ() * cos[a]); return new BlockPos(newX, pos.getY(), newZ); } public static BlockPos chunkPosition(BlockPos pos) { return new BlockPos(pos.getX() - (pos.getX() >> 4) * 16, pos.getY() - (pos.getY() >> 4) * 16, pos.getZ() - (pos.getZ() >> 4) * 16); } public static Iterable<BlockPos> getAllInBox(AxisAlignedBB aabb) { return BlockPos.getAllInBox(new BlockPos(aabb.minX, aabb.minY, aabb.minZ), new BlockPos(Math.ceil(aabb.maxX) - 1, Math.ceil(aabb.maxY) - 1, Math.ceil(aabb.maxZ) - 1)); } public static ByteBuf toBytes(BlockPos pos) { ByteBuf buf = Unpooled.buffer(8); buf.writeLong(pos.toLong()); return buf; } public static BlockPos fromBytes(ByteBuf buf) { return BlockPos.fromLong(buf.readLong()); } }
package com.zsmartsystems.zigbee.dongle.telegesis.internal; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zsmartsystems.zigbee.dongle.telegesis.ZigBeeDongleTelegesis; import com.zsmartsystems.zigbee.transport.ZigBeePort; import com.zsmartsystems.zigbee.transport.ZigBeePort.FlowControl; import com.zsmartsystems.zigbee.transport.ZigBeeTransportFirmwareCallback; import com.zsmartsystems.zigbee.transport.ZigBeeTransportFirmwareStatus; /** * Firmware update handler for the Telegesis dongle * * @author Chris Jackson * */ public class TelegesisFirmwareUpdateHandler { /** * The logger. */ private final Logger logger = LoggerFactory.getLogger(TelegesisFirmwareUpdateHandler.class); private final InputStream firmware; private final ZigBeePort serialPort; private final ZigBeeTransportFirmwareCallback callback; private final long TIMEOUT_IN_NANOS = TimeUnit.SECONDS.toNanos(10); private final long BL_TIMEOUT_IN_NANOS = TimeUnit.SECONDS.toNanos(3); private final int BYTE_READ_TIMEOUT_IN_MS = 250; private final int MENU_MAX_RETRIES = 5; private final int XMODEM_MAX_RETRIES = 10; private final int XMODEL_CRC_POLYNOMIAL = 0x1021; private final int BOOTLOAD_BAUD_RATE = 115200; private final int DATA_CHUNK_SIZE = 128; private final int CRN = '\n'; private final int SOH = 0x01; private final int EOT = 0x04; private final int ACK = 0x06; private final int NAK = 0x15; private final int CAN = 0x18; private final int XMODEM_CRC_READY = 0x43; // ASCII 'C' /** * Flag to stop the current transfer */ private boolean stopBootload = false; /** * Reference to our master */ private final ZigBeeDongleTelegesis dongle; /** * Constructor for the firmware handler * * @param dongle the {@link ZigBeeDongleTelegesis} to receive the completion notification * @param firmware {@link InputStream} containing the data * @param serialPort {@link ZigBeePort} to communicate on * @param callback {@link ZigBeeTransportFirmwareCallback} to provide status updates */ public TelegesisFirmwareUpdateHandler(ZigBeeDongleTelegesis dongle, InputStream firmware, ZigBeePort serialPort, ZigBeeTransportFirmwareCallback callback) { this.dongle = dongle; this.firmware = firmware; this.serialPort = serialPort; this.callback = callback; } /** * Starts the bootload. * The routine will open the serial port at 115200baud. It will send a CR up to 3 times waiting for the bootloader * prompt. It will then select the upload option, transfer the file, then run. The serial port will then be closed. * */ public void startBootload() { Thread firmwareThread = new Thread("TelegesisFirmwareUpdateHandler") { @Override public void run() { try { doUpdate(); } finally { try { firmware.close(); } catch (IOException e) { // ignored } } } }; firmwareThread.setPriority(Thread.MAX_PRIORITY); firmwareThread.start(); } /** * Cancel a bootload */ public void cancelUpdate() { stopBootload = true; } /** * Waits for {@link #XMODEM_CRC_READY} byte to show up. * * @return true if {@link #XMODEM_CRC_READY} byte was read before {@link #TIMEOUT_IN_NANOS} was reached, false * otherwise. */ private boolean waitForReady() { long start = System.nanoTime(); while (serialPort.read(BYTE_READ_TIMEOUT_IN_MS) != XMODEM_CRC_READY) { if ((System.nanoTime() - start) > TIMEOUT_IN_NANOS) { return false; } try { Thread.sleep(250); } catch (InterruptedException e) { } } return true; } /** * Performs the actual update */ private void doUpdate() { logger.debug("Telegesis bootloader: Starting."); try { Thread.sleep(1500); } catch (InterruptedException e) { // Eat me! } if (!serialPort.open(BOOTLOAD_BAUD_RATE, FlowControl.FLOWCONTROL_OUT_NONE)) { logger.debug("Telegesis bootloader: Failed to open serial port."); transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_FAILED); return; } logger.debug("Telegesis bootloader: Serial port opened."); // Wait for the bootload menu prompt if (!getBlPrompt()) { logger.debug("Telegesis bootloader: Failed waiting for menu before transfer."); transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_FAILED); return; } logger.debug("Telegesis bootloader: Got bootloader prompt."); // Select option 1 to upload the file serialPort.write('1'); // Short delay here to allow all bootloader menu data to be received so there's no confusion with acks. if (!waitForReady()) { logger.debug("Telegesis bootloader: Failed waiting for ready character before starting transfer!"); transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_FAILED); return; } callback.firmwareUpdateCallback(ZigBeeTransportFirmwareStatus.FIRMWARE_TRANSFER_STARTED); boolean bootloadOk = transferFile(); if (bootloadOk) { callback.firmwareUpdateCallback(ZigBeeTransportFirmwareStatus.FIRMWARE_TRANSFER_COMPLETE); logger.debug("Telegesis bootloader: Transfer successful."); } else { logger.debug("Telegesis bootloader: Transfer failed."); } // Short delay here to allow completion. This is mainly required if there was an abort. try { Thread.sleep(5000); } catch (InterruptedException e) { // Eat me! } // Transfer was completed, or aborted. Either way all we can do is run the firmware and it should return // to the main prompt logger.debug("Telegesis bootloader: Waiting for menu."); // Wait for the bootload menu prompt if (!getBlPrompt()) { logger.debug("Telegesis bootloader: Failed waiting for menu after transfer."); transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_FAILED); return; } // Select 2 to run logger.debug("Telegesis bootloader: Running firmware."); serialPort.write('2'); // Short delay here to allow all bootloader to run. try { Thread.sleep(500); } catch (InterruptedException e) { // Eat me! } logger.debug("Telegesis bootloader: Done."); // We're done - either we completed, or it was cancelled if (!bootloadOk) { transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_FAILED); } else if (stopBootload) { transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_CANCELLED); } else { transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_COMPLETE); } } /** * Waits for the Telegesis bootloader "BL >" response * * @return true if the prompt is found */ private boolean getBlPrompt() { int[] matcher = new int[] { 'B', 'L', ' ', '>' }; int matcherCount = 0; int retryCount = 0; while (retryCount < MENU_MAX_RETRIES) { try { Thread.sleep(1500); } catch (InterruptedException e) { // Eat me! } serialPort.purgeRxBuffer(); // Send CR to wake up the bootloader serialPort.write(CRN); long start = System.nanoTime(); while ((System.nanoTime() - start) < BL_TIMEOUT_IN_NANOS) { int val = serialPort.read(BYTE_READ_TIMEOUT_IN_MS); if (val == -1) { continue; } if (logger.isTraceEnabled()) { logger.trace("Ember bootloader: get prompt read {}", String.format("%02X %c", val, val)); } if (val != matcher[matcherCount]) { matcherCount = 0; continue; } matcherCount++; if (matcherCount == matcher.length) { return true; } } retryCount++; } logger.debug("Telegesis bootloader: Unable to get bootloader prompt."); transferComplete(ZigBeeTransportFirmwareStatus.FIRMWARE_UPDATE_FAILED); return false; } private ByteBuffer readChunk(InputStream is) throws IOException { ByteBuffer byteBuffer = ByteBuffer.allocate(DATA_CHUNK_SIZE); int data; // read until we either got DATA_CHUNK_SIZE bytes or the stream has reached its end while (byteBuffer.hasRemaining() && (data = is.read()) != -1) { byteBuffer.put((byte) data); } return byteBuffer; } /** * Sends End Of Transfer frame and waits for ACK response, retries up to {@link #XMODEM_MAX_RETRIES} times. */ private void sendEOT() { int retries = 0; do { serialPort.write(EOT); try { Thread.sleep(250); } catch (InterruptedException e) { // ignored } } while (getTransferResponse() != ACK && retries++ < XMODEM_MAX_RETRIES); } private String byteToHex(byte num) { char[] hexDigits = new char[2]; hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16); hexDigits[1] = Character.forDigit((num & 0xF), 16); return new String(hexDigits); } private String encodeHexString(byte[] byteArray) { StringBuffer hexStringBuffer = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { hexStringBuffer.append(byteToHex(byteArray[i])).append(" "); } return hexStringBuffer.toString(); } /** * Transfers the file using the XModem protocol * * @return true if the transfer completed successfully */ private boolean transferFile() { int retries; int response; int frame = 1; boolean done; boolean cancelTransfer = false; // Clear all input in the input stream before starting the transfer try { logger.debug("Telegesis bootloader: Clearing input stream..."); serialPort.purgeRxBuffer(); logger.debug("Telegesis bootloader: Starting transfer."); while (!stopBootload && !cancelTransfer) { retries = 0; // Output DATA_CHUNK_SIZE bytes ByteBuffer data = readChunk(firmware); done = data.position() < DATA_CHUNK_SIZE; do { logger.debug("Telegesis bootloader: Transfer frame {}, attempt {}.", frame, retries); // Send SOH if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: Write SOH"); } serialPort.write(SOH); if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: Write frame count"); } // Send frame count serialPort.write(frame); serialPort.write(255 - frame); // Allow 10 retries if (retries++ > XMODEM_MAX_RETRIES) { sendEOT(); return false; } if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: Chunk data hasArray: {}", data.hasArray()); logger.trace("Telegesis bootloader: Chunk data len: {}", data.array().length); logger.trace("Telegesis bootloader: Chunk data: {}, done: {}", encodeHexString(data.array()), done); } int crc = 0; int countWriteCalls = 0; for (int value : data.array()) { serialPort.write(value); countWriteCalls++; for (int i = 0; i < 8; i++) { boolean bit = ((value >> (7 - i) & 1) == 1); boolean c15 = ((crc >> 15 & 1) == 1); crc <<= 1; // If coefficient of bit and remainder polynomial = 1 xor crc with polynomial if (c15 ^ bit) { crc ^= XMODEL_CRC_POLYNOMIAL; } } } crc &= 0xffff; if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: Number of serialPort.write invocations: {}", countWriteCalls); logger.trace("Telegesis bootloader: CRC for chunk: {}", crc); logger.trace("Telegesis bootloader: Write CRC"); } serialPort.write((crc >> 8) & 0xff); serialPort.write(crc & 0xff); // Wait for the acknowledgment do { response = getTransferResponse(); } while (response == XMODEM_CRC_READY); if (logger.isTraceEnabled()) { logger.debug("Telegesis bootloader: Response {}.", response); } if (response == CAN) { logger.debug("Telegesis bootloader: Received CAN."); retries = XMODEM_MAX_RETRIES; cancelTransfer = true; break; } } while (response != ACK); if (done) { logger.debug("Telegesis bootloader: Transfer complete."); sendEOT(); return true; } frame = (frame + 1) & 0xff; } } catch (IOException e) { logger.debug("Telegesis bootloader: Transfer failed due IO error."); } serialPort.write(EOT); return false; } /** * Waits for a single byte response as part of the XModem protocol * * @return the value of the received data, or NAK on timeout */ private int getTransferResponse() { long start = System.nanoTime(); while (!stopBootload) { int val = serialPort.read(BYTE_READ_TIMEOUT_IN_MS); if (val == -1) { if ((System.nanoTime() - start) > TIMEOUT_IN_NANOS) { if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: getTransferResponse timeout returning NAK."); } return NAK; } continue; } else { if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: getTransferResponse read value {}", val); } return val; } } if (logger.isTraceEnabled()) { logger.trace("Telegesis bootloader: NAK default case returning NAK"); } return NAK; } /** * Clean up and notify everyone that we're done. * * @param status the final {@link ZigBeeTransportFirmwareStatus} at completion */ private void transferComplete(ZigBeeTransportFirmwareStatus status) { serialPort.close(); callback.firmwareUpdateCallback(status); dongle.bootloadComplete(); } }
package net.ucanaccess.converters; import java.math.BigDecimal; import java.math.MathContext; import java.sql.Timestamp; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import net.ucanaccess.converters.TypesMap.AccessType; import net.ucanaccess.ext.FunctionType; import net.ucanaccess.jdbc.UcanaccessSQLException; import net.ucanaccess.jdbc.UcanaccessSQLException.ExceptionMessages; public class Functions { public final static SimpleDateFormat[] SDFA = new SimpleDateFormat[] { new SimpleDateFormat("MMM dd,yyyy"), new SimpleDateFormat("MM dd,yyyy"), new SimpleDateFormat("MM/dd/yyyy"), new SimpleDateFormat("MMM dd hh:mm:ss"), new SimpleDateFormat("MM dd hh:mm:ss"), new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"), new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("MM/dd/yyyy hh:mm:ss") }; public static final SimpleDateFormat SDFBB = new SimpleDateFormat( "yyyy-MM-dd"); @FunctionType(functionName = "ASC", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG) public static Integer asc(String s) { if (s == null || s.length() == 0) return null; return (int) s.charAt(0); } @FunctionType(functionName = "ATN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double atn(double v) { return Math.atan(v); } @FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.YESNO) public static boolean cbool(BigDecimal value) { return cbool((Object) value); } @FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.YESNO }, returnType = AccessType.YESNO) public static boolean cbool(Boolean value) { return cbool((Object) value); } private static boolean cbool(Object obj) { boolean r = (obj instanceof Boolean) ? (Boolean) obj : (obj instanceof String) ? Boolean.valueOf((String) obj) : (obj instanceof Number) ? ((Number) obj) .doubleValue() != 0 : false; return r; } @FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean cbool(String value) { return cbool((Object) value); } @FunctionType(functionName = "CCUR", argumentTypes = { AccessType.CURRENCY }, returnType = AccessType.CURRENCY) public static BigDecimal ccur(BigDecimal value) throws UcanaccessSQLException { return value.setScale(4, BigDecimal.ROUND_HALF_UP);// .doubleValue(); } @FunctionType(functionName = "CDATE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DATETIME) public static Timestamp cdate(String dt) { return dateValue(dt); } @FunctionType(functionName = "CDBL", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double cdbl(Double value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CDEC", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double cdec(Double value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CINT", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.INTEGER) public static Short cint(Double value) throws UcanaccessSQLException { return new BigDecimal((long) Math.floor(value + 0.499999999999999d)) .shortValueExact(); } @FunctionType(functionName = "CLONG", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG) public static Integer clong(Double value) throws UcanaccessSQLException { return (int) Math.floor(value + 0.499999999999999d); } @FunctionType(functionName = "CSIGN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.SINGLE) public static double csign(double value) { MathContext mc = new MathContext(7); return new BigDecimal(value, mc).doubleValue(); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.YESNO }, returnType = AccessType.MEMO) public static String cstr(Boolean value) throws UcanaccessSQLException { return cstr((Object) value); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.MEMO) public static String cstr(double value) throws UcanaccessSQLException { return cstr((Object) value); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.LONG }, returnType = AccessType.MEMO) public static String cstr(int value) throws UcanaccessSQLException { return cstr((Object) value); } public static String cstr(Object value) throws UcanaccessSQLException { return value == null ? null : format(value.toString(), ""); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.MEMO) public static String cstr(Timestamp value) throws UcanaccessSQLException { return value == null ? null : format(value, "general date"); } @FunctionType(functionName = "CVAR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.MEMO) public static String cvar(Double value) throws UcanaccessSQLException { return format(value, "general number"); } @FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Date dateAdd(String intv, int vl, Date dt) throws UcanaccessSQLException { if (dt == null || intv == null) return null; Calendar cl = Calendar.getInstance(); cl.setTime(dt); if (intv.equalsIgnoreCase("yyyy")) { cl.add(Calendar.YEAR, vl); } else if (intv.equalsIgnoreCase("q")) { cl.add(Calendar.MONTH, vl * 3); } else if (intv.equalsIgnoreCase("y") || intv.equalsIgnoreCase("d")) { cl.add(Calendar.DAY_OF_YEAR, vl); } else if (intv.equalsIgnoreCase("m")) { cl.add(Calendar.MONTH, vl); } else if (intv.equalsIgnoreCase("w")) { cl.add(Calendar.DAY_OF_WEEK, vl); } else if (intv.equalsIgnoreCase("ww")) { cl.add(Calendar.WEEK_OF_YEAR, vl); } else if (intv.equalsIgnoreCase("h")) { cl.add(Calendar.HOUR, vl); } else if (intv.equalsIgnoreCase("n")) { cl.add(Calendar.MINUTE, vl); } else if (intv.equalsIgnoreCase("s")) { cl.add(Calendar.SECOND, vl); } else throw new UcanaccessSQLException( ExceptionMessages.INVALID_INTERVAL_VALUE); return (dt instanceof Timestamp) ? new Timestamp(cl.getTimeInMillis()) : new java.sql.Date(cl.getTimeInMillis()); } @FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Timestamp dateAdd(String intv, int vl, Timestamp dt) throws UcanaccessSQLException { return (Timestamp) dateAdd(intv, vl, (Date) dt); } @FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer dateDiff(String intv, Timestamp dt1, Timestamp dt2) throws UcanaccessSQLException { if (dt1 == null || intv == null || dt2 == null) return null; Calendar clMin = Calendar.getInstance(); Calendar clMax = Calendar.getInstance(); int sign = dt1.after(dt2) ? -1 : 1; if (sign == 1) { clMax.setTime(dt2); clMin.setTime(dt1); } else { clMax.setTime(dt1); clMin.setTime(dt2); } clMin.set(Calendar.MILLISECOND, 0); clMax.set(Calendar.MILLISECOND, 0); Integer result; if (intv.equalsIgnoreCase("yyyy")) { result = clMax.get(Calendar.YEAR) - clMin.get(Calendar.YEAR); } else if (intv.equalsIgnoreCase("q")) { result = dateDiff("yyyy", dt1, dt2) * 4 + (clMax.get(Calendar.MONTH) - clMin.get(Calendar.MONTH)) / 3; } else if (intv.equalsIgnoreCase("y") || intv.equalsIgnoreCase("d")) { result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / (1000 * 60 * 60 * 24))); } else if (intv.equalsIgnoreCase("m")) { result = dateDiff("yyyy", dt1, dt2) * 12 + (clMax.get(Calendar.MONTH) - clMin.get(Calendar.MONTH)); } else if (intv.equalsIgnoreCase("w") || intv.equalsIgnoreCase("ww")) { result = (int) Math .floor(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / (1000 * 60 * 60 * 24 * 7))); } else if (intv.equalsIgnoreCase("h")) { result = (int) Math .round(((double) (clMax.getTime().getTime() - clMin .getTime().getTime())) / (1000d * 60 * 60)); } else if (intv.equalsIgnoreCase("n")) { result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / (1000 * 60))); } else if (intv.equalsIgnoreCase("s")) { result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / 1000)); } else throw new UcanaccessSQLException( ExceptionMessages.INVALID_INTERVAL_VALUE); return result * sign; } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.LONG }, returnType = AccessType.LONG) public static Integer datePart(String intv, Timestamp dt, Integer firstDayOfWeek) throws UcanaccessSQLException { Integer ret = (intv.equalsIgnoreCase("ww"))?datePart(intv, dt,firstDayOfWeek,1):datePart(intv, dt); if (intv.equalsIgnoreCase("w") && firstDayOfWeek > 1) { Calendar cl = Calendar.getInstance(); cl.setTime(dt); ret = cl.get(Calendar.DAY_OF_WEEK)-firstDayOfWeek+1; if(ret<=0)ret=7+ret; } return ret; } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG) public static Integer datePart(String intv, Timestamp dt, Integer firstDayOfWeek, Integer firstWeekOfYear) throws UcanaccessSQLException { Integer ret = datePart(intv, dt); if (intv.equalsIgnoreCase("ww") && (firstWeekOfYear > 1||firstDayOfWeek>1)) { Calendar cl = Calendar.getInstance(); cl.setTime(dt); cl.set(Calendar.MONTH, Calendar.JANUARY); cl.set(Calendar.DAY_OF_MONTH, 1); Calendar cl1 = Calendar.getInstance(); cl1.setTime(dt); if(firstDayOfWeek==0)firstDayOfWeek=1; int dow= cl.get(Calendar.DAY_OF_WEEK)-firstDayOfWeek+1; if(dow<=0){ dow=7+dow; if(cl1.get(Calendar.DAY_OF_WEEK)-firstDayOfWeek>=0) ret++; } if (dow > 4 && firstWeekOfYear == 2) { ret } if (dow>1 && firstWeekOfYear == 3) { ret } } return ret; } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer datePart(String intv, Timestamp dt) throws UcanaccessSQLException { if (dt == null || intv == null) return null; Calendar cl = Calendar.getInstance(Locale.US); cl.setTime(dt); if (intv.equalsIgnoreCase("yyyy")) { return cl.get(Calendar.YEAR); } else if (intv.equalsIgnoreCase("q")) { return (int) Math.ceil((cl.get(Calendar.MONTH) + 1) / 3d); } else if (intv.equalsIgnoreCase("d")) { return cl.get(Calendar.DAY_OF_MONTH); } else if (intv.equalsIgnoreCase("y")) { return cl.get(Calendar.DAY_OF_YEAR); } else if (intv.equalsIgnoreCase("m")) { return cl.get(Calendar.MONTH) + 1; } else if (intv.equalsIgnoreCase("ww")) { return cl.get(Calendar.WEEK_OF_YEAR); } else if (intv.equalsIgnoreCase("w")) { return cl.get(Calendar.DAY_OF_WEEK); } else if (intv.equalsIgnoreCase("h")) { return cl.get(Calendar.HOUR_OF_DAY); } else if (intv.equalsIgnoreCase("n")) { return cl.get(Calendar.MINUTE); } else if (intv.equalsIgnoreCase("s")) { return cl.get(Calendar.SECOND); } else throw new UcanaccessSQLException( ExceptionMessages.INVALID_INTERVAL_VALUE); } @FunctionType(functionName = "DATESERIAL", argumentTypes = { AccessType.LONG, AccessType.LONG, AccessType.LONG }, returnType = AccessType.DATETIME) public static Timestamp dateSerial(int year, int month, int day) { Calendar cl = Calendar.getInstance(); cl.setLenient(true); cl.set(Calendar.YEAR, year); cl.set(Calendar.MONTH, month - 1); cl.set(Calendar.DAY_OF_MONTH, day); cl.set(Calendar.HOUR_OF_DAY, 0); cl.set(Calendar.MINUTE, 0); cl.set(Calendar.SECOND, 0); cl.set(Calendar.MILLISECOND, 0); return new Timestamp(cl.getTime().getTime()); } @FunctionType(functionName = "DATEVALUE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DATETIME) public static Timestamp dateValue(String dt) { for (SimpleDateFormat sdf : SDFA) try { sdf.setLenient(true); return new Timestamp(sdf.parse(dt).getTime()); } catch (ParseException e) { } return null; } @FunctionType(functionName = "DATEVALUE", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Timestamp dateValue(Timestamp dt) { Calendar cl = Calendar.getInstance(); cl.setTime(dt); cl.set(Calendar.HOUR_OF_DAY, 0); cl.set(Calendar.MINUTE, 0); cl.set(Calendar.SECOND, 0); cl.set(Calendar.MILLISECOND, 0); return new Timestamp(cl.getTime().getTime()); } @FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.DOUBLE, AccessType.TEXT }, returnType = AccessType.TEXT) public static String format(double d, String par) throws UcanaccessSQLException { if ("percent".equalsIgnoreCase(par)) { return (new BigDecimal(d * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%").replace(".", ","); } if ("fixed".equalsIgnoreCase(par)) { return new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP) .toString().replace(".", ","); } if ("standard".equalsIgnoreCase(par)) { DecimalFormat formatter = new DecimalFormat(" return formatter.format(d); } if ("general number".equalsIgnoreCase(par)) { DecimalFormat formatter = new DecimalFormat(); DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator(','); formatter.setGroupingUsed(false); formatter.setDecimalFormatSymbols(dfs); return formatter.format(d); } if ("yes/no".equalsIgnoreCase(par)) { return d == 0 ? "No" : "Yes"; } if ("true/false".equalsIgnoreCase(par)) { return d == 0 ? "False" : "True"; } if ("On/Off".equalsIgnoreCase(par)) { return d == 0 ? "Off" : "On"; } if ("Scientific".equalsIgnoreCase(par)) { return String.format(Locale.US, "%6.2E", d).replace(".", ","); } try { DecimalFormat formatter = new DecimalFormat(par); return formatter.format(d); } catch (Exception e) { throw new UcanaccessSQLException(e); } } @FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.TEXT, AccessType.TEXT }, returnType = AccessType.TEXT) public static String format(String s, String par) throws UcanaccessSQLException { if (isNumeric(s)) { return format(Double.parseDouble(s), par); } if (isDate(s)) { return format(dateValue(s), par); } return s; } @FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.DATETIME, AccessType.TEXT }, returnType = AccessType.TEXT) public static String format(Timestamp t, String par) throws UcanaccessSQLException { if ("long date".equalsIgnoreCase(par)) { return new SimpleDateFormat("EEEE d MMMM yyyy").format(t); } if ("medium date".equalsIgnoreCase(par)) { return new SimpleDateFormat("d-MMM-yy").format(t); } if ("short date".equalsIgnoreCase(par)) { return new SimpleDateFormat("dd/MM/yyyy").format(t); } if ("general date".equalsIgnoreCase(par)) { return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(t); } if ("long time".equalsIgnoreCase(par)) { return new SimpleDateFormat("HH:mm:ss").format(t); } if ("medium time".equalsIgnoreCase(par)) { return new SimpleDateFormat("hh:mm").format(t); } if ("short time".equalsIgnoreCase(par)) { return new SimpleDateFormat("HH:mm").format(t); } if("q".equalsIgnoreCase(par)){ return String.valueOf(datePart(par, t)); } return new SimpleDateFormat(par.replaceAll("m", "M").replaceAll("n", "m")).format(t); } @FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO, AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.MEMO) public static String iif(boolean b, String o, String o1) { return b ? o : o1; } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.LONG, AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer instr(Integer start, String text, String search) { return instr(start, text, search, -1); } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.LONG, AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instr(Integer start, String text, String search, Integer compare) { start if (compare != 0) text = text.toLowerCase(); if (text.length() <= start) { return 0; } else text = text.substring(start); return text.indexOf(search) + start + 1; } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer instr(String text, String search) { return instr(1, text, search, -1); } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instr(String text, String search, Integer compare) { return instr(1, text, search, compare); } @FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.TEXT, AccessType.TEXT }, returnType = AccessType.LONG) public static Integer instrrev(String text, String search) { return instrrev(text, search, -1, -1); } @FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instrrev(String text, String search, Integer start) { return instrrev(text, search, start, -1); } @FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instrrev(String text, String search, Integer start, Integer compare) { if (compare != 0) text = text.toLowerCase(); if (text.length() <= start) { return 0; } else { if (start > 0) text = text.substring(0, start); return text.lastIndexOf(search) + 1; } } @FunctionType(functionName = "ISDATE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean isDate(String dt) { return dateValue(dt) != null; } @FunctionType(functionName = "ISDATE", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.YESNO) public static boolean isDate(Timestamp dt) { return true; } @FunctionType(namingConflict = true, functionName = "IsNull", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean isNull(String o) { return o == null; } @FunctionType(functionName = "ISNUMERIC", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.YESNO) public static boolean isNumeric(BigDecimal b) { return true; } @FunctionType(functionName = "ISNUMERIC", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean isNumeric(String s) { try { new BigDecimal(s); return true; } catch (Exception e) { } return false; } @FunctionType(functionName = "LEN", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG) public static Integer len(String o) { if (o == null) return null; return new Integer(o.length()); } @FunctionType(functionName = "MID", argumentTypes = { AccessType.MEMO, AccessType.LONG}, returnType = AccessType.MEMO) public static String mid(String value, int start) { return mid( value, start,value.length()); } @FunctionType(functionName = "MID", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.LONG }, returnType = AccessType.MEMO) public static String mid(String value, int start, int length) { if (value == null) return null; int len = start - 1 + length; if (start < 1) throw new RuntimeException("Invalid function call"); if (len > value.length()) { len = value.length(); } return value.substring(start - 1, len); } @FunctionType(namingConflict = true, functionName = "MONTHNAME", argumentTypes = { AccessType.LONG }, returnType = AccessType.TEXT) public static String monthName(int i) throws UcanaccessSQLException { return monthName(i, false); } @FunctionType(namingConflict = true, functionName = "MONTHNAME", argumentTypes = { AccessType.LONG, AccessType.YESNO }, returnType = AccessType.TEXT) public static String monthName(int i, boolean abbr) throws UcanaccessSQLException { i if (i >= 0 && i <= 11) { DateFormatSymbols dfs = new DateFormatSymbols(); return abbr ? dfs.getShortMonths()[i] : dfs.getMonths()[i]; } throw new UcanaccessSQLException(ExceptionMessages.INVALID_MONTH_NUMBER); } @FunctionType(functionName = "DATE", argumentTypes = {}, returnType = AccessType.DATETIME) public static Timestamp date() { Calendar cl=Calendar.getInstance(); cl.set(Calendar.MILLISECOND, 0); cl.set(Calendar.SECOND, 0); cl.set(Calendar.MINUTE, 0); cl.set(Calendar.HOUR_OF_DAY,0); return new Timestamp(cl.getTime().getTime()); } @FunctionType(namingConflict = true, functionName = "NOW", argumentTypes = {}, returnType = AccessType.DATETIME) public static Timestamp now() { Calendar cl = Calendar.getInstance(); cl.set(Calendar.MILLISECOND, 0); return new Timestamp(cl.getTime().getTime()); } private static Object nz(Object value, Object outher) { return value == null ? outher : value; } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.MEMO }, returnType = AccessType.MEMO) public static String nz(String value) { return value == null ? "" : value; } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.MEMO) public static String nz(String value, String outher) { return (String) nz((Object) value, (Object) outher); } @FunctionType(functionName = "SIGN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.INTEGER) public static short sign(double n) { return (short) (n == 0 ? 0 : (n > 0 ? 1 : -1)); } @FunctionType(functionName = "SPACE", argumentTypes = { AccessType.LONG }, returnType = AccessType.MEMO) public static String space(Integer nr) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < nr; ++i) sb.append(' '); return sb.toString(); } @FunctionType(functionName = "STR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.TEXT) public static String str(double d) { String pre = d > 0 ? " " : ""; return Math.round(d) == d ? pre + Math.round(d) : pre + d; } @FunctionType(functionName = "TIME", argumentTypes = {}, returnType = AccessType.DATETIME) public static Timestamp time() { Calendar cl = Calendar.getInstance(); cl.setTime(now()); cl.set(1899, 11, 30); return new java.sql.Timestamp(cl.getTimeInMillis()); } @FunctionType(functionName = "VAL", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.DOUBLE) public static Double val(BigDecimal val1) { return val((Object) val1); } private static Double val(Object val1) { if (val1 == null) return null; String val = val1.toString().trim(); int lp = val.lastIndexOf("."); char[] ca = val.toCharArray(); StringBuffer sb = new StringBuffer(); int minLength = 1; for (int i = 0; i < ca.length; i++) { char c = ca[i]; if (((c == '-') || (c == '+')) && (i == 0)) { ++minLength; sb.append(c); } else if (c == ' ') continue; else if (Character.isDigit(c)) { sb.append(c); } else if (c == '.' && i == lp) { sb.append(c); if (i == 0 || (i == 1 && minLength == 2)) { ++minLength; } } else break; } if (sb.length() < minLength) return 0.0d; else return Double.parseDouble(sb.toString()); } @FunctionType(functionName = "VAL", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DOUBLE) public static Double val(String val1) { return val((Object) val1); } @FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG }, returnType = AccessType.TEXT) public static String weekDayName(int i) { return weekDayName(i, false); } @FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG, AccessType.YESNO }, returnType = AccessType.TEXT) public static String weekDayName(int i, boolean abbr) { return weekDayName(i, abbr, 1); } @FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG, AccessType.YESNO, AccessType.LONG }, returnType = AccessType.TEXT) public static String weekDayName(int i, boolean abbr, int s) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, i + s - 1); String pattern = abbr ? "%ta" : "%tA"; return String.format(pattern, cal, cal); } @FunctionType(functionName = "WEEKDAY", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer weekDay(Timestamp dt ) throws UcanaccessSQLException { return datePart("w", dt); } @FunctionType(functionName = "WEEKDAY", argumentTypes = { AccessType.DATETIME,AccessType.LONG }, returnType = AccessType.LONG) public static Integer weekDay(Timestamp dt,Integer firstDayOfWeek ) throws UcanaccessSQLException { return datePart("w", dt,firstDayOfWeek); } @FunctionType(functionName = "STRING", argumentTypes = { AccessType.LONG,AccessType.MEMO }, returnType = AccessType.MEMO) public static String string(Integer nr, String str ) throws UcanaccessSQLException { if(str==null)return null; String ret=""; for(int i=0;i<nr;++i){ ret+=str.charAt(0); } return ret; } @FunctionType(functionName = "TIMESERIAL", argumentTypes = {AccessType.LONG,AccessType.LONG,AccessType.LONG}, returnType = AccessType.DATETIME) public static Timestamp timeserial(Integer h,Integer m,Integer s) { Calendar cl = Calendar.getInstance(); cl.setTime(now()); cl.set(1899, 11, 30,h,m,s); return new java.sql.Timestamp(cl.getTimeInMillis()); } }
package nl.mpi.kinnate.svg; import java.awt.geom.AffineTransform; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import org.apache.batik.bridge.UpdateManager; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGLocatable; import org.w3c.dom.svg.SVGRect; public class SvgUpdateHandler { private GraphPanel graphPanel; private KinTermSavePanel kinTermSavePanel; private boolean dragUpdateRequired = false; private boolean threadRunning = false; private int updateDragNodeX = 0; private int updateDragNodeY = 0; private float[][] dragRemainders = null; protected SvgUpdateHandler(GraphPanel graphPanelLocal, KinTermSavePanel kinTermSavePanelLocal) { graphPanel = graphPanelLocal; kinTermSavePanel = kinTermSavePanelLocal; } protected void updateSvgSelectionHighlights() { if (kinTermSavePanel != null) { String kinTypeStrings = ""; for (String entityID : graphPanel.selectedGroupId) { if (kinTypeStrings.length() != 0) { kinTypeStrings = kinTypeStrings + "|"; } kinTypeStrings = kinTypeStrings + graphPanel.getKinTypeForElementId(entityID); } if (kinTypeStrings != null) { kinTermSavePanel.setSelectedKinTypeSting(kinTypeStrings); } } UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { // todo: there may be issues related to the updateManager being null, this should be looked into if symptoms arise. updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { if (graphPanel.doc != null) { // for (String groupString : new String[]{"EntityGroup", "LabelsGroup"}) { // Element entityGroup = graphPanel.doc.getElementById(groupString); { Element entityGroup = graphPanel.doc.getElementById("EntityGroup"); for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { if ("g".equals(currentChild.getLocalName())) { Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); if (idAttrubite != null) { String entityId = idAttrubite.getTextContent(); System.out.println("group id: " + entityId); Node existingHighlight = null; // find any existing highlight for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) { if ("rect".equals(subGoupNode.getLocalName())) { Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id"); if (subGroupIdAttrubite != null) { if ("highlight".equals(subGroupIdAttrubite.getTextContent())) { existingHighlight = subGoupNode; } } } } if (!graphPanel.selectedGroupId.contains(entityId)) { // remove all old highlights if (existingHighlight != null) { currentChild.removeChild(existingHighlight); } // add the current highlights } else { if (existingHighlight == null) { // svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); SVGRect bbox = ((SVGLocatable) currentChild).getBBox(); // System.out.println("bbox X: " + bbox.getX()); // System.out.println("bbox Y: " + bbox.getY()); // System.out.println("bbox W: " + bbox.getWidth()); // System.out.println("bbox H: " + bbox.getHeight()); Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); int paddingDistance = 20; symbolNode.setAttribute("id", "highlight"); symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance)); symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance)); symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2)); symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2)); symbolNode.setAttribute("fill", "none"); symbolNode.setAttribute("stroke-width", "1"); if (graphPanel.selectedGroupId.indexOf(entityId) == 0) { symbolNode.setAttribute("stroke-dasharray", "3"); symbolNode.setAttribute("stroke-dashoffset", "0"); } else { symbolNode.setAttribute("stroke-dasharray", "6"); symbolNode.setAttribute("stroke-dashoffset", "0"); } symbolNode.setAttribute("stroke", "blue"); // symbolNode.setAttribute("id", "Highlight"); // symbolNode.setAttribute("id", "Highlight"); // symbolNode.setAttribute("id", "Highlight"); // symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;" // + "stroke-dasharray:1, 1;stroke-dashoffset:0"); currentChild.appendChild(symbolNode); } } } } } } } } }); } } protected void dragCanvas(int updateDragNodeXLocal, int updateDragNodeYLocal) { AffineTransform at = new AffineTransform(); at.translate(updateDragNodeXLocal, updateDragNodeYLocal); at.concatenate(graphPanel.svgCanvas.getRenderingTransform()); graphPanel.svgCanvas.setRenderingTransform(at); } protected void startDrag() { // dragRemainders is used to store the remainder after snap between drag updates dragRemainders = null; } protected void updateDragNode(int updateDragNodeXLocal, int updateDragNodeYLocal) { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); synchronized (SvgUpdateHandler.this) { dragUpdateRequired = true; updateDragNodeX += updateDragNodeXLocal; updateDragNodeY += updateDragNodeYLocal; if (!threadRunning) { threadRunning = true; updateManager.getUpdateRunnableQueue().invokeLater(getRunnable()); } } } private Runnable getRunnable() { return new Runnable() { public void run() { if (dragRemainders == null) { dragRemainders = new float[graphPanel.selectedGroupId.size()][]; for (int dragCounter = 0; dragCounter < dragRemainders.length; dragCounter++) { dragRemainders[dragCounter] = new float[]{0, 0}; } } boolean continueUpdating = true; while (continueUpdating) { continueUpdating = false; int updateDragNodeXInner; int updateDragNodeYInner; synchronized (SvgUpdateHandler.this) { dragUpdateRequired = false; updateDragNodeXInner = updateDragNodeX; updateDragNodeYInner = updateDragNodeY; updateDragNodeX = 0; updateDragNodeY = 0; } // System.out.println("updateDragNodeX: " + updateDragNodeXInner); // System.out.println("updateDragNodeY: " + updateDragNodeYInner); if (graphPanel.doc == null || graphPanel.dataStoreSvg.graphData == null) { GuiHelper.linorgBugCatcher.logError(new Exception("graphData or the svg document is null, is this an old file format? try redrawing before draging.")); } else { boolean allRealtionsSelected = true; relationLoop: for (EntityData selectedEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (selectedEntity.isVisible && graphPanel.selectedGroupId.contains(selectedEntity.getUniqueIdentifier())) { for (EntityRelation entityRelation : selectedEntity.getVisiblyRelateNodes()) { EntityData relatedEntity = entityRelation.getAlterNode(); if (relatedEntity.isVisible && !graphPanel.selectedGroupId.contains(relatedEntity.getUniqueIdentifier())) { allRealtionsSelected = false; break relationLoop; } } } } int dragCounter = 0; for (String entityId : graphPanel.selectedGroupId) { // store the remainder after snap for re use on each update dragRemainders[dragCounter] = graphPanel.entitySvg.moveEntity(graphPanel.doc, entityId, updateDragNodeXInner + dragRemainders[dragCounter][0], updateDragNodeYInner + dragRemainders[dragCounter][1], graphPanel.dataStoreSvg.snapToGrid, allRealtionsSelected); dragCounter++; } // Element entityGroup = doc.getElementById("EntityGroup"); // for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { // if ("g".equals(currentChild.getLocalName())) { // Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); // if (idAttrubite != null) { // String entityPath = idAttrubite.getTextContent(); // if (selectedGroupElement.contains(entityPath)) { // SVGRect bbox = ((SVGLocatable) currentChild).getBBox(); //// ((SVGLocatable) currentDraggedElement).g // // drageboth x and y //// ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeYInner - bbox.getY()) + ")"); // // limit drag to x only // ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", 0)"); //// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeXInner)); //// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeYInner)); // // SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox(); //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); //// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned //// SVGLocatable.getTransformToElement() //// SVGPoint.matrixTransform() int vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(graphPanel.dataStoreSvg.graphData.gridHeight); int hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(graphPanel.dataStoreSvg.graphData.gridWidth); new RelationSvg().updateRelationLines(graphPanel, graphPanel.selectedGroupId, graphPanel.svgNameSpace, hSpacing, vSpacing); //new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg")); } synchronized (SvgUpdateHandler.this) { continueUpdating = dragUpdateRequired; if (!continueUpdating) { threadRunning = false; } } } } }; } public void addLabel(final String labelString, final float xPos, final float yPos) { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { Element labelGroup = graphPanel.doc.getElementById("LabelsGroup"); Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("x", Float.toString(xPos)); labelText.setAttribute("y", Float.toString(yPos)); labelText.setAttribute("fill", "black"); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "28"); labelText.setAttribute("id", "label" + labelGroup.getChildNodes().getLength()); Text textNode = graphPanel.doc.createTextNode(labelString); labelText.appendChild(textNode); // todo: put this into a geometry group and allow for selection and drag labelGroup.appendChild(labelText); // graphPanel.doc.getDocumentElement().appendChild(labelText); ((EventTarget) labelText).addEventListener("mousedown", new MouseListenerSvg(graphPanel), false); } }); } } }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.ArrayWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import java.lang.Integer; import java.util.StringTokenizer; import java.util.TreeSet; // >>> Don't Change public class TopPopularLinks extends Configured implements Tool { public static final Log LOG = LogFactory.getLog(TopPopularLinks.class); public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new TopPopularLinks(), args); System.exit(res); } public static class IntArrayWritable extends ArrayWritable { public IntArrayWritable() { super(IntWritable.class); } public IntArrayWritable(Integer[] numbers) { super(IntWritable.class); IntWritable[] ints = new IntWritable[numbers.length]; for (int i = 0; i < numbers.length; i++) { ints[i] = new IntWritable(numbers[i]); } set(ints); } } // <<< Don't Change @Override public int run(String[] args) throws Exception { Configuration conf = this.getConf(); FileSystem fs = FileSystem.get(conf); Path tmpPath = new Path("/mp2/tmp"); fs.delete(tmpPath, true); Job jobA = Job.getInstance(conf, "Links Count"); jobA.setOutputKeyClass(Text.class); jobA.setOutputValueClass(IntWritable.class); jobA.setMapperClass(LinkCountMap.class); jobA.setReducerClass(LinkCountReduce.class); FileInputFormat.setInputPaths(jobA, new Path(args[0])); FileOutputFormat.setOutputPath(jobA, tmpPath); jobA.setJarByClass(TopPopularLinks.class); jobA.waitForCompletion(true); Job jobB = Job.getInstance(conf, "Top Links"); jobB.setOutputKeyClass(Text.class); jobB.setOutputValueClass(IntWritable.class); jobB.setMapOutputKeyClass(NullWritable.class); jobB.setMapOutputValueClass(TextArrayWritable.class); jobB.setMapperClass(TopLinksMap.class); jobB.setReducerClass(TopLinksReduce.class); jobB.setNumReduceTasks(1); FileInputFormat.setInputPaths(jobB, tmpPath); FileOutputFormat.setOutputPath(jobB, new Path(args[1])); jobB.setInputFormatClass(KeyValueTextInputFormat.class); jobB.setOutputFormatClass(TextOutputFormat.class); jobB.setJarByClass(TopTitles.class); return jobB.waitForCompletion(true) ? 0 : 1; } public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> { String delimiters = " :"; @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line, this.delimiters); while (tokenizer.hasMoreTokens()) { Integer nextToken = Integer.parseInt(tokenizer.nextToken().trim()); context.write(new IntWritable(nextToken), new IntWritable(1)); } } } public static class LinkCountReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> { @Override public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int count = 0; for (IntWritable v : values) { count += v.get(); } context.write(key, new IntWritable(count)); } } public static class TopLinksMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> { Integer N; private TreeSet<Pair<Integer, String>> countToLinkMap = new TreeSet<Pair<Integer, String>>(); @Override protected void setup(Context context) throws IOException,InterruptedException { Configuration conf = context.getConfiguration(); this.N = conf.getInt("N", 10); } @Override public void map(Text key, Text value, Context context) throws IOException, InterruptedException { Integer count = Integer.parseInt(value.toString()); String link = key.toString(); countToLinkMap.add(new Pair<Integer, String>(count, link)); if (countToLinkMap.size() > this.N) { countToLinkMap.remove(countToLinkMap.first()); } } @Override protected void cleanup(Context context) throws IOException, InterruptedException { for (Pair<Integer, String> item : countToLinkMap) { String[] strings = {item.second, item.first.toString()}; TextArrayWritable val = new TextArrayWritable(strings); context.write(NullWritable.get(), val); } } } public static class TopLinksReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> { Integer N; private TreeSet<Pair<Integer, String>> countToLinkMap = new TreeSet<Pair<Integer, String>>(); @Override protected void setup(Context context) throws IOException,InterruptedException { Configuration conf = context.getConfiguration(); this.N = conf.getInt("N", 10); } @Override public void reduce(NullWritable key, Iterable<TextArrayWritable> values, Context context) throws IOException, InterruptedException { for (TextArrayWritable val: values) { Text[] pair= (Text[]) val.toArray(); String link = pair[0].toString(); Integer count = Integer.parseInt(pair[1].toString()); countToLinkMap.add(new Pair<Integer, String>(count, link)); if (countToLinkMap.size() > this.N) { countToLinkMap.remove(countToLinkMap.first()); } } for (Pair<Integer, String> item: countToLinkMap) { Text link = new Text(item.second); IntWritable value = new IntWritable(item.first); context.write(link, value); } } } } // >>> Don't Change class Pair<A extends Comparable<? super A>, B extends Comparable<? super B>> implements Comparable<Pair<A, B>> { public final A first; public final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public static <A extends Comparable<? super A>, B extends Comparable<? super B>> Pair<A, B> of(A first, B second) { return new Pair<A, B>(first, second); } @Override public int compareTo(Pair<A, B> o) { int cmp = o == null ? 1 : (this.first).compareTo(o.first); return cmp == 0 ? (this.second).compareTo(o.second) : cmp; } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair<?, ?>) obj).first) && equal(second, ((Pair<?, ?>) obj).second); } private boolean equal(Object o1, Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } } // <<< Don't Change
package org.deegree.feature.persistence.transaction; import java.util.HashSet; import java.util.Set; import org.deegree.commons.tom.Reference; import org.deegree.commons.tom.gml.GMLObject; import org.deegree.feature.Feature; import org.deegree.geometry.Geometry; import org.deegree.gml.utils.GMLObjectVisitor; class IdChecker implements GMLObjectVisitor { final Set<String> ids = new HashSet<String>(); @Override public boolean visitGeometry( final Geometry geom ) { checkForDuplication( geom.getId() ); return true; } @Override public boolean visitFeature( final Feature feature ) { checkForDuplication( feature.getId() ); return true; } @Override public boolean visitObject( final GMLObject o ) { checkForDuplication( o.getId() ); return true; } @Override public boolean visitReference( final Reference<?> ref ) { return false; } private void checkForDuplication( final String id ) { if ( id != null ) { if ( ids.contains( id ) ) { final String msg = "Duplication of object id '" + id + "'."; throw new IllegalArgumentException( msg ); } ids.add( id ); } } }
package org.eclipse.birt.report.engine.emitter.config.excel; import static org.eclipse.birt.report.engine.api.IExcelRenderOption.HIDE_GRIDLINES; import static org.eclipse.birt.report.engine.api.IExcelRenderOption.WRAPPING_TEXT; import static org.eclipse.birt.report.engine.api.IRenderOption.CHART_DPI; import java.util.Locale; import org.eclipse.birt.report.engine.api.EXCELRenderOption; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.emitter.config.AbstractConfigurableOptionObserver; import org.eclipse.birt.report.engine.emitter.config.AbstractEmitterDescriptor; import org.eclipse.birt.report.engine.emitter.config.ConfigurableOption; import org.eclipse.birt.report.engine.emitter.config.IConfigurableOption; import org.eclipse.birt.report.engine.emitter.config.IConfigurableOptionObserver; import org.eclipse.birt.report.engine.emitter.config.IOptionValue; import org.eclipse.birt.report.engine.emitter.config.excel.i18n.Messages; /** * This class is a descriptor of excel emitter. */ public class ExcelEmitterDescriptor extends AbstractEmitterDescriptor { protected IConfigurableOption[] options; protected Locale locale; public ExcelEmitterDescriptor( ) { initOptions( ); } public void setLocale( Locale locale ) { if ( this.locale != locale ) { this.locale = locale; initOptions( ); } } private void initOptions( ) { // Initializes the option for WrappingText. ConfigurableOption wrappingText = initializeWrappingText( ); // Initializes the option for chart DPI. ConfigurableOption chartDpi = new ConfigurableOption( CHART_DPI ); chartDpi.setDisplayName( getMessage( "OptionDisplayValue.ChartDpi" ) ); //$NON-NLS-1$ chartDpi.setDataType( IConfigurableOption.DataType.INTEGER ); chartDpi.setDisplayType( IConfigurableOption.DisplayType.TEXT ); chartDpi.setDefaultValue( new Integer( 192 ) ); chartDpi.setToolTip( getMessage( "Tooltip.ChartDpi" ) ); chartDpi.setDescription( getMessage( "OptionDescription.ChartDpi" ) ); //$NON-NLS-1$ ConfigurableOption hideGridlines = new ConfigurableOption( HIDE_GRIDLINES ); hideGridlines .setDisplayName( getMessage( "OptionDisplayValue.HideGridlines" ) ); //$NON-NLS-1$ hideGridlines.setDataType( IConfigurableOption.DataType.BOOLEAN ); hideGridlines.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); hideGridlines.setDefaultValue( Boolean.FALSE ); hideGridlines.setToolTip( null ); hideGridlines .setDescription( getMessage( "OptionDescription.HideGridlines" ) ); //$NON-NLS-1$ options = new IConfigurableOption[]{wrappingText, chartDpi}; } protected String getMessage( String key ) { return Messages.getString( key, locale ); } protected ConfigurableOption initializeWrappingText( ) { ConfigurableOption wrappingText = new ConfigurableOption( WRAPPING_TEXT ); wrappingText .setDisplayName( getMessage( "OptionDisplayValue.WrappingText" ) ); //$NON-NLS-1$ wrappingText.setDataType( IConfigurableOption.DataType.BOOLEAN ); wrappingText.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); wrappingText.setDefaultValue( Boolean.TRUE ); wrappingText.setToolTip( null ); wrappingText .setDescription( getMessage( "OptionDescription.WrappingText" ) ); //$NON-NLS-1$ return wrappingText; } @Override public IConfigurableOptionObserver createOptionObserver( ) { return new ExcelOptionObserver( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.emitter.config.AbstractEmitterDescriptor * #getDescription() */ public String getDescription( ) { return getMessage( "ExcelEmitter.Description" ); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.emitters.IEmitterDescriptor#getDisplayName * () */ public String getDisplayName( ) { return getMessage( "ExcelEmitter.DisplayName" ); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.emitters.IEmitterDescriptor#getID() */ public String getID( ) { return "org.eclipse.birt.report.engine.emitter.prototype.excel"; //$NON-NLS-1$ } /** * ExcelOptionObserver */ class ExcelOptionObserver extends AbstractConfigurableOptionObserver { public IConfigurableOption[] getOptions( ) { return options; } public IRenderOption getPreferredRenderOption( ) { EXCELRenderOption renderOption = new EXCELRenderOption( ); renderOption.setEmitterID( getID( ) ); renderOption.setOutputFormat( "xls" ); //$NON-NLS-1$ if ( values != null && values.length > 0 ) { for ( IOptionValue optionValue : values ) { if ( optionValue != null ) { renderOption.setOption( optionValue.getName( ), optionValue.getValue( ) ); } } } return renderOption; } } }
package org.innovateuk.ifs.project.projectdetails.controller; import org.innovateuk.ifs.application.service.CompetitionService; import org.innovateuk.ifs.application.service.OrganisationService; import org.innovateuk.ifs.commons.security.SecuredBySpring; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.project.ProjectService; import org.innovateuk.ifs.project.projectdetails.ProjectDetailsService; import org.innovateuk.ifs.project.projectdetails.viewmodel.ProjectDetailsViewModel; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.ProjectUserResource; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.util.PrioritySorting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.innovateuk.ifs.user.resource.UserRoleType.PARTNER; import static org.innovateuk.ifs.user.resource.UserRoleType.PROJECT_MANAGER; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst; /** * This controller will handle all requests that are related to project details. */ @Controller @RequestMapping("/competition/{competitionId}/project") public class ProjectDetailsController { @Autowired private CompetitionService competitionService; @Autowired private ProjectService projectService; @Autowired private ProjectDetailsService projectDetailsService; @Autowired private OrganisationService organisationService; @PreAuthorize("hasAnyAuthority('project_finance', 'comp_admin', 'support', 'innovation_lead')") @SecuredBySpring(value = "VIEW_PROJECT_DETAILS", description = "Project finance, comp admin, support and innovation lead can view the project details") @GetMapping("/{projectId}/details") public String viewProjectDetails(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, Model model, UserResource loggedInUser) { ProjectResource projectResource = projectService.getById(projectId); List<ProjectUserResource> projectUsers = projectService.getProjectUsersForProject(projectResource.getId()); OrganisationResource leadOrganisationResource = projectService.getLeadOrganisation(projectId); List<OrganisationResource> partnerOrganisations = sortedOrganisations(getPartnerOrganisations(projectUsers), leadOrganisationResource); model.addAttribute("model", new ProjectDetailsViewModel(projectResource, competitionId, null, leadOrganisationResource.getName(), getProjectManager(projectUsers).orElse(null), getFinanceContactForPartnerOrganisation(projectUsers, partnerOrganisations))); return "project/detail"; } @PreAuthorize("hasAnyAuthority('project_finance')") @SecuredBySpring(value = "VIEW_EDIT_PROJECT_DURATION", description = "Only the project finance can view the page to edit the project duration") @GetMapping("/{projectId}/edit-duration") public String editProjectDuration(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, Model model, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); CompetitionResource competition = competitionService.getById(competitionId); model.addAttribute("model", new ProjectDetailsViewModel(project, competitionId, competition.getName(), null, null, null)); return "project/edit-duration"; } @PreAuthorize("hasAnyAuthority('project_finance')") @SecuredBySpring(value = "UPDATE_PROJECT_DURATION", description = "Only the project finance can update the project duration") @PostMapping("/{projectId}/update-duration") public String updateProjectDuration(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, @RequestParam(value = "durationInMonths") final Long durationInMonths, Model model, UserResource loggedInUser) { Supplier<String> failureView = () -> "redirect:/competition/" + competitionId + "/project/" + projectId + "/edit-duration"; Supplier<String> successView = () -> "redirect:/project/" + projectId + "/finance-check"; return projectDetailsService.updateProjectDuration(projectId, durationInMonths) .handleSuccessOrFailure(failure -> failureView.get(), success -> successView.get()); } private List<OrganisationResource> getPartnerOrganisations(final List<ProjectUserResource> projectRoles) { return projectRoles.stream() .filter(uar -> uar.getRoleName().equals(PARTNER.getName())) .map(uar -> organisationService.getOrganisationById(uar.getOrganisation())) .collect(Collectors.toList()); } private List<OrganisationResource> sortedOrganisations(List<OrganisationResource> organisations, OrganisationResource lead) { return new PrioritySorting<>(organisations, lead, OrganisationResource::getName).unwrap(); } private Optional<ProjectUserResource> getProjectManager(List<ProjectUserResource> projectUsers) { return simpleFindFirst(projectUsers, pu -> PROJECT_MANAGER.getName().equals(pu.getRoleName())); } private Map<OrganisationResource, ProjectUserResource> getFinanceContactForPartnerOrganisation(List<ProjectUserResource> projectUsers, List<OrganisationResource> partnerOrganisations) { List<ProjectUserResource> financeRoles = simpleFilter(projectUsers, ProjectUserResource::isFinanceContact); Map<OrganisationResource, ProjectUserResource> organisationFinanceContactMap = new LinkedHashMap<>(); partnerOrganisations.stream().forEach(organisation -> organisationFinanceContactMap.put(organisation, simpleFindFirst(financeRoles, financeUserResource -> financeUserResource.getOrganisation().equals(organisation.getId())).orElse(null)) ); return organisationFinanceContactMap; } }
package org.apdplat.superword.tools; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.apache.commons.lang.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * * IP * * * @author */ public class ProxyIp { private ProxyIp(){} private static final Logger LOGGER = LoggerFactory.getLogger(ProxyIp.class); private static final String ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; private static final String ENCODING = "gzip, deflate"; private static final String LANGUAGE = "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"; private static final String CONNECTION = "keep-alive"; private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0"; private static volatile boolean isSwitching = false; private static volatile long lastSwitchTime = 0l; private static final WebClient WEB_CLIENT = new WebClient(BrowserVersion.INTERNET_EXPLORER_11); private static final Pattern IP_PATTERN = Pattern.compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))"); private static final List<String> IPS = new Vector<>(); private static volatile int currentIpIndex = 0; private static volatile boolean detect = true; private static volatile int detectInterval = 300000; private static final Path PROXY_IPS_FILE = Paths.get("src/main/resources/proxy_ips.txt"); private static String previousIp = getCurrentIp(); private static final Set<String> EXCELLENT_IPS = new ConcurrentSkipListSet<>(); private static final Set<String> EXCELLENT_USA_IPS = new ConcurrentSkipListSet<>(); private static final Set<String> NORMAL_IPS = new ConcurrentSkipListSet<>(); private static final Path EXCELLENT_PROXY_IPS_FILE = Paths.get("src/main/resources/proxy_ips_excellent.txt");; private static final Path EXCELLENT_USA_PROXY_IPS_FILE = Paths.get("src/main/resources/proxy_ips_excellent_usa.txt"); private static final Path NORMAL_PROXY_IPS_FILE = Paths.get("src/main/resources/proxy_ips_normal.txt"); static { Set<String> ipSet = new HashSet<>(); try { if(Files.notExists(PROXY_IPS_FILE.getParent())){ PROXY_IPS_FILE.getParent().toFile().mkdirs(); } if(Files.notExists(PROXY_IPS_FILE)){ PROXY_IPS_FILE.toFile().createNewFile(); } if(Files.notExists(EXCELLENT_PROXY_IPS_FILE)){ EXCELLENT_PROXY_IPS_FILE.toFile().createNewFile(); } if(Files.notExists(EXCELLENT_USA_PROXY_IPS_FILE)){ EXCELLENT_USA_PROXY_IPS_FILE.toFile().createNewFile(); } if(Files.notExists(NORMAL_PROXY_IPS_FILE)){ NORMAL_PROXY_IPS_FILE.toFile().createNewFile(); } LOGGER.info("IP"+PROXY_IPS_FILE.toAbsolutePath().toString()); ipSet.addAll(Files.readAllLines(PROXY_IPS_FILE)); ipSet.addAll(Files.readAllLines(EXCELLENT_PROXY_IPS_FILE)); }catch (Exception e){ LOGGER.error("IP", e); } if(ipSet.isEmpty()){ ipSet.addAll(getProxyIps()); } IPS.addAll(ipSet); LOGGER.info("IP("+IPS.size()+")"); AtomicInteger i = new AtomicInteger(); IPS.forEach(ip->LOGGER.info(i.incrementAndGet()+""+ip)); new Thread(()->{ int count=0; while(detect) { try { save(); if(count%10==9){ toNewIp(); } Thread.sleep(detectInterval); getProxyIps().forEach(ip -> { if (!IPS.contains(ip)) { IPS.add(ip); LOGGER.info("IP" + ip); } }); count++; } catch (Exception e) { LOGGER.error("IP", e); } } }).start(); } public static void stopDetect(){ detect = false; } public static void startDetect(){ detect = true; } private static void save(){ try { Set<String> ips = new ConcurrentSkipListSet<>(); ips.addAll(Files.readAllLines(PROXY_IPS_FILE)); ips.addAll(IPS); ips.removeAll(NORMAL_IPS); Files.write(PROXY_IPS_FILE, toVerify(ips)); LOGGER.info("" + ips.size() + "IP"); Set<String> excellentIps = new HashSet<>(); excellentIps.addAll(Files.readAllLines(EXCELLENT_PROXY_IPS_FILE)); excellentIps.addAll(EXCELLENT_IPS); Files.write(EXCELLENT_PROXY_IPS_FILE, toVerify(excellentIps)); LOGGER.info("" + excellentIps.size() + "IP"); Set<String> excellentUsaIps = new HashSet<>(); excellentUsaIps.addAll(Files.readAllLines(EXCELLENT_USA_PROXY_IPS_FILE)); excellentUsaIps.addAll(EXCELLENT_USA_IPS); Files.write(EXCELLENT_USA_PROXY_IPS_FILE, toVerify(excellentUsaIps)); LOGGER.info("" + excellentUsaIps.size() + "IP"); Set<String> normalIps = new HashSet<>(); normalIps.addAll(Files.readAllLines(NORMAL_PROXY_IPS_FILE)); normalIps.addAll(NORMAL_IPS); Files.write(NORMAL_PROXY_IPS_FILE, toVerify(normalIps)); LOGGER.info("" + normalIps.size() + "IP"); }catch (Exception e){ LOGGER.error("", e); } } private static List<String> toVerify(Set<String> ips){ AtomicInteger i = new AtomicInteger(); AtomicInteger f = new AtomicInteger(); List<String> list = ips.parallelStream().filter(ip->{ LOGGER.info(""+ips.size()+"/"+i.incrementAndGet()); String[] attr = ip.split(":"); if(verify(attr[0], Integer.parseInt(attr[1]))){ return true; } IPS.remove(ip); f.incrementAndGet(); return false; }).sorted().collect(Collectors.toList()); LOGGER.info("IP"+(ips.size()-f.get())); LOGGER.info("IP"+f.get()); return list; } private static String getNextProxyIp(){ int index = currentIpIndex%IPS.size(); currentIpIndex++; return IPS.get(index); } public static boolean toNewIp() { long requestSwitchTime = System.currentTimeMillis(); LOGGER.info(Thread.currentThread()+""); synchronized (ProxyIp.class) { if (isSwitching) { LOGGER.info(Thread.currentThread()+""); try { ProxyIp.class.wait(); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } LOGGER.info(Thread.currentThread()+""); return true; } isSwitching = true; } if(requestSwitchTime <= lastSwitchTime){ LOGGER.info(""); isSwitching = false; return true; } LOGGER.info(Thread.currentThread()+""); long start = System.currentTimeMillis(); String proxyIp = useNewProxyIp(); String currentIp = null; int times=0; //IPIPIP while((currentIp=getCurrentIp()).equals(previousIp) && (times++)<Integer.MAX_VALUE){ NORMAL_IPS.add(proxyIp); IPS.remove(proxyIp); proxyIp = useNewProxyIp(); } if(!currentIp.equals(previousIp)) { previousIp =currentIp; EXCELLENT_IPS.add(proxyIp); LOGGER.info(Thread.currentThread()+""); LOGGER.info(Thread.currentThread()+""+(System.currentTimeMillis()-start)+""); synchronized (ProxyIp.class) { ProxyIp.class.notifyAll(); } isSwitching = false; lastSwitchTime = System.currentTimeMillis(); return true; } NORMAL_IPS.add(proxyIp); IPS.remove(proxyIp); LOGGER.info(Thread.currentThread()+""); LOGGER.info(Thread.currentThread()+""+(System.currentTimeMillis()-start)+""); synchronized (ProxyIp.class) { ProxyIp.class.notifyAll(); } isSwitching = false; return false; } private static String useNewProxyIp(){ String newProxy = getNextProxyIp(); String[] attr = newProxy.split(":"); System.setProperty("proxySet", "true"); System.setProperty("http.proxyHost", attr[0]); System.setProperty("http.proxyPort", attr[1]); LOGGER.info(""+newProxy); return newProxy; } /** * IPIP * @param host * @param port * @return */ public static boolean verify(String host, int port){ try { String url = "http://apdplat.org"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(proxy); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setUseCaches(false); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder html = new StringBuilder(); String line = null; while ((line=reader.readLine()) != null){ html.append(line); } LOGGER.info("HTML"+html); if(html.toString().contains("APDPlat")){ LOGGER.info("IP"+host+":"+port); return true; } }catch (Exception e){ LOGGER.error(e.getMessage()); } LOGGER.info("IP"+host+":"+port); return false; } /** * ip138IP * @return */ public static String getCurrentIp(){ try { String url = "http://1111.ip138.com/ic.asp?timestamp="+System.nanoTime(); String text = Jsoup.connect(url) .header("Accept", ACCEPT) .header("Accept-Encoding", ENCODING) .header("Accept-Language", LANGUAGE) .header("Connection", CONNECTION) .header("Host", "1111.ip138.com") .header("Referer", "http://ip138.com/") .header("User-Agent", USER_AGENT) .ignoreContentType(true) .timeout(5000) .get() .text(); LOGGER.info("IP"+text); Matcher matcher = IP_PATTERN.matcher(text); if(matcher.find()){ String ip = matcher.group(); LOGGER.info("IP"+ip); if(text.contains("")){ EXCELLENT_USA_IPS.add(System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } return ip; } }catch (Exception e){ LOGGER.error(e.getMessage()); } LOGGER.info("IPIP"+ previousIp); return previousIp; } private static Set<String> getProxyIps(){ Set<String> ips = new HashSet<>(); ips.addAll(getProxyIpOne()); ips.addAll(getProxyIpTwo()); ips.addAll(getProxyIpThree()); ips.addAll(getProxyIpFour()); return ips; } private static List<String> getProxyIpOne(){ String url = "http://proxy.goubanjia.com/?timestamp="+System.nanoTime(); String cssPath = "html body div.wrap.fullwidth div#content div#post-2.post-2.page.type-page.status-publish.hentry div.entry.entry-content div#list table.table tbody tr"; return getProxyIp(url, cssPath); } private static List<String> getProxyIpTwo(){ String url = "http://ip.qiaodm.com/?timestamp="+System.nanoTime(); String cssPath = "html body div#main_container div.inner table.iplist tbody tr"; return getProxyIp(url, cssPath); } private static List<String> getProxyIp(String url, String cssPath){ List<String> ips = new ArrayList<>(); try { String html = ((HtmlPage)WEB_CLIENT.getPage(url)).getBody().asXml(); //LOGGER.info("html"+html); Document doc = Jsoup.parse(html); Elements elements = doc.select(cssPath); elements .forEach(element -> { try { Elements tds = element.children(); String ip = null; int port = 0; if (tds.size() > 1) { Element ele = tds.get(0); ip = getIps(ele); String text = tds.get(1).text(); LOGGER.info(""+text+" -> "+tds.get(1).outerHtml()); port = Integer.parseInt(text); } if(ip != null && port > 0){ LOGGER.info("IP"+ip+""+port); if(verify(ip, port)){ LOGGER.info("IP"+ip+""+port+""); ips.add(ip + ":" + port); }else { LOGGER.info("IP"+ip+""+port+""); } } }catch (Exception e){ LOGGER.error("IP", e); } }); }catch (Exception e){ LOGGER.error("IP", e); } return ips; } private static List<String> getProxyIpThree(){ List<String> ips = new ArrayList<>(); for(int i=1; i<=10; i++){ ips.addAll(getProxyIpThree(i)); } return ips; } private static List<String> getProxyIpThree(int page){ List<String> ips = new ArrayList<>(); try { String url = "http: String html = ((HtmlPage)WEB_CLIENT.getPage(url)).getBody().asXml(); //LOGGER.info("html"+html); Document doc = Jsoup.parse(html); Elements elements = doc.select("html body div#container div#list table.table.table-bordered.table-striped tbody tr"); elements .forEach(element -> { try { Elements tds = element.children(); String ip = null; int port = 0; if (tds.size() > 1) { ip = tds.get(0).text(); String text = tds.get(1).text(); LOGGER.info("IP"+ip); LOGGER.info(""+text); Matcher matcher = IP_PATTERN.matcher(ip.toString()); if(matcher.find()){ ip = matcher.group(); LOGGER.info("ip"+ip); }else{ LOGGER.info("ip"+ip); ip = null; } try{ port = Integer.parseInt(text); LOGGER.info(""+port); }catch (Exception e){ LOGGER.info(""+port); } } if(ip != null && port > 0){ LOGGER.info("IP"+ip+""+port); if(verify(ip, port)){ LOGGER.info("IP"+ip+""+port+""); ips.add(ip + ":" + port); }else { LOGGER.info("IP"+ip+""+port+""); } } }catch (Exception e){ LOGGER.error("IP", e); } }); }catch (Exception e){ LOGGER.error("IP", e); } return ips; } private static List<String> getProxyIpFour(){ List<String> ips = new ArrayList<>(); for(int i=1; i<=10; i++){ ips.addAll(getProxyIpFour(i)); } return ips; } private static List<String> getProxyIpFour(int page){ List<String> ips = new ArrayList<>(); try { String url = "http: String html = ((HtmlPage)WEB_CLIENT.getPage(url)).getBody().asXml(); //LOGGER.info("html"+html); Document doc = Jsoup.parse(html); Elements elements = doc.select("html body#nav_btn01 div.tab_c_box.buy_tab_box table.ui.table.segment tbody tr"); elements .forEach(element -> { try { Elements tds = element.children(); String ip = null; int port = 0; if (tds.size() > 1) { ip = tds.get(0).text(); String text = tds.get(1).text(); LOGGER.info("IP"+ip); LOGGER.info(""+text); Matcher matcher = IP_PATTERN.matcher(ip.toString()); if(matcher.find()){ ip = matcher.group(); LOGGER.info("ip"+ip); }else{ LOGGER.info("ip"+ip); ip = null; } try{ port = Integer.parseInt(text); LOGGER.info(""+port); }catch (Exception e){ LOGGER.info(""+port); } } if(ip != null && port > 0){ LOGGER.info("IP"+ip+""+port); if(verify(ip, port)){ LOGGER.info("IP"+ip+""+port+""); ips.add(ip + ":" + port); }else { LOGGER.info("IP"+ip+""+port+""); } } }catch (Exception e){ LOGGER.error("IP", e); } }); }catch (Exception e){ LOGGER.error("IP", e); } return ips; } private static String getIps(Element element){ StringBuilder ip = new StringBuilder(); Elements all = element.children(); LOGGER.info(""); LOGGER.info("IP"+element.text()); AtomicInteger count = new AtomicInteger(); all.forEach(ele -> { String html = ele.outerHtml(); LOGGER.info(count.incrementAndGet() + "" + "HTML"+html.replaceAll("[\n\r]", "")); String text = ele.text(); if(ele.hasAttr("style") && (ele.attr("style").equals("display: none;") || ele.attr("style").equals("display:none;"))) { LOGGER.info(""+text); }else{ if(StringUtils.isNotBlank(text)){ LOGGER.info(""+text); ip.append(text); }else{ LOGGER.info(""); } } }); LOGGER.info(" LOGGER.info("ip: "+ip); LOGGER.info(" Matcher matcher = IP_PATTERN.matcher(ip.toString()); if(matcher.find()){ String _ip = matcher.group(); LOGGER.info("ip"+_ip); return _ip; }else{ LOGGER.info("ip"+ip); } return null; } public static void main(String[] args) { //IP1 detectInterval=1000; while(true){ toNewIp(); } } }
package org.eclipse.che.ide.extension.builder.client.console.indicators; import org.eclipse.che.ide.api.action.Presentation; import org.eclipse.che.ide.api.action.PropertyChangeEvent; import org.eclipse.che.ide.api.action.PropertyChangeListener; import org.eclipse.che.ide.extension.builder.client.BuilderResources; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Frame; import com.google.gwt.user.client.ui.InlineLabel; /** * View for {@link IndicatorAction}. * It contains caption and data separated by colon symbol. * Data may be text or URL. * * @author Artem Zatsarynnyy */ public class IndicatorView extends Composite { private final boolean isURL; private final Presentation presentation; private Anchor dataAnchor; private InlineLabel dataLabel; private PropertyListener propertyListener; private final static String TARGET = "download-frame"; public IndicatorView(String caption, boolean isURL, int width, Presentation presentation, BuilderResources resources) { this.isURL = isURL; this.presentation = presentation; FlowPanel panel = new FlowPanel(); InlineLabel captionLabel = new InlineLabel(caption + ':'); panel.add(captionLabel); if (isURL) { dataAnchor = new Anchor(); dataAnchor.setStyleName(resources.builder().dataLabel()); panel.add(dataAnchor); //Add iframe for avoid opening a new window when downloading the built artifacts Frame frame = new Frame(); frame.getElement().setAttribute("name", TARGET); frame.setSize("0px", "0px"); frame.setVisible(false); panel.add(frame); } else { dataLabel = new InlineLabel(); dataLabel.setStyleName(resources.builder().dataLabel()); panel.add(dataLabel); } panel.ensureDebugId(caption); panel.setStyleName(resources.builder().infoPanel()); panel.setWidth(width + "px"); initWidget(panel); } @Override protected void onLoad() { super.onLoad(); if (propertyListener == null) { propertyListener = new PropertyListener(); presentation.addPropertyChangeListener(propertyListener); } } @Override protected void onUnload() { super.onUnload(); if (propertyListener != null) { presentation.removePropertyChangeListener(propertyListener); propertyListener = null; } } private void setData(String value) { if (value == null) { value = ""; } if (isURL) { if (value.length() > 20) { dataAnchor.setText(value.substring(0, 10) + "..." + value.substring(value.length() - 10)); } else { dataAnchor.setText(value); } dataAnchor.setHref(value); dataAnchor.setTarget(TARGET); } else { dataLabel.setText(value); } } private void setHint(String value) { if (value == null) { value = ""; } if (isURL) { dataAnchor.setTitle(value); } else { dataLabel.setTitle(value); } } private class PropertyListener implements PropertyChangeListener { @Override public void onPropertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case Properties.DATA_PROPERTY: setData((String)e.getNewValue()); break; case Properties.HINT_PROPERTY: setHint((String)e.getNewValue()); break; } } } }
package org.rlcommunity.critter; /** * SimulatorComponentLight * * This component deals with light-emitting objects and light sensors, * pairing the two into a happy match. * * @author Marc G. Bellemare */ public class SimulatorComponentLight implements SimulatorComponent { public static final String NAME = "light"; public SimulatorComponentLight() { } /** Computes what light sensors should receive given the current state, * and set the result in the next state. * * @param pCurrent The current state of the system (must not be modified) * @param pNext The next state of the system (where results are stored) * @param delta The number of milliseconds elapsed between pCurrent * and pNext. */ public void apply(SimulatorState pCurrent, SimulatorState pNext, int delta) { Scene scene = new Scene(pCurrent); Vector2D rayDirection; RayIntersection intersectData; Ray r; SimulatorObject sensor; ObjectStateLightSensor lightSensor; ObjectStateLightSensor oldLightSensor; SimulatorObject oldSensor; Vector2D sensorPosition; SimulatorObject source; ObjectStateLightSource lightSource; Vector2D srcPosition; for (int Ksensor = 0; Ksensor < pNext.getObjects(ObjectStateLightSensor.NAME).size(); Ksensor++) { sensor = pNext.getObjects(ObjectStateLightSensor.NAME).get(Ksensor); lightSensor = (ObjectStateLightSensor) sensor.getState(ObjectStateLightSensor.NAME); sensorPosition = sensor.getPosition(); oldSensor = pCurrent.getObject(sensor); oldLightSensor = (ObjectStateLightSensor) oldSensor.getState(ObjectStateLightSensor.NAME); double sensorWidth = oldLightSensor.getSensorWidth(); int numPixels = oldLightSensor.getNumPixels(); double sensorDepth = oldLightSensor.getSensorDepth(); double angleBetweenRays = (Math.atan((sensorWidth / numPixels) / sensorDepth)); double currentRayAngle = 0; //even or odd number of pixels..compute orientation of first ray in sensor (counter clockwise rotation from orientation of sensor). if (numPixels % 2 == 0) { currentRayAngle = sensor.getDirection() - angleBetweenRays / 2.0 + (Math.floor(numPixels / 2)) * angleBetweenRays; } else { currentRayAngle = oldSensor.getDirection() + (Math.floor(numPixels / 2)) * angleBetweenRays; //correct if first ray rotates through PI -PI boarder } if (currentRayAngle > Math.PI) { currentRayAngle = -Math.PI + currentRayAngle - Math.PI; } double sumIntensity = 0; //store total intensity of each pixel in the sensor //for each pixel in the sensor for (int Ipixel = 0; Ipixel < numPixels; Ipixel++) { //as we rotate clockwise through pixels may cross PI -PI boarder if (currentRayAngle < -Math.PI) { currentRayAngle = Math.PI + currentRayAngle + Math.PI; //create ray } rayDirection = Vector2D.unitVector(currentRayAngle); rayDirection.normalize(); r = new Ray(sensorPosition, rayDirection); //remove robot so it doesn't block ray scene.removeSubtree(oldSensor.getRoot()); //find out first point (object) ray i intersects with intersectData = scene.traceRay(r); if (intersectData != null) {//if the ray hits nothing then intensity is zero. We probably have no walls //angle between robot's sensor ray and surface normal double angle1 = sensorPosition.minus(intersectData.point).direction(); double angle2 = intersectData.normal.direction(); double angleOfIncidence = Math.abs(angle1) - Math.abs(angle2); //put robot back in...robot may block light on intersection point scene.addSubtree(oldSensor.getRoot()); //for each light source sum up intensity at intersection point for (int Jsource = 0; Jsource < pCurrent.getObjects(ObjectStateLightSource.NAME).size(); Jsource++) { double intensity = 0; source = pCurrent.getObjects(ObjectStateLightSource.NAME).get(Jsource); lightSource = (ObjectStateLightSource) source.getState(ObjectStateLightSource.NAME); srcPosition = source.getPosition(); //unlikely case where ray intersects the light source directly double slope = (sensorPosition.x - srcPosition.x) / (sensorPosition.y - srcPosition.y); double tol = Math.pow(10, -15); if (Math.abs(slope - (rayDirection.x / rayDirection.y)) < tol) { intensity = lightSource.getIntensity() * (1.0 / Math.pow(srcPosition.distance(sensorPosition), 2)); sumIntensity += intensity; } else { //light source should have no polygon...incase marc changes his name scene.removeSubtree(source.getRoot()); //find angle between light source and surface normal angle1 = srcPosition.minus(intersectData.point).direction(); double angleOfIncidence2 = Math.abs(angle1) - Math.abs(angle2); //is point illuminated? if (scene.isVisible(srcPosition, intersectData.point)) { double totalDistance = srcPosition.distance(intersectData.point) + intersectData.point.distance(sensorPosition); double bouncePenalty = 1.0; //intensity at sensor is function of distance and angles of incidence intensity = bouncePenalty * lightSource.getIntensity() * (1.0 / Math.pow(totalDistance, 2)) + Math.abs(Math.cos(angleOfIncidence) * Math.cos(angleOfIncidence2)); //sum up light from multiple sources and from each pixel sumIntensity += intensity; } } }//loop over sources }//test for object intersection currentRayAngle -= angleBetweenRays; //next ray rotating clockwise } //loop over pixels //sensor reading is average of pixel readings lightSensor.setLightSensorValue(sumIntensity / numPixels); System.out.println("sensor(" + Ksensor + ") intensity = " + lightSensor.getLightSensorValue()); } //loop over sensors System.out.println(" } }
package org.voltdb.iv2; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.LinkedBlockingDeque; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.Mailbox; import org.voltcore.messaging.TransactionInfoBaseMessage; import org.voltcore.utils.CoreUtils; import org.voltdb.messaging.DumpMessage; import org.voltdb.SiteProcedureConnection; import org.voltdb.StoredProcedureInvocation; import org.voltdb.VoltTable; import org.voltdb.client.ProcedureInvocationType; import org.voltdb.dtxn.TransactionState; import org.voltdb.messaging.BorrowTaskMessage; import org.voltdb.messaging.FragmentResponseMessage; import org.voltdb.messaging.FragmentTaskMessage; import org.voltdb.messaging.Iv2InitiateTaskMessage; import org.voltdb.utils.VoltTableUtil; public class MpTransactionState extends TransactionState { static VoltLogger tmLog = new VoltLogger("TM"); /** * This is thrown by the TransactionState instance when something * goes wrong mid-fragment, and execution needs to back all the way * out to the stored procedure call. */ public static class FragmentFailureException extends RuntimeException { private static final long serialVersionUID = 1L; } final Iv2InitiateTaskMessage m_initiationMsg; LinkedBlockingDeque<FragmentResponseMessage> m_newDeps = new LinkedBlockingDeque<FragmentResponseMessage>(); Map<Integer, Set<Long>> m_remoteDeps; Map<Integer, List<VoltTable>> m_remoteDepTables = new HashMap<Integer, List<VoltTable>>(); final List<Long> m_useHSIds = new ArrayList<Long>(); long m_buddyHSId; FragmentTaskMessage m_remoteWork = null; FragmentTaskMessage m_localWork = null; boolean m_haveDistributedInitTask = false; boolean m_isRestart = false; MpTransactionState(Mailbox mailbox, TransactionInfoBaseMessage notice, List<Long> useHSIds, long buddyHSId, boolean isRestart) { super(mailbox, notice); m_initiationMsg = (Iv2InitiateTaskMessage)notice; m_useHSIds.addAll(useHSIds); m_buddyHSId = buddyHSId; m_isRestart = isRestart; } public void updateMasters(List<Long> masters) { m_useHSIds.clear(); m_useHSIds.addAll(masters); } /** * Used to reset the internal state of this transaction so it can be successfully restarted */ void restart() { // The poisoning path will, unfortunately, set this to true. Need to undo that. m_needsRollback = false; // Also need to make sure that we get the original invocation in the first fragment // since some masters may not have seen it. m_haveDistributedInitTask = false; m_isRestart = true; } @Override public boolean isSinglePartition() { return false; } @Override public StoredProcedureInvocation getInvocation() { return m_initiationMsg.getStoredProcedureInvocation(); } // Overrides needed by MpProcedureRunner @Override public void setupProcedureResume(boolean isFinal, int[] dependencies) { // Reset state so we can run this batch cleanly m_localWork = null; m_remoteWork = null; m_remoteDeps = null; m_remoteDepTables.clear(); } // I met this List at bandcamp... public void setupProcedureResume(boolean isFinal, List<Integer> deps) { setupProcedureResume(isFinal, com.google.common.primitives.Ints.toArray(deps)); } @Override public void createLocalFragmentWork(FragmentTaskMessage task, boolean nonTransactional) { m_localWork = task; m_localWork.setTruncationHandle(m_initiationMsg.getTruncationHandle()); } @Override public void createAllParticipatingFragmentWork(FragmentTaskMessage task) { // Don't generate remote work or dependency tracking or anything if // there are no fragments to be done in this message // At some point maybe ProcedureRunner.slowPath() can get smarter if (task.getFragmentCount() > 0) { // Distribute the initiate task for command log replay. // Command log must log the initiate task; // Only send the fragment once. if (!m_haveDistributedInitTask && !isForReplay() && !isReadOnly()) { m_haveDistributedInitTask = true; task.setInitiateTask((Iv2InitiateTaskMessage)getNotice()); } if (m_initiationMsg.getStoredProcedureInvocation().getType() == ProcedureInvocationType.REPLICATED) { task.setOriginalTxnId(m_initiationMsg.getStoredProcedureInvocation().getOriginalTxnId()); } m_remoteWork = task; m_remoteWork.setTruncationHandle(m_initiationMsg.getTruncationHandle()); // Distribute fragments to remote destinations. long[] non_local_hsids = new long[m_useHSIds.size()]; for (int i = 0; i < m_useHSIds.size(); i++) { non_local_hsids[i] = m_useHSIds.get(i); } // send to all non-local sites if (non_local_hsids.length > 0) { m_mbox.send(non_local_hsids, m_remoteWork); } } else { m_remoteWork = null; } } private Map<Integer, Set<Long>> createTrackedDependenciesFromTask(FragmentTaskMessage task, List<Long> expectedHSIds) { Map<Integer, Set<Long>> depMap = new HashMap<Integer, Set<Long>>(); for (int i = 0; i < task.getFragmentCount(); i++) { int dep = task.getOutputDepId(i); Set<Long> scoreboard = new HashSet<Long>(); depMap.put(dep, scoreboard); for (long hsid : expectedHSIds) { scoreboard.add(hsid); } } return depMap; } @Override public Map<Integer, List<VoltTable>> recursableRun(SiteProcedureConnection siteConnection) { // if we're restarting this transaction, and we only have local work, add some dummy // remote work so that we can avoid injecting a borrow task into the local buddy site // before the CompleteTransactionMessage with the restart flag reaches it. // Right now, any read on a replicated table which has no distributed work will // generate these null fragments in the restarted transaction. boolean usedNullFragment = false; if (m_isRestart && m_remoteWork == null) { usedNullFragment = true; m_remoteWork = new FragmentTaskMessage(m_localWork.getInitiatorHSId(), m_localWork.getCoordinatorHSId(), m_localWork.getTxnId(), m_localWork.getUniqueId(), m_localWork.isReadOnly(), false, false); m_remoteWork.setEmptyForRestart(getNextDependencyId()); if (!m_haveDistributedInitTask && !isForReplay() && !isReadOnly()) { m_haveDistributedInitTask = true; m_remoteWork.setInitiateTask((Iv2InitiateTaskMessage)getNotice()); } // Distribute fragments to remote destinations. long[] non_local_hsids = new long[m_useHSIds.size()]; for (int i = 0; i < m_useHSIds.size(); i++) { non_local_hsids[i] = m_useHSIds.get(i); } // send to all non-local sites if (non_local_hsids.length > 0) { m_mbox.send(non_local_hsids, m_remoteWork); } } // Do distributed fragments, if any if (m_remoteWork != null) { // Create some record of expected dependencies for tracking m_remoteDeps = createTrackedDependenciesFromTask(m_remoteWork, m_useHSIds); // if there are remote deps, block on them // FragmentResponses indicating failure will throw an exception // which will propagate out of handleReceivedFragResponse and // cause ProcedureRunner to do the right thing and cause rollback. while (!checkDoneReceivingFragResponses()) { FragmentResponseMessage msg = pollForResponses(); handleReceivedFragResponse(msg); } } // satisified. Clear this defensively. Procedure runner is sloppy with // cleaning up if it decides new work is necessary that is local-only. m_remoteWork = null; BorrowTaskMessage borrowmsg = new BorrowTaskMessage(m_localWork); m_localWork.m_sourceHSId = m_mbox.getHSId(); // if we created a bogus fragment to distribute to serialize restart and borrow tasks, // don't include the empty dependencies we got back in the borrow fragment. if (!usedNullFragment) { borrowmsg.addInputDepMap(m_remoteDepTables); } m_mbox.send(m_buddyHSId, borrowmsg); FragmentResponseMessage msg = pollForResponses(); m_localWork = null; // Build results from the FragmentResponseMessage // This is similar to dependency tracking...maybe some // sane way to merge it Map<Integer, List<VoltTable>> results = new HashMap<Integer, List<VoltTable>>(); for (int i = 0; i < msg.getTableCount(); i++) { int this_depId = msg.getTableDependencyIdAtIndex(i); VoltTable this_dep = msg.getTableAtIndex(i); List<VoltTable> tables = results.get(this_depId); if (tables == null) { tables = new ArrayList<VoltTable>(); results.put(this_depId, tables); } tables.add(this_dep); } // Need some sanity check that we got all of the expected output dependencies? return results; } private FragmentResponseMessage pollForResponses() { FragmentResponseMessage msg = null; try { final String snapShotRestoreProcName = "@SnapshotRestore"; while (msg == null) { msg = m_newDeps.poll(60L * 5, TimeUnit.SECONDS); if (msg == null) { if (!snapShotRestoreProcName.equals(m_initiationMsg.getStoredProcedureName()) ) { tmLog.warn("Possible multipartition transaction deadlock detected for: " + m_initiationMsg); if (m_remoteWork == null) { tmLog.warn("Waiting on local BorrowTask response from site: " + CoreUtils.hsIdToString(m_buddyHSId)); } else { tmLog.warn("Waiting on remote dependencies: "); for (Entry<Integer, Set<Long>> e : m_remoteDeps.entrySet()) { tmLog.warn("Dep ID: " + e.getKey() + " waiting on: " + CoreUtils.hsIdCollectionToString(e.getValue())); } } m_mbox.send(com.google.common.primitives.Longs.toArray(m_useHSIds), new DumpMessage()); } } } } catch (InterruptedException e) { // can't leave yet - the transaction is inconsistent. // could retry; but this is unexpected. Crash. throw new RuntimeException(e); } if (msg.getStatusCode() != FragmentResponseMessage.SUCCESS) { m_needsRollback = true; if (msg.getException() != null) { throw msg.getException(); } else { throw new FragmentFailureException(); } } return msg; } private void trackDependency(long hsid, int depId, VoltTable table) { // Remove the distributed fragment for this site from remoteDeps // for the dependency Id depId. Set<Long> localRemotes = m_remoteDeps.get(depId); if (localRemotes == null && m_isRestart) { // Tolerate weird deps showing up on restart // After Ariel separates unique ID from transaction ID, rewrite restart to restart with // a new transaction ID and make this and the fake distributed fragment stuff go away. return; } Object needed = localRemotes.remove(hsid); if (needed != null) { // add table to storage List<VoltTable> tables = m_remoteDepTables.get(depId); if (tables == null) { tables = new ArrayList<VoltTable>(); m_remoteDepTables.put(depId, tables); } // null dependency table is from a joining node, has no content, drop it if (table.getStatusCode() != VoltTableUtil.NULL_DEPENDENCY_STATUS) { tables.add(table); } } else { System.out.println("No remote dep for local site: " + hsid); } } private void handleReceivedFragResponse(FragmentResponseMessage msg) { for (int i = 0; i < msg.getTableCount(); i++) { int this_depId = msg.getTableDependencyIdAtIndex(i); VoltTable this_dep = msg.getTableAtIndex(i); long src_hsid = msg.getExecutorSiteId(); trackDependency(src_hsid, this_depId, this_dep); } } private boolean checkDoneReceivingFragResponses() { boolean done = true; for (Set<Long> depid : m_remoteDeps.values()) { if (depid.size() != 0) { done = false; } } return done; } // Runs from Mailbox's network thread public void offerReceivedFragmentResponse(FragmentResponseMessage message) { // push into threadsafe queue m_newDeps.offer(message); } /** * Kill a transaction - maybe shutdown mid-transaction? Or a timeout * collecting fragments? This is a don't-know-what-to-do-yet * stub. * TODO: fix this. */ void terminateTransaction() { throw new RuntimeException("terminateTransaction is not yet implemented."); } }
package org.dita.dost.reader; import static org.dita.dost.util.Constants.*; import static org.dita.dost.writer.DitaWriter.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.Content; import org.dita.dost.module.ContentImpl; import org.dita.dost.util.FileUtils; import org.dita.dost.util.StringUtils; import org.dita.dost.writer.ChunkTopicParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; /** * ChunkMapReader class, read ditamap file for chunking. * */ public final class ChunkMapReader implements AbstractReader { public static final String FILE_NAME_STUB_DITAMAP = "stub.ditamap"; public static final String FILE_EXTENSION_CHUNK = ".chunk"; public static final String ATTR_XTRF_VALUE_GENERATED = "generated_by_chunk"; public static final String CHUNK_BY_DOCUMENT = "by-document"; public static final String CHUNK_BY_TOPIC = "by-topic"; public static final String CHUNK_TO_CONTENT = "to-content"; public static final String CHUNK_TO_NAVIGATION = "to-navigation"; private DITAOTLogger logger; private boolean chunkByTopic = false; private String filePath = null; private LinkedHashMap<String, String> changeTable = null; private Hashtable<String, String> conflictTable = null; private final Random random; private Set<String> refFileSet = null; private String ditaext = null; private String transtype = null; private ProcessingInstruction workdir = null; private ProcessingInstruction workdirUrl = null; private ProcessingInstruction path2proj = null; private String processingRole = ATTR_PROCESSING_ROLE_VALUE_NORMAL; /** * Constructor. */ public ChunkMapReader() { super(); chunkByTopic=false;// By default, processor should chunk by document. changeTable = new LinkedHashMap<String, String>(INT_128); refFileSet = new HashSet<String>(INT_128); conflictTable = new Hashtable<String, String>(INT_128); random = new Random(); } /** * read input file. * @param filename filename */ @Override public void read(final String filename) { final File inputFile = new File(filename); filePath = inputFile.getParent(); try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(inputFile); // workdir and path2proj processing instructions. final NodeList docNodes = doc.getChildNodes(); for (int i = 0; i < docNodes.getLength(); i++) { final Node node = docNodes.item(i); if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { final ProcessingInstruction pi = (ProcessingInstruction) node; if (pi.getNodeName() == PI_WORKDIR_TARGET) { workdir = pi; } if (pi.getNodeName() == PI_WORKDIR_TARGET_URI) { workdirUrl = pi; } else if (pi.getNodeName().equals(PI_PATH2PROJ_TARGET)) { path2proj = pi; } } } //get the document node final Element root = doc.getDocumentElement(); //get the immediate child nodes final NodeList list = root.getChildNodes(); final String rootChunkValue = root.getAttribute(ATTRIBUTE_NAME_CHUNK); if(rootChunkValue != null && rootChunkValue.contains(CHUNK_BY_TOPIC)){ chunkByTopic = true; }else{ chunkByTopic = false; } //chunk value = "to-content" //When @chunk="to-content" is specified on "map" element, //chunk module will change its @class attribute to "topicref" //and process it as if it were a normal topicref wich @chunk="to-content" if(rootChunkValue != null && rootChunkValue.indexOf(CHUNK_TO_CONTENT)!=-1){ // if to-content is specified on map element // create the reference to the new file on root element. String newFilename = inputFile.getName().substring( 0, inputFile.getName().indexOf(FILE_EXTENSION_DITAMAP)) + ditaext; File newFile = new File(inputFile.getParentFile().getAbsolutePath(),newFilename); if (newFile.exists()) { newFilename = generateFilename("Chunk", ditaext); final String oldpath = newFile.getAbsolutePath(); newFile = new File(FileUtils.resolveFile(inputFile.getParentFile().getAbsolutePath(), newFilename)); // Mark up the possible name changing, in case that references might be updated. conflictTable.put(newFile.getAbsolutePath(), FileUtils.normalize(oldpath)); } //change the class attribute to "topicref" final String originClassValue = root.getAttribute(ATTRIBUTE_NAME_CLASS); root.setAttribute(ATTRIBUTE_NAME_CLASS, originClassValue + MAP_TOPICREF.matcher); root.setAttribute(ATTRIBUTE_NAME_HREF, newFilename); //create the new file OutputStreamWriter newFileWriter = null; try{ newFileWriter = new OutputStreamWriter(new FileOutputStream(newFile), UTF8); newFileWriter.write(XML_HEAD); newFileWriter.write(LESS_THAN); newFileWriter.write(QUESTION); newFileWriter.write(PI_WORKDIR_TARGET); newFileWriter.write(STRING_BLANK); newFileWriter.write(UNIX_SEPARATOR); newFileWriter.write(newFile.getParentFile().getAbsolutePath()); newFileWriter.write(QUESTION); newFileWriter.write(GREATER_THAN); newFileWriter.write(LESS_THAN); newFileWriter.write(QUESTION); newFileWriter.write(PI_WORKDIR_TARGET_URI); newFileWriter.write(STRING_BLANK); newFileWriter.write(UNIX_SEPARATOR); newFileWriter.write(newFile.getParentFile().toURI().toString()); newFileWriter.write(QUESTION); newFileWriter.write(GREATER_THAN); newFileWriter.write("<dita></dita>"); newFileWriter.flush(); newFileWriter.close(); }catch (final Exception e) { logger.logError(e.getMessage(), e) ; }finally{ try{ if(newFileWriter!=null){ newFileWriter.close(); } }catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } //process chunk processTopicref(root); //add newly created file to changeTable changeTable.put(newFile.getAbsolutePath(),newFile.getAbsolutePath()); // restore original root element if(originClassValue != null){ root.setAttribute(ATTRIBUTE_NAME_CLASS, originClassValue); } //remove the href root.removeAttribute(ATTRIBUTE_NAME_HREF); }else{ // if to-content is not specified on map element //process the map element's immediate child node(s) for (int i = 0; i < list.getLength(); i++){ final Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE){ final Element currentElem = (Element) node; final Node classAttr = node.getAttributes().getNamedItem(ATTRIBUTE_NAME_CLASS); String classValue = null; if(classAttr != null){ classValue = classAttr.getNodeValue(); } if(classValue != null && MAP_RELTABLE.matches(classValue)){ updateReltable(currentElem); } if(classValue != null && MAP_TOPICREF.matches(classValue) && !MAPGROUP_D_TOPICGROUP.matches(classValue)){ processTopicref(currentElem); } } } } //write the edited ditamap file to a temp file outputMapFile(inputFile.getAbsolutePath()+FILE_EXTENSION_CHUNK,root); if(!inputFile.delete()){ logger.logError(MessageUtils.getInstance().getMessage("DOTJ009E", inputFile.getPath(), inputFile.getAbsolutePath()+FILE_EXTENSION_CHUNK).toString()); } if(!new File(inputFile.getAbsolutePath()+FILE_EXTENSION_CHUNK).renameTo(inputFile)){ logger.logError(MessageUtils.getInstance().getMessage("DOTJ009E", inputFile.getPath(), inputFile.getAbsolutePath()+FILE_EXTENSION_CHUNK).toString()); } }catch (final Exception e){ logger.logError(e.getMessage(), e) ; } } /** * Generate file name * * @param prefix file name prefix * @param extension file extension * @return generated file name */ private String generateFilename(final String prefix, final String extension) { return prefix + random.nextInt(Integer.MAX_VALUE) + extension; } @Override public void setLogger(final DITAOTLogger logger) { this.logger = logger; } private void outputMapFile(final String file, final Element root) { OutputStreamWriter output = null; try{ output = new OutputStreamWriter( new FileOutputStream(file), UTF8); // path2proj processing instructions were not being sent to output. // The follow few lines corrects that problem. output.write(XML_HEAD); if (workdir != null) { output(workdir, output); } if (workdirUrl != null) { output(workdirUrl, output); } if (path2proj != null) { output(path2proj, output); } output(root,output); output.flush(); output.close(); }catch (final Exception e) { logger.logError(e.getMessage(), e) ; }finally{ try{ if(output!=null){ output.close(); } }catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } } private void output(final ProcessingInstruction instruction,final Writer outputWriter) throws IOException{ outputWriter.write(LESS_THAN); outputWriter.write(QUESTION); outputWriter.write(instruction.getTarget()); outputWriter.write(STRING_BLANK); outputWriter.write(instruction.getData()); outputWriter.write(QUESTION); outputWriter.write(GREATER_THAN); } private void output(final Text text, final Writer outputWriter) throws IOException{ outputWriter.write(StringUtils.escapeXML(text.getData())); } private void output(final Element elem, final Writer outputWriter) throws IOException{ outputWriter.write(LESS_THAN); outputWriter.write(elem.getNodeName()); final NamedNodeMap attrMap = elem.getAttributes(); for (int i = 0; i<attrMap.getLength(); i++){ outputWriter.write(STRING_BLANK); outputWriter.write(attrMap.item(i).getNodeName()); outputWriter.write(EQUAL); outputWriter.write(QUOTATION); outputWriter.write(StringUtils.escapeXML(attrMap.item(i).getNodeValue())); outputWriter.write(QUOTATION); } outputWriter.write(GREATER_THAN); final NodeList children = elem.getChildNodes(); for (int j = 0; j<children.getLength(); j++){ final Node child = children.item(j); switch (child.getNodeType()){ case Node.TEXT_NODE: output((Text) child, outputWriter); break; case Node.PROCESSING_INSTRUCTION_NODE: output((ProcessingInstruction) child, outputWriter); break; case Node.ELEMENT_NODE: output((Element) child, outputWriter); break; } } outputWriter.write(LESS_THAN); outputWriter.write(SLASH); outputWriter.write(elem.getNodeName()); outputWriter.write(GREATER_THAN); } //process chunk private void processTopicref(final Element node) { String hrefValue = null; String chunkValue = null; String copytoValue = null; String scopeValue = null; String classValue = null; String xtrfValue = null; String processValue = null; final String tempRole = processingRole; boolean prevChunkByTopic = false; final Node hrefAttr = node.getAttributeNode(ATTRIBUTE_NAME_HREF); final Node chunkAttr = node.getAttributeNode(ATTRIBUTE_NAME_CHUNK); final Node copytoAttr = node.getAttributeNode(ATTRIBUTE_NAME_COPY_TO); final Node scopeAttr = node.getAttributeNode(ATTRIBUTE_NAME_SCOPE); final Node classAttr = node.getAttributeNode(ATTRIBUTE_NAME_CLASS); final Node xtrfAttr = node.getAttributeNode(ATTRIBUTE_NAME_XTRF); final Node processAttr = node.getAttributeNode(ATTRIBUTE_NAME_PROCESSING_ROLE); if(hrefAttr != null){ hrefValue = hrefAttr.getNodeValue(); } if(chunkAttr != null){ chunkValue = chunkAttr.getNodeValue(); } if(copytoAttr != null){ copytoValue = copytoAttr.getNodeValue(); } if(scopeAttr != null) { scopeValue = scopeAttr.getNodeValue(); } if(classAttr != null) { classValue = classAttr.getNodeValue(); } if(xtrfAttr != null) { xtrfValue = xtrfAttr.getNodeValue(); } if(processAttr != null) { processValue = processAttr.getNodeValue(); processingRole = processValue; } //This file is chunked(by-topic) if (xtrfValue != null && xtrfValue.contains(ATTR_XTRF_VALUE_GENERATED)) { return; } //set chunkByTopic if there is "by-topic" or "by-document" in chunkValue if(chunkValue != null && (chunkValue.contains(CHUNK_BY_TOPIC) || chunkValue.contains(CHUNK_BY_DOCUMENT))){ //a temp value to store the flag prevChunkByTopic = chunkByTopic; //if there is "by-topic" then chunkByTopic should be set to true; chunkByTopic = chunkValue.contains(CHUNK_BY_TOPIC); } if(ATTR_SCOPE_VALUE_EXTERNAL.equalsIgnoreCase(scopeValue) || (hrefValue != null && !FileUtils.fileExists(FileUtils.resolveFile(filePath, hrefValue))) || (MAPGROUP_D_TOPICHEAD.matches(classValue) && chunkValue == null)|| ////support topicref without href attribute (MAP_TOPICREF.matches(classValue) && chunkValue == null && hrefValue == null) ) { //|| (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processValue))) { //Skip external links or non-existing href files. //Skip topic head entries. //Skip @processing-role=resource-only entries. if(chunkValue != null && (chunkValue.contains(CHUNK_BY_TOPIC) || chunkValue.contains(CHUNK_BY_DOCUMENT))){ chunkByTopic = prevChunkByTopic; } processChildTopicref(node); //chunk "to-content" } else if(chunkValue != null && //edited on 20100818 for bug:3042978 chunkValue.indexOf(CHUNK_TO_CONTENT) != -1 && (hrefAttr != null || copytoAttr != null || node.hasChildNodes())){ //if this is the start point of the content chunk //TODO very important start point(to-content). processChunk(node,false, chunkByTopic); }else if(chunkValue != null && chunkValue.indexOf(CHUNK_TO_NAVIGATION)!=-1 && INDEX_TYPE_ECLIPSEHELP.equals(transtype)){ //if this is the start point of the navigation chunk if(chunkValue != null && (chunkValue.contains(CHUNK_BY_TOPIC) || chunkValue.contains(CHUNK_BY_DOCUMENT))){ //restore the chunkByTopic value chunkByTopic = prevChunkByTopic; } processChildTopicref(node); //create new map file //create new map's root element final Node root = node.getOwnerDocument().getDocumentElement().cloneNode(false); //create navref element final Element navref = node.getOwnerDocument().createElement(MAP_NAVREF.localName); final String newMapFile = generateFilename("MAPCHUNK", ".ditamap"); navref.setAttribute(MAPGROUP_D_MAPREF.localName,newMapFile); navref.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_NAVREF.toString()); //replace node with navref node.getParentNode().replaceChild(navref,node); root.appendChild(node); // generate new file final String navmap = FileUtils.resolveFile(filePath,newMapFile); changeTable.put(navmap, navmap); outputMapFile(navmap,(Element)root); //chunk "by-topic" }else if(chunkByTopic){ //TODO very important start point(by-topic). processChunk(node,true, chunkByTopic); if(chunkValue != null && (chunkValue.contains(CHUNK_BY_TOPIC) || chunkValue.contains(CHUNK_BY_DOCUMENT))){ chunkByTopic = prevChunkByTopic; } processChildTopicref(node); }else{ String currentPath = null; if(copytoValue != null){ currentPath = FileUtils.resolveFile(filePath, copytoValue); }else if(hrefValue != null){ currentPath = FileUtils.resolveFile(filePath, hrefValue); } if(currentPath != null){ if(changeTable.containsKey(currentPath)){ changeTable.remove(currentPath); } if(!refFileSet.contains(currentPath)){ refFileSet.add(currentPath); } } // Here, we have a "by-document" chunk, simply // send it to the output. if ((chunkValue != null || !chunkByTopic) && currentPath != null && !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) { changeTable.put(currentPath, currentPath); } if (chunkValue != null && (chunkValue.contains(CHUNK_BY_TOPIC) || chunkValue.contains(CHUNK_BY_DOCUMENT))){ chunkByTopic = prevChunkByTopic; } processChildTopicref(node); } //restore chunkByTopic if there is "by-topic" or "by-document" in chunkValue if(chunkValue != null && (chunkValue.contains(CHUNK_BY_TOPIC) || chunkValue.contains(CHUNK_BY_DOCUMENT))){ chunkByTopic = prevChunkByTopic; } processingRole = tempRole; } private void processChildTopicref(final Node node) { final NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++){ final Node current = children.item(i); if(current.getNodeType()==Node.ELEMENT_NODE){ final Element currentElem = (Element) current; final String classValue = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS); final String hrefValue = currentElem.getAttribute(ATTRIBUTE_NAME_HREF); final String xtrfValue = currentElem.getAttribute(ATTRIBUTE_NAME_XTRF); if(MAP_TOPICREF.matches(classValue)){ if((hrefValue.length() != 0 && !ATTR_XTRF_VALUE_GENERATED.equals(xtrfValue) && ! FileUtils.resolveFile(filePath,hrefValue) .equals(changeTable.get(FileUtils.resolveFile(filePath,hrefValue)))) || MAPGROUP_D_TOPICHEAD.matches(classValue) ){ //make sure hrefValue make sense and target file //is not generated file or the element is topichead processTopicref(currentElem); //support topicref without href attribute }else if(hrefValue.length() == 0){ processTopicref(currentElem); } } } } } private void processChunk(final Element elem, final boolean separate, final boolean chunkByTopic) { //set up ChunkTopicParser try{ final ChunkTopicParser chunkParser = new ChunkTopicParser(); chunkParser.setLogger(logger); chunkParser.setup(changeTable, conflictTable, refFileSet, elem, separate, chunkByTopic, ditaext); chunkParser.write(filePath); }catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } private void updateReltable(final Element elem) { final String hrefValue = elem.getAttribute(ATTRIBUTE_NAME_HREF); if (hrefValue.length() != 0){ if(changeTable.containsKey(FileUtils.resolveFile(filePath,hrefValue))){ String resulthrefValue = null; if (hrefValue.indexOf(SHARP)!=-1){ resulthrefValue=FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP ,FileUtils.resolveFile(filePath,hrefValue)) + hrefValue.substring(hrefValue.indexOf(SHARP)+1); }else{ resulthrefValue=FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP ,FileUtils.resolveFile(filePath,hrefValue)); } elem.setAttribute(ATTRIBUTE_NAME_HREF, resulthrefValue); } } final NodeList children = elem.getChildNodes(); for(int i = 0; i < children.getLength(); i++){ final Node current = children.item(i); if(current.getNodeType() == Node.ELEMENT_NODE){ final Element currentElem = (Element) current; final String classValue = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS); if (MAP_TOPICREF.matches(classValue)){ } } } } /** * get content. * @return content value {@code LinkedHashMap<String, String>} * @deprecated use {@link #getChangeTable()} instead */ @Override @Deprecated public Content getContent() { throw new UnsupportedOperationException(); } /** * Get changed files table. * @return map of changed files */ public Map<String, String> getChangeTable() { return Collections.unmodifiableMap(changeTable); } /** * get conflict table. * @return conflict table */ public Hashtable<String, String> getConflicTable() { return conflictTable; } /** * Set up environment. * @param ditaext ditaext * @param transtype transtype */ public void setup(final String ditaext, final String transtype) { this.ditaext = ditaext; this.transtype = transtype; } }
package de.raphaelgeissler.dependencychecker.core.impl.validation; import static org.junit.Assert.*; import java.io.File; import java.util.Arrays; import java.util.jar.Manifest; import org.junit.Before; import org.junit.Test; import de.raphaelgeissler.dependencychecker.Checker; import de.raphaelgeissler.dependencychecker.core.api.DependencyValidationResult; import de.raphaelgeissler.dependencychecker.core.api.DependencyValidator; import de.raphaelgeissler.dependencychecker.core.impl.manifest.ManifestBuilder; import de.raphaelgeissler.dependencychecker.core.impl.manifest.ManifestDataStore; import de.raphaelgeissler.dependencychecker.core.impl.validation.DValBuilder; import de.raphaelgeissler.dependencychecker.core.impl.validation.DValCompBuilder; import de.raphaelgeissler.dependencychecker.core.impl.validation.DependencyCheckerConfig; import de.raphaelgeissler.dependencychecker.core.impl.validation.DependencyValidatorImpl; public class DependencyValidatorTest extends AbstractDependencyCheckerConfigTest { private DependencyCheckerConfig dependencyCheckerConfig; private ManifestDataStore manifestDataStore; @Before public void setup() { File configFile = new File("files/example/example.dependencychecker"); dependencyCheckerConfig = new DependencyCheckerConfig(); dependencyCheckerConfig.loadData(configFile.getAbsolutePath()); File manifestCore = new File("files/example/core/MANIFEST.MF"); File manifestModel = new File("files/example/model/MANIFEST.MF"); File manifestUI = new File("files/example/ui/MANIFEST.MF"); manifestDataStore = new ManifestDataStore(); manifestDataStore.parseManifestFiles(Arrays.asList(manifestCore.getAbsolutePath(), manifestModel.getAbsolutePath(), manifestUI.getAbsolutePath())); } @Test public void complexFailingValidation() throws Exception { DependencyValidator dependencyValidator = new DependencyValidatorImpl(dependencyCheckerConfig.getChecker(), manifestDataStore); DependencyValidationResult result = dependencyValidator.validate(); assertFalse(result.wasSuccessful()); assertTrue(result.getResultMessages().size() == 3); assertEquals("de.raphaelgeissler.example.ui", result.getResultMessages().get(2).getPluginId()); assertEquals("de.raphaelgeissler.example.model", result.getResultMessages().get(2).getDependencyPluginId()); assertEquals(7, result.getResultMessages().get(2).getLineNumber()); assertFalse(result.getResultMessages().get(2).correct()); } @Test public void testName() throws Exception { Checker checker = new DValBuilder("TestConfig") .comp(new DValCompBuilder("Core").id("de.ragedev.example.core.*").forbidden("UI")) .comp(new DValCompBuilder("UI").id("de.ragedev.example.ui.*")).build(); Manifest manifestCorePlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin1").build(); Manifest manifestCorePlugin2 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin2").build(); Manifest manifestCoreAPIPlugin = new ManifestBuilder().symbolicName("de.ragedev.example.core.api") .addRequiredBundle("de.ragedev.example.ui.plugin1").build(); Manifest manifestUI = new ManifestBuilder().symbolicName("de.ragedev.example.ui.plugin1") .addRequiredBundle("de.ragedev.example.core.api").build(); ManifestDataStore store = new ManifestDataStore(); store.parseManifests( Arrays.asList(manifestCorePlugin1, manifestCorePlugin2, manifestCoreAPIPlugin, manifestUI)); DependencyValidator dependencyValidator = new DependencyValidatorImpl(checker, store); DependencyValidationResult result = dependencyValidator.validate(); assertFalse(result.wasSuccessful()); } @Test public void sameComponent() throws Exception { Checker checker = new DValBuilder("TestConfig") .comp(new DValCompBuilder("Core").id("de.ragedev.example.core.*")).build(); Manifest manifestCorePlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin1").build(); Manifest manifestCorePlugin2 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin2") .addRequiredBundle("de.ragedev.example.core.plugin1").build(); ManifestDataStore store = new ManifestDataStore(); store.parseManifests(Arrays.asList(manifestCorePlugin1, manifestCorePlugin2)); DependencyValidator dependencyValidator = new DependencyValidatorImpl(checker, store); DependencyValidationResult result = dependencyValidator.validate(); assertTrue(result.wasSuccessful()); } @Test public void differentComponents() throws Exception { Checker checker = new DValBuilder("TestConfig") .comp(new DValCompBuilder("Core").id("de.ragedev.example.core.*").port("de.ragedev.example.core.api")) .comp(new DValCompBuilder("UI").id("de.ragedev.example.ui.*")).build(); Manifest manifestCorePlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin1").build(); Manifest manifestUiPlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.ui.plugin1") .addRequiredBundle("de.ragedev.example.core.plugin1").build(); ManifestDataStore store = new ManifestDataStore(); store.parseManifests(Arrays.asList(manifestCorePlugin1, manifestUiPlugin1)); DependencyValidator dependencyValidator = new DependencyValidatorImpl(checker, store); DependencyValidationResult result = dependencyValidator.validate(); assertFalse(result.wasSuccessful()); } @Test public void differentComponentsAndPort() throws Exception { Checker checker = new DValBuilder("TestConfig") .comp(new DValCompBuilder("Core").id("de.ragedev.example.core.*").port("de.ragedev.example.core.api")) .comp(new DValCompBuilder("UI").id("de.ragedev.example.ui.*")).build(); Manifest manifestCorePlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin1").build(); Manifest manifestUiPlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.ui.plugin1") .addRequiredBundle("de.ragedev.example.core.api").build(); ManifestDataStore store = new ManifestDataStore(); store.parseManifests(Arrays.asList(manifestCorePlugin1, manifestUiPlugin1)); DependencyValidator dependencyValidator = new DependencyValidatorImpl(checker, store); DependencyValidationResult result = dependencyValidator.validate(); assertTrue(result.wasSuccessful()); } @Test public void differentComponentsAndForbidden() throws Exception { Checker checker = new DValBuilder("TestConfig") .comp(new DValCompBuilder("Core").id("de.ragedev.example.core.*").port("de.ragedev.example.core.api")) .comp(new DValCompBuilder("UI").id("de.ragedev.example.ui.*").forbidden("Core")).build(); Manifest manifestCorePlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.core.plugin1").build(); Manifest manifestUiPlugin1 = new ManifestBuilder().symbolicName("de.ragedev.example.ui.plugin1") .addRequiredBundle("de.ragedev.example.core.api").build(); ManifestDataStore store = new ManifestDataStore(); store.parseManifests(Arrays.asList(manifestCorePlugin1, manifestUiPlugin1)); DependencyValidator dependencyValidator = new DependencyValidatorImpl(checker, store); DependencyValidationResult result = dependencyValidator.validate(); assertFalse(result.wasSuccessful()); } }
package controllers; import models.Client; import models.Grant; import play.mvc.Security; import play.mvc.Result; import java.net.URI; import java.net.URISyntaxException; import java.util.UUID; public class APIOAuthController extends BaseController { public static Result addClient(String clientId, String clientSecret, String callback) { Client client = new Client(); client.clientId = clientId; client.clientSecret = clientSecret; try { client.callBack = new URI(callback); } catch (URISyntaxException e) { e.printStackTrace(); } client.create(); return ok(); } @Security.Authenticated(Secured.class) public static Result authorize(String clientId, String user) { if (request().method().equals("GET")) { return ok("getmethod" + clientId); //redirect to authorization view } else { Grant grant = new Grant(); grant.user = Component.currentAccount(); grant.client = Client.findByClientId(clientId); String authorizationCode = UUID.randomUUID().toString(); grant.code = authorizationCode; grant.create(); return redirect(grant.client.callBack + "?code=" + authorizationCode); } } }
package flc.nbl_actors.experimental; import flc.nbl_actors.core.*; import flc.nbl_actors.experimental.log.*; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.*; public class ASyncTest { static void log(Object o) { System.out.println(o); } static String indent(int n) { final String spc = " "; return spc.substring(0, Math.min(spc.length(), n)); } private static volatile boolean isLogging; static class Node { static IASync<Integer> func(int depth) { if (depth < 1) return new ASyncDirect<>(1); final IGreenThrFactory f = ThreadContext.get().getFactory(); ForkJoin<Integer> fj = new ForkJoin<>(0); final Supplier<IASync<Integer>> message = () -> func(depth - 1); final BiFunction<Integer, Integer, Integer> callback2 = (s, v) -> { if (isLogging) log(indent(depth * 4 + 4) + v); return s + v; }; fj.callAsync(f.newThread(), message, callback2); fj.callAsync(f.newThread(), message, callback2); return fj.resultAsync(); } } private static void testASync(int depth, int nThr) throws InterruptedException { log("testASync nThr:" + nThr); final GreenThrFactory_single factory = new GreenThrFactory_single(nThr); final Integer value_exp = 2 << (depth - 1); factory.newThread().execute(() -> Node.func(depth).result(val -> { log(" expect: " + value_exp); log(" result: " + val); assertEquals(value_exp, val); factory.shutdown(); })); factory.reverseOrder(true); // factory.start(); factory.await(0); log(" OK testASync nThr:" + nThr); } @Test public void testASync() throws InterruptedException { isLogging = true; testASync(3, 1); isLogging = false; testASync(8, 4); } @Test public void testIASync_result() throws InterruptedException { log("\n\ntestIASync_result"); class Impl { IASync<Integer> func(int val) { return new ASyncDirect<>(val); } } try (IGreenThrFactory threads = new GreenThr_zero()) { ActorRef<Impl> ref = new ActorRef<>(threads, new Impl()); final Integer val = 234; threads.newThread().execute(() -> ref .call(a -> a.func(val)) .result(v -> { log(" value = " + v); assertEquals(val, v); log(" OK"); }) ); } } static void tst(GreenThrFactory_Q factory) throws InterruptedException { IGreenThr gt = factory.newThread(); CountDownLatch latch = new CountDownLatch(1); gt.execute(() -> { latch.countDown(); log(" gt.execute"); }); latch.await(); factory.shutdown(); } static void tst2(IGreenThrFactory factory) throws Exception { final AtomicInteger noPending = new AtomicInteger(1); final AtomicInteger nodes = new AtomicInteger(); final AtomicInteger noPendMax = new AtomicInteger(); final CountDownLatch pendingLatch = new CountDownLatch(1); class TreeNod extends ActorBase<TreeNod> { int traverse(int pos) { if (pos < 10000) { noPending.addAndGet(2); self().send(a -> traverse(pos * 10 + 1)); self().send(a -> traverse(pos * 10 + 2)); } log(" " + nodes.incrementAndGet() + " node: " + pos + " (" + (noPending.get() - 1) + ")"); if (noPending.addAndGet(-1) == 0) { log("traverse done."); pendingLatch.countDown(); } noPendMax.updateAndGet(op -> Math.max(op, noPending.get())); return pos; } IASync<Integer> sum(int a, int b) { return new ASyncDirect<>(a + b); } } final int a = 2; final int b = 10; IActorRef<TreeNod> actor = new TreeNod().init(factory); CompletableFuture<Integer> fut = new CompletableFuture<>(); factory.newThread().execute( () -> { actor.call(inst -> inst.sum(a, b)) .result(s -> { boolean ok = s == (a + b); log("sum: " + s + " ok:" + ok); }); actor.send(inst -> inst.sum(a, b).result(fut::complete)); actor.call(inst -> a + b, s -> { boolean ok = s == (a + b); log("sum2: " + s + " ok:" + ok); }); actor.send(inst -> inst.traverse(1)); } ); int ab = fut.get(); //blocks assert ab == a + b; pendingLatch.await(); log("traverse max: " + noPendMax.get()); } @Test public void testGreenThrFactory_N() throws InterruptedException { log("\n\ntestGreenThrFactory_N.."); ExecutorService exec = Executors.newFixedThreadPool(4); GreenThrFactory_Exec factory = new GreenThrFactory_Exec(exec); final AtomicInteger count = new AtomicInteger(0); final int N = 3; for (int n = 0; n < N; ++n) { factory.newThread().execute(() -> { int no = count.incrementAndGet(); log(" do " + no); }); } factory.setEmptyListener(() -> { log("done"); factory.shutdown(); }); factory.await(0); assertEquals(N, count.get()); } @Test public void testFactory() throws Exception { try (IGreenThrFactory f = new GreenThrFactory_Q(1)) { tst2(f); } tst(new GreenThrFactory_Q(2)); tst(new GreenThrFactory_Q(Executors.newFixedThreadPool(2), 2)); } @Test public void testMessageRelay_RingBuf() throws InterruptedException { final MsgListenerFactoryRingBuf buffer = new MsgListenerFactoryRingBuf(100, null); final ThreadLocal<IMsgEvent> lastEvent = new ThreadLocal<>(); class Info implements Supplier<String> { final String s; final int depth; public Info(String s, int depth) { this.s = s; this.depth = depth; } @Override public String get() { return s + depth; } void assertSent(IMsgEvent event, IGreenThr toThr) { MsgSent s = (MsgSent) event; assertTrue(s.userInfo == this); assertTrue(s.targetThread == toThr); } void assertReceived(IMsgEvent event) { MsgSent s = ((MsgReceived) event).sent; assertTrue(s.userInfo == this); } } class TraceCheck implements Consumer<IMsgEvent> { @Override public void accept(IMsgEvent rec) { lastEvent.set(rec); System.out.println("Message trace:"); int depth = 0; List<IMsgEvent> trace = buffer.getMessageTrace(rec); for (IMsgEvent event : trace) { System.out.println(" * " + event); ++depth; } MessageRelay.TContext ctx = MessageRelay.getContext(); MsgSent sent; if (rec instanceof MsgSent) { sent = (MsgSent) rec; assertEquals("sent id", rec.id(), ctx.getLastSent().id()); } else { sent = ((MsgReceived) rec).sent; assertEquals("received id", rec.id(), ctx.getLastReceived().id()); List<IMsgEvent> trace2 = ctx.getMessageTrace(); assertEquals("getMessageTrace:list", trace, trace2); } if (sent.userInfo instanceof Info) { Info info = (Info) sent.userInfo; assertEquals("getMessageTrace;depth", depth, info.depth); } } } class Action { void repeat(final int depth, final IGreenThrFactory gf) { IGreenThr thr = gf.newThread(); final Info info = new Info("A", depth); MessageRelay.logInfo(info); thr.execute(() -> { info.assertReceived(lastEvent.get()); System.out.println(" got A" + depth); if (depth < 4) repeat(depth + 1, gf); }); info.assertSent(lastEvent.get(), thr); final Info infoB = new Info("B", depth); MessageRelay.logInfo(infoB); thr.execute(() -> { infoB.assertReceived(lastEvent.get()); System.out.println(" got B" + depth); }); infoB.assertSent(lastEvent.get(), thr); } } class MyActor extends ActorBase<MyActor> { void call(int value) { System.out.println(" actor received " + value); } } System.out.println("testMessageRelay_RingBuf"); try (IGreenThrFactory gf = new GreenThrFactory_single(4)) { buffer.listenToIncoming(new TraceCheck()); gf.setMessageRelay(new MessageRelay(buffer)); new Action().repeat(1, gf); final int no = 747; MessageRelay.logInfo("" + no); new MyActor().init(gf) .send(a -> a.call(no)); // gf.await(10000L); gf.await(0); } System.out.println("\nDone running. Buffer dump:"); buffer.forEach(e -> System.out.println(e.info())); System.out.println("done testMessageRelay_RingBuf"); //todo? junit-test smaller parts } }
package org.jboss.plugins; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.maven.plugin.logging.Log; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.XmlUtil; import org.w3c.dom.Document; public class RegisterExtension { final Log log; public RegisterExtension(Log log) { this.log = log; } /** * registers extension to standalone.xml * @param options * @param destFile output file (standalone.xml or domain.xml with new stuff) * @param moduleId ID of JBoss Module to register as an JBoss extension * @throws Exception */ public void register(RegisterOptions options, File destFile, String moduleId) throws Exception { try { log.info("Register extension module="+moduleId); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // we still need to read standalone.xml and subsystem.xml to DOM to be able to detect namespaces Document srcDoc = dBuilder.parse(options.getServerConfig()); Document subsystemDoc = null; Document socketBindingDoc = null; // unset profiles in case we're not editing domain.xml if (isStandaloneXml(srcDoc)) { options.profiles(null); } if (options.getSubsystem().isFile() && options.getSubsystem().canRead()) { subsystemDoc = dBuilder.parse(options.getSubsystem()); log.info("Configuring subsystem from file "+options.getSubsystem()); } else { log.info("Subsystem file ["+options.getSubsystem()+"] does not exist, subsystem will not be configured"); } if (options.getSocketBinding().isFile() && options.getSocketBinding().canRead()) { socketBindingDoc = dBuilder.parse(options.getSocketBinding()); log.info("Configuring socket-binding from file "+options.getSocketBinding()); } else { log.info("Socket-binding file ["+options.getSocketBinding()+"] does not exist, socket-binding will not be configured"); } // do XSL transformation TransformerFactory f = TransformerFactory.newInstance(); InputStream stylesheet = createStylesheet( getNameSpace(srcDoc), moduleId, subsystemDoc, options.getProfiles(), socketBindingDoc, options.getSocketBindingGroups() ); Transformer t = f.newTransformer(new StreamSource(stylesheet)); Source s = new StreamSource(options.getServerConfig()); Result r = new StreamResult(destFile); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); t.transform(s, r); // finallly pretty-print output file (XSL transformation does not handle whitespace text nodes well) formatXmlDocument(destFile); log.info("New serverConfig file written to ["+destFile.getAbsolutePath()+"]"); } catch (TransformerConfigurationException e) { throw new Exception(e.toString()); } catch (TransformerException e) { throw new Exception(e.toString()); } } private InputStream createStylesheet(String namespace, String module, Document subsystem, String[] profileNames, Document socketBinding, String[] socketBindingGroups) throws IOException { // when writing new nodes we'll ignore wring xmlns attribute String ignoreNs = "s"; // s is main namespace for server config String subns = ""; boolean isSubsystem = subsystem != null; boolean isSocketBinding = socketBinding != null; StringBuilder sheet = new StringBuilder("<?xml version=\"1.0\" ?>"); sheet.append("<xsl:stylesheet xmlns:xsl=\"http: + " xmlns:s=\"" + namespace + "\""); if (isSubsystem) { subns = getNameSpace(subsystem); sheet.append(" xmlns:sub=\"" + subns + "\""); ignoreNs += " sub"; // sub is namespace for subsystem we're setting up } sheet.append(" exclude-result-prefixes=\"" + ignoreNs + "\" version=\"1.0\">"); // for both extensions and profiles we first copy all nodes by excluding potentially existing one and then we append new content // append new extension sheet.append("<xsl:variable name=\"extension\"><extension module=\""+ module+ "\" /></xsl:variable>"); sheet.append("<xsl:template match=\"s:extensions\"><xsl:copy><xsl:apply-templates select=\"*[not(@module='" + module + "')]\" /><xsl:copy-of select=\"$extension\" /></xsl:copy>" + "</xsl:template>"); // append new subsystem if (isSubsystem) { String profileSelector = createXPathNameAttributeSelector(profileNames); sheet.append("<xsl:variable name=\"subsystem\">"+ doc2string(subsystem)+ "</xsl:variable>"); sheet.append("<xsl:template match=\"s:profile"+profileSelector+"\"><xsl:copy>" + "<xsl:apply-templates select=\"@*\" />" + "<xsl:apply-templates select=\"*[not(namespace-uri() ='"+ subns+ "')]\" />" + "<xsl:copy-of select=\"$subsystem\" /></xsl:copy>" + "</xsl:template>"); } // append new socket-binding if (isSocketBinding) { String sbgSelector = createXPathNameAttributeSelector(socketBindingGroups); String bindingName = socketBinding.getDocumentElement().getAttribute("name"); sheet.append("<xsl:variable name=\"socketBinding\">"+ doc2string(socketBinding)+ "</xsl:variable>"); sheet.append("<xsl:template match=\"s:socket-binding-group"+sbgSelector+"\"><xsl:copy>" + "<xsl:apply-templates select=\"@*\" />" + "<xsl:apply-templates select=\"*[not(@name='"+ bindingName + "')]\" />" + "<xsl:copy-of select=\"$socketBinding\" /></xsl:copy>" + "</xsl:template>"); } // generic identity template sheet.append("<xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\" /></xsl:copy></xsl:template>"); sheet.append("</xsl:stylesheet>"); log.debug("XSL :"+sheet); return new ByteArrayInputStream(IOUtil.toByteArray(sheet.toString())); } private static String createXPathNameAttributeSelector(String[] names) { if (names == null || names.length == 0) { return ""; } StringBuilder sb = new StringBuilder("["); for (String name : names) { sb.append("@name='"+name+"' or "); } sb.delete(sb.length()-4, sb.length()); sb.append("]"); return sb.toString(); } private static boolean isStandaloneXml(Document doc) { return "server".equals(doc.getDocumentElement().getNodeName()); } /** * return XML namespace for root of given document * @param doc * @return */ private static String getNameSpace(Document doc) { if (doc == null) { return null; } return doc.getDocumentElement().getAttribute("xmlns"); } private void formatXmlDocument(File file) { try { InputStream is = new ByteArrayInputStream(IOUtil.toByteArray(new FileInputStream(file))); XmlUtil.prettyFormat(is, new FileOutputStream(file),4,System.getProperty("line.separator")); IOUtil.close(is); } catch (Exception ex) { throw new RuntimeException("Error formatting file "+file.getAbsolutePath(), ex); } } /** * return content of XML document as string * @param doc * @return */ private String doc2string(Document doc) { if (doc == null) { return null; } try { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); } catch (Exception ex) { throw new RuntimeException("Error converting to String", ex); } } }
package org.jtrfp.trcl.obj; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Camera; import org.jtrfp.trcl.NormalMap; import org.jtrfp.trcl.OverworldSystem; import org.jtrfp.trcl.RenderMode; import org.jtrfp.trcl.Triangle; import org.jtrfp.trcl.Tunnel; import org.jtrfp.trcl.World; import org.jtrfp.trcl.beh.Behavior; import org.jtrfp.trcl.beh.CollidesWithTerrain; import org.jtrfp.trcl.beh.CollidesWithTunnelWalls; import org.jtrfp.trcl.beh.CollisionBehavior; import org.jtrfp.trcl.beh.DamageableBehavior; import org.jtrfp.trcl.beh.LoopingPositionBehavior; import org.jtrfp.trcl.beh.NAVTargetableBehavior; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.file.DirectionVector; import org.jtrfp.trcl.game.Game; import org.jtrfp.trcl.game.TVF3Game; import org.jtrfp.trcl.gpu.GL33Model; import org.jtrfp.trcl.gpu.PortalTexture; import org.jtrfp.trcl.gpu.Renderer; import org.jtrfp.trcl.gui.ReporterFactory.Reporter; import org.jtrfp.trcl.miss.Mission; import org.jtrfp.trcl.miss.NAVObjective; import org.jtrfp.trcl.shell.GameShellFactory.GameShell; public class TunnelExitObject extends PortalEntrance { private Vector3D exitLocation, exitHeading, exitTop; private final Tunnel tun; private NAVObjective navObjectiveToRemove; private boolean mirrorTerrain = false; private boolean onlyRemoveIfTargeted=false; private static final int NUDGE = 5000; private GameShell gameShell; public TunnelExitObject(Tunnel tun, String debugName, WorldObject approachingObject) { super(new PortalExit(),approachingObject); addBehavior(new TunnelExitBehavior()); final DirectionVector v = tun.getSourceTunnel().getExit(); final NormalMap map = new NormalMap( getGameShell(). getGame(). getCurrentMission(). getOverworldSystem(). getAltitudeMap()); final double exitY = map.heightAt(TRFactory.legacy2Modern(v.getZ()), TRFactory.legacy2Modern(v .getX())); this.exitLocation = new Vector3D(TRFactory.legacy2Modern(v.getZ()), exitY, TRFactory.legacy2Modern(v .getX())); this.tun = tun; exitHeading = map. normalAt( exitLocation.getX(), exitLocation.getZ()); this.exitLocation = exitLocation.add(exitHeading.scalarMultiply(NUDGE)); if(exitHeading.getY()<.99&&exitHeading.getNorm()>0)//If the ground is flat this doesn't work. exitTop = (Vector3D.PLUS_J.crossProduct(exitHeading).crossProduct(exitHeading)).negate(); else exitTop = (Vector3D.PLUS_I);// ... so we create a clause for that. final PortalExit pExit = getPortalExit(); pExit.setPosition(exitLocation.toArray()); pExit.setHeading(exitHeading); pExit.setTop(exitTop); pExit.setRootGrid(((TVF3Game)getGameShell().getGame()).getCurrentMission().getOverworldSystem()); pExit.notifyPositionChange(); this.setPortalExit(pExit); setPortalTexture(new PortalTexture()); setVisible(true); Triangle [] tris = Triangle.quad2Triangles(new double[]{-50000,50000,50000,-50000}, new double[]{50000,50000,-50000,-50000}, new double[]{0,0,0,0}, new double[]{0,1,1,0}, new double[]{1,1,0,0}, getPortalTexture(), RenderMode.STATIC, false, Vector3D.ZERO, "TunnelExitObject.portalModel"); //Model m = Model.buildCube(100000, 100000, 200, new PortalTexture(0), new double[]{50000,50000,100},false,tr); GL33Model m = new GL33Model(false, getTr(),"TunnelExitObject."+debugName); m.addTriangles(tris); setModel(m); }//end constructor private class TunnelExitBehavior extends Behavior implements CollisionBehavior, NAVTargetableBehavior { private boolean navTargeted=false; @Override public void proposeCollision(WorldObject other) { final TR tr = getTr(); if (other instanceof Player) { if(getParent().getPosition()[0]<0) throw new RuntimeException("Negative X coord! "+getParent().getPosition()[0]); //System.out.println("TunnelExitObject relevance tally="+tr.gpu.get().rendererFactory.get().getRelevanceTallyOf(getParent())+" within range? "+TunnelExitObject.this.isWithinRange()); //We want to track the camera's crossing in deciding when to move the player. final Camera camera = tr.mainRenderer.getCamera(); //System.out.println("hash: "+super.hashCode()+" Cam pos = "+camera.getPosition()[0]+" thisPos="+TunnelExitObject.this.getPosition()[0]); if (camera.getPosition()[0] > TunnelExitObject.this .getPosition()[0]) { System.out.println("Escaping tunnel at exit.X="+getPosition()[0]+" camera.X="+camera.getPosition()[0]); final Game game = ((TVF3Game)getGameShell().getGame()); final Mission mission = game.getCurrentMission(); final OverworldSystem overworldSystem = mission.getOverworldSystem(); System.out.println("TunnelExitObject leaving tunnel "+tun); //tr.getDefaultGrid().nonBlockingAddBranch(overworldSystem); //tr.getDefaultGrid().nonBlockingRemoveBranch(branchToRemove) tr.mainRenderer.getSkyCube().setSkyCubeGen(overworldSystem.getSkySystem().getBelowCloudsSkyCubeGen()); final Renderer portalRenderer = TunnelExitObject.this.getPortalRenderer(); //if(portalRenderer == null) //portalRenderer.getSkyCube().setSkyCubeGen(GameShellFactory.DEFAULT_GRADIENT); // Teleport //final Camera secondaryCam = portalRenderer.getCamera(); final TunnelExitObject teo = (TunnelExitObject)this.getParent(); other.setPosition(teo.getPortalExit().getControlledPosition()); other.setHeadingArray(teo.getPortalExit().getControlledHeading()); other.setTopArray(teo.getPortalExit().getControlledTop()); other.notifyPositionChange(); World.relevanceExecutor.submit(new Runnable(){ @Override public void run() { //final SpacePartitioningGrid grid = tr.getDefaultGrid(); // Tunnel off //grid.removeBranch(tun); // World on //grid.addBranch(overworldSystem); //Switch to overworld mode //try{mission.setDisplayMode(mission.overworldMode);} //catch(Exception e){e.printStackTrace();} // Nav //grid.addBranch(game.getNavSystem()); }}); // Reset player behavior final Player player = ((TVF3Game)getGameShell().getGame()).getPlayer(); player.setActive(false); player.resetVelocityRotMomentum(); player.probeForBehavior(CollidesWithTunnelWalls.class) .setEnable(false); player.probeForBehavior(DamageableBehavior.class) .addInvincibility(250);// Safety kludge when near // walls. player.probeForBehavior(CollidesWithTerrain.class) .setEnable(true); player.probeForBehavior(LoopingPositionBehavior.class) .setEnable(true); /* player.probeForBehavior( HeadingXAlwaysPositiveBehavior.class) .setEnable(false);*/ // Update debug data Features.get(tr, Reporter.class).report("org.jtrfp.Tunnel.isInTunnel?", "false"); // Reset projectile behavior final ProjectileFactory[] pfs = tr.getResourceManager() .getProjectileFactories(); for (ProjectileFactory pf : pfs) { Projectile[] projectiles = pf.getProjectiles(); for (Projectile proj : projectiles) { ((WorldObject) proj) .probeForBehavior( LoopingPositionBehavior.class) .setEnable(true); }// end for(projectiles) }// end for(projectileFactories) final NAVObjective navObjective = getNavObjectiveToRemove(); if (navObjective != null && (navTargeted|!onlyRemoveIfTargeted)) { ((TVF3Game)getGameShell().getGame()).getCurrentMission().removeNAVObjective(navObjective); }// end if(have NAV to remove if(mirrorTerrain){ tr.setRunState(new Mission.ChamberState(){}); }else tr.setRunState(new Mission.OverworldState(){}); overworldSystem.setChamberMode(mirrorTerrain);//TODO: Use PCL to set this automatically in Mission /* if(mirrorTerrain) tr.setRunState(new Mission.ChamberState(){}); else tr.setRunState(new Mission.PlayerActivity(){}); */ ((TVF3Game)getGameShell().getGame()).getNavSystem().updateNAVState(); mission.setDisplayMode(mission.getOverworldMode()); overworldSystem.setTunnelMode(false); player.setActive(true); }// end if(x past threshold) }// end if(Player) }// end proposeCollision() @Override public void notifyBecomingCurrentTarget() { navTargeted=true; } }// end TunnelExitBehavior /** * @return the navObjectiveToRemove */ public NAVObjective getNavObjectiveToRemove() { return navObjectiveToRemove; } /** * @param navObjectiveToRemove * the navObjectiveToRemove to set * @param onlyRemoveIfTargeted */ public void setNavObjectiveToRemove(NAVObjective navObjectiveToRemove, boolean onlyRemoveIfTargeted) { this.onlyRemoveIfTargeted = onlyRemoveIfTargeted; this.navObjectiveToRemove = navObjectiveToRemove; } public void setMirrorTerrain(boolean b) { mirrorTerrain = b; } /** * @return the exitLocation */ public Vector3D getExitLocation() { return exitLocation; } /** * @param exitLocation * the exitLocation to set */ public void setExitLocation(Vector3D exitLocation) { this.exitLocation = exitLocation; } /** * @return the mirrorTerrain */ public boolean isMirrorTerrain() { return mirrorTerrain; } public GameShell getGameShell() { if(gameShell == null){ gameShell = Features.get(getTr(), GameShell.class);} return gameShell; } public void setGameShell(GameShell gameShell) { this.gameShell = gameShell; } }// end TunnelExitObject
package org.lantern.monitoring; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.lantern.Country; import org.lantern.LanternConstants; import org.lantern.LanternService; import org.lantern.LanternUtils; import org.lantern.event.Events; import org.lantern.monitoring.Stats.Gauges; import org.lantern.state.Mode; import org.lantern.state.Model; import org.lantern.state.SyncPath; import org.lantern.util.Threads; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class StatsManager implements LanternService { private static final Logger LOGGER = LoggerFactory .getLogger(StatsManager.class); // Get stats every minute private static final long GET_INTERVAL = 60; // Post stats every 5 minutes private static final long POST_INTERVAL = 5 * 60; private static final long FALLBACK_POST_INTERVAL = 20; private final Model model; private final StatshubAPI statshub = new StatshubAPI( LanternUtils.isFallbackProxy() ? null : LanternConstants.LANTERN_LOCALHOST_ADDR); private final MemoryMXBean memoryMXBean = ManagementFactory .getMemoryMXBean(); private final OperatingSystemMXBean osStats = ManagementFactory .getOperatingSystemMXBean(); private final ScheduledExecutorService getScheduler = Threads .newSingleThreadScheduledExecutor("StatsManager-Get"); private final ScheduledExecutorService postScheduler = Threads .newSingleThreadScheduledExecutor("StatsManager-Post"); @Inject public StatsManager(Model model) { this.model = model; } @Override public void start() { getScheduler.scheduleAtFixedRate( getStats, 30, GET_INTERVAL, TimeUnit.SECONDS); postScheduler.scheduleAtFixedRate( postStats, 60, // wait 1 minute before first posting stats, to give the // system a chance to initialize metadata LanternUtils.isFallbackProxy() ? FALLBACK_POST_INTERVAL : POST_INTERVAL, TimeUnit.SECONDS); } @Override public void stop() { getScheduler.shutdownNow(); postScheduler.shutdownNow(); try { getScheduler.awaitTermination(30, TimeUnit.SECONDS); postScheduler.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException ie) { LOGGER.warn("Unable to await termination of schedulers", ie); } } private final Runnable getStats = new Runnable() { public void run() { try { StatsResponse resp = statshub.getStats("country"); if (resp != null) { Map<String, Stats> countryDim = resp.getDims().get( "country"); if (countryDim != null) { model.setGlobalStats(countryDim.get("total")); for (Country country : model.getCountries().values()) { country.setStats(countryDim.get( country.getCode().toLowerCase())); } Events.sync(SyncPath.GLOBAL_STATS, model.getGlobalStats()); Events.sync(SyncPath.COUNTRIES, model.getCountries()); } } } catch (Exception e) { LOGGER.warn("Unable to getStats: " + e.getMessage(), e); } } }; private final Runnable postStats = new Runnable() { public void run() { // Only report stats if user enabled auto-reporting if (model.getSettings().isAutoReport()) { try { String userGuid = model.getUserGuid(); String countryCode = model.getLocation().getCountry(); if (StringUtils.isBlank(countryCode) || "--".equals(countryCode)) { countryCode = "xx"; } String instanceId = model.getInstanceId(); Stats instanceStats = model.getInstanceStats().toInstanceStats(); addSystemStats(instanceStats); statshub.postInstanceStats( instanceId, userGuid, countryCode, LanternUtils.isFallbackProxy(), instanceStats); if (userGuid != null) { Stats userStats = model.getInstanceStats() .toUserStats( userGuid, Mode.give == model.getSettings() .getMode(), Mode.get == model.getSettings() .getMode()); statshub.postUserStats(userGuid, countryCode, userStats); } } catch (Exception e) { LOGGER.warn("Unable to postStats: " + e.getMessage(), e); } } } }; private void addSystemStats(Stats stats) { stats.setGauge(Gauges.processCPUUsage, scalePercent(getSystemStat("getProcessCpuLoad"))); stats.setGauge(Gauges.systemCPUUsage, scalePercent(getSystemStat("getSystemCpuLoad"))); stats.setGauge(Gauges.systemLoadAverage, scalePercent(osStats.getSystemLoadAverage())); stats.setGauge(Gauges.memoryUsage, memoryMXBean .getHeapMemoryUsage() .getCommitted() + memoryMXBean.getNonHeapMemoryUsage() .getCommitted()); stats.setGauge(Gauges.openFileDescriptors, getOpenFileDescriptors()); } private long getOpenFileDescriptors() { if (!isOnUnix()) { return 0L; } return (Long) getSystemStat("getOpenFileDescriptorCount"); } private Long scalePercent(Number value) { if (value == null) return null; return (long) (((Double) value) * 100.0); } private <T extends Number> T getSystemStat(final String name) { if (!isOnUnix()) { return (T) (Double) 0.0; } else { try { final Method method = osStats.getClass() .getDeclaredMethod(name); method.setAccessible(true); return (T) method.invoke(osStats); } catch (final Exception e) { LOGGER.debug("Unable to get system stat: {}", name, e); return (T) (Double) 0.0; } } } private boolean isOnUnix() { return osStats.getClass().getName() .equals("com.sun.management.UnixOperatingSystem"); } }
package org.mitre.synthea.engine; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.mitre.synthea.helpers.TimeSeriesData; import org.mitre.synthea.world.agents.Person; /** * Various components used in the generic module framework. * All components should be defined within this class. */ public abstract class Components { /** * A Range of values, with a low and a high. * Values must be numeric. (ex, Integer, Long, Double) * * @param <R> Type of range */ public static class Range<R extends Number> { /** * Minimum value of the range. */ public R low; /** * Maximum value of the range. */ public R high; /** * Decimal places for value within the range. */ public Integer decimals; } /** * Variant of the Range class, where a unit is required. * Defining this in a separate class makes it easier to define * where units are and are not required. * * @param <R> Type of range */ public static class RangeWithUnit<R extends Number> extends Range<R> { /** * Unit for the range. Ex, "years" if the range represents an amount of time. */ public String unit; } /** * An Exact quantity representing a single fixed value. Note that "quantity" here may be a bit of * a misnomer as the value does not have to be numeric. Ex, it may be a String or Code. * * @param <T> * Type of quantity */ public static class Exact<T> { /** * The fixed value. */ public T quantity; } /** * Variant of the Exact class, where a unit is required. * Defining this in a separate class makes it easier to define * where units are and are not required. * * @param <T> Type of quantity */ public static class ExactWithUnit<T> extends Exact<T> { /** * Unit for the quantity. Ex, "days" if the quantity represents an amount of time. */ public String unit; } public static class DateInput { public int year; public int month; public int day; public int hour; public int minute; public int second; public int millisecond; } public static class SampledData { public double originValue; // Zero value public Double factor; // Multiply data by this before adding to origin public Double lowerLimit; // Lower limit of detection public Double upperLimit; // Upper limit of detection public List<String> attributes; // Person attributes containing TimeSeriesData objects public transient List<TimeSeriesData> series; // List of actual series data collections // Format for the output decimal numbers public String decimalFormat; /** * Retrieves the actual data lists from the given Person according to * the provided timeSeriesAttributes values. * @param person Person to get time series data from */ public void setSeriesData(Person person) { int dataLen = 0; double dataPeriod = 0; series = new ArrayList<TimeSeriesData>(attributes.size()); for (String attr : attributes) { TimeSeriesData data = (TimeSeriesData) person.attributes.get(attr); if (dataLen == 0) { dataLen = data.getValues().size(); dataPeriod = data.getPeriod(); } else { // Verify that each series is consistent in length if (data.getValues().size() != dataLen) { throw new IllegalArgumentException("Provided series [" + StringUtils.join(attributes, ", ") + "] have inconsistent lengths!"); } // Verify that each series has identical period if (data.getPeriod() != dataPeriod) { throw new IllegalArgumentException("Provided series [" + StringUtils.join(attributes, ", ") + "] have inconsistent periods!"); } } series.add(data); } } } }
package org.mitre.synthea.engine; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.stream.XMLStreamException; import org.apache.commons.math.ode.DerivativeException; import org.sbml.jsbml.Model; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.SBMLException; import org.sbml.jsbml.validator.ModelOverdeterminedException; import org.sbml.jsbml.xml.stax.SBMLReader; import org.simulator.math.odes.AdamsBashforthSolver; import org.simulator.math.odes.AdamsMoultonSolver; import org.simulator.math.odes.AbstractDESSolver; import org.simulator.math.odes.DormandPrince54Solver; import org.simulator.math.odes.DormandPrince853Solver; import org.simulator.math.odes.EulerMethod; import org.simulator.math.odes.GraggBulirschStoerSolver; import org.simulator.math.odes.HighamHall54Solver; import org.simulator.math.odes.MultiTable; import org.simulator.math.odes.MultiTable.Block; import org.simulator.math.odes.RosenbrockSolver; import org.simulator.math.odes.RungeKutta_EventSolver; import org.simulator.sbml.SBMLinterpreter; /** * Physiology represents the entry point of a physiology simulation submodule. */ public class Physiology { private static final Map<String, Class> SOLVER_CLASSES; private static final Map<String, AbstractDESSolver> SOLVERS = new HashMap(); private static Path sbmlPath; private final SBMLinterpreter interpreter; private final String[] modelFields; private final double[] modelDefaults; private final AbstractDESSolver solver; private final double simDuration; private final double leadTime; static { Map<String, Class> initSolvers = new HashMap(); // Add all currently available solvers from the SBSCL library initSolvers.put("adams_bashforth", AdamsBashforthSolver.class); initSolvers.put("adams_moulton", AdamsMoultonSolver.class); initSolvers.put("dormand_prince_54", DormandPrince54Solver.class); initSolvers.put("dormand_prince_853", DormandPrince853Solver.class); initSolvers.put("euler", EulerMethod.class); initSolvers.put("gragg_bulirsch_stoer", GraggBulirschStoerSolver.class); initSolvers.put("higham_hall_54", HighamHall54Solver.class); initSolvers.put("rosenbrock", RosenbrockSolver.class); initSolvers.put("runge_kutta", RungeKutta_EventSolver.class); // Make unmodifiable so it doesn't change after initialization SOLVER_CLASSES = Collections.unmodifiableMap(initSolvers); // get the path to our physiology models directory containing SBML files URL physiologyFolder = ClassLoader.getSystemClassLoader().getResource("physiology"); try { sbmlPath = Paths.get(physiologyFolder.toURI()); } catch (URISyntaxException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); } } /** * Physiology constructor. * @param modelPath Path to the SBML file to load relative to resources/physiology * @param solverName Name of the solver to use * @param stepSize Time step for the simulation * @param simDuration Amount of time to simulate */ public Physiology(String modelPath, String solverName, double stepSize, double simDuration) { this(modelPath, solverName, stepSize, simDuration, 0); } /** * Physiology constructor. * @param modelPath Path to the SBML file to load relative to resources/physiology * @param solverName Name of the solver to use * @param stepSize Time step for the simulation * @param simDuration Amount of time to simulate * @param leadTime Amount of time to run the simulation before capturing results */ public Physiology(String modelPath, String solverName, double stepSize, double simDuration, double leadTime) { Path modelFilepath = Paths.get(sbmlPath.toString(), modelPath); interpreter = getInterpreter(modelFilepath.toString()); modelFields = interpreter.getIdentifiers(); modelDefaults = interpreter.getInitialValues(); solver = getSolver(solverName); solver.setStepSize(stepSize); this.simDuration = simDuration; this.leadTime = leadTime; } /** * Solves the model at each time step for the specified duration using the provided inputs * as initial parameters. Provides the results as a map of value lists where each key is * a model parameter. In addition to the model parameters is a "Time" field which provides * a list of all simulated time points. * <p> * Note that this method will throw a DerivativeException if the model encounters an error * while attempting to solve the system. * @param inputs Map of model parameter inputs. For any parameters which are not provided * the default value from the model will be used. * @return map of parameter names to value lists * @throws DerivativeException */ public MultiTable run(Map<String, Double> inputs) throws DerivativeException { // Reset the solver to its initial state solver.reset(); // Create a copy of the default parameters to use double[] params = Arrays.copyOf(modelDefaults, modelDefaults.length); // Overwrite model defaults with the provided input parameters for(int i=0; i < modelFields.length; i++) { String field = modelFields[i]; if(inputs.containsKey(field)) { params[i] = inputs.get(field); } } // Solve the ODE for the specified duration and return the results return solver.solve(interpreter, params, -leadTime, simDuration); } /** * Checks whether a string is a valid solver name. * @param solverName solver name string to check * @return true if valid false otherwise. */ public static boolean checkValidSolver(String solverName) { return SOLVER_CLASSES.containsKey(solverName); } /** * Gets the set of valid solver names * @return set of valid solver name strings */ public static Set<String> getSolvers() { return SOLVER_CLASSES.keySet(); } private static AbstractDESSolver getSolver(String solverName) throws RuntimeException { // If the provided solver name doesn't exist in our map, it's an invalid // value that the programmer needs to correct. if(!checkValidSolver(solverName)) { throw new RuntimeException("Invalid Solver: \"" + solverName + "\""); } // If this solver has already been instantiated, retrieve it if(SOLVERS.containsKey(solverName)) { return SOLVERS.get(solverName); } // It hasn't been instantiated yet so we do so now try { SOLVERS.put(solverName, (AbstractDESSolver) SOLVER_CLASSES.get(solverName).newInstance()); } catch (InstantiationException | IllegalAccessException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Unable to instantiate " + solverName + " solver"); } // Retrieve the solver we just instantiated return SOLVERS.get(solverName); } private static SBMLinterpreter getInterpreter(String filepath) { SBMLReader reader = new SBMLReader(); File inputFile = new File(filepath); try { SBMLDocument doc = reader.readSBML(inputFile); System.out.println("Loaded SBML Document successfully!"); Model model = doc.getModel(); try { SBMLinterpreter interpreter = new SBMLinterpreter(model); System.out.println("Interpreted SBML Model successfully!"); return interpreter; } catch (ModelOverdeterminedException | SBMLException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error interpreting SBML Model..."); } } catch (IOException | XMLStreamException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Failed to load SBML document..."); } return null; } private static void testModel(Physiology physio, Path outputFile) { // Use all default parameters testModel(physio, outputFile, new HashMap()); } private static void testModel(Physiology physio, Path outputPath, Map<String,Double> inputs) { try { MultiTable solution = physio.run(inputs); PrintWriter writer; try { writer = new PrintWriter(outputPath.toString(), "UTF-8"); } catch (FileNotFoundException | UnsupportedEncodingException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Unable to open output file:" + outputPath); return; } System.out.println("Block 1: " + Arrays.toString(solution.getBlock(0).getColumnNames())); System.out.println("Block 2: " + Arrays.toString(solution.getBlock(1).getColumnNames())); int numRows = solution.getRowCount(); int numCols = solution.getColumnCount(); for(int colIdx = 0; colIdx < numCols; colIdx++) { writer.print(solution.getColumnIdentifier(colIdx)); if(colIdx < numCols -1) { writer.print(","); } } writer.println(); for(int rowIdx = 0; rowIdx < numRows; rowIdx++) { for(int colIdx = 0; colIdx < numCols; colIdx++) { writer.print(solution.getValueAt(rowIdx, colIdx)); if(colIdx < numCols -1) { writer.print(","); } } writer.println(); } writer.close(); System.out.println("Success!"); } catch (DerivativeException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error solving Model..."); } } private static void getPerfStats(Path modelPath, String solverName) { SBMLinterpreter interpreter = getInterpreter(modelPath.toString()); System.out.println("Interpreted SBML Model successfully!"); AbstractDESSolver solver = getSolver(solverName); // solver.setStepSize(stepSize); try { double[] defaultValues = interpreter.getInitialValues(); PrintWriter statWriter; try { statWriter = new PrintWriter("stats.csv", "UTF-8"); } catch (FileNotFoundException | UnsupportedEncodingException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); return; } statWriter.print("index,step_size (s),exec_time (ms)"); statWriter.println(); Random r = new Random(); for(int i=0; i < 100; i++) { System.out.println("Running iteration " + (i+1)); double[] initialVals = defaultValues.clone(); // Generate some random resistance values and initial parameters initialVals[7] = randValue(0.98, 2); initialVals[6] = randValue(0.13, 0.17); initialVals[26] = randValue(10, 80); initialVals[27] = randValue(2, 130); double stepSize; if(r.nextDouble() < 0.4) { stepSize = randValue(0.001, 0.1); } else { stepSize = randValue(0.001, 0.01); } solver.setStepSize(stepSize); long startTime = System.nanoTime(); solver.solve(interpreter, initialVals, 0, 2); long endTime = System.nanoTime(); statWriter.print(i + "," + stepSize + "," + ((endTime-startTime)/1000000.0)); statWriter.println(); } statWriter.close(); System.out.println("Success!"); } catch (DerivativeException ex) { Logger.getLogger(Physiology.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error solving Model..."); } } public static double randValue(double rangeMin, double rangeMax) { Random r = new Random(); return rangeMin + (rangeMax - rangeMin) * r.nextDouble(); } public static void main(String [] args) throws DerivativeException { Map<String,Double> inputs = new HashMap(); // inputs.put("R_sys", 1.814); inputs.put("E_es_lvf", 1.034); // inputs.put("B", 150.0); // inputs.put("C", 0.25); // inputs.put("period", 0.5); // inputs.put("inactive_t0", 1.0); // inputs.put("inactive_t1", 1.5); Physiology physio = new Physiology("circulation/Smith2004_CVS_human.xml", "runge_kutta", 0.01, 2, 1.0); // Physiology physio = new Physiology("circulation/Fink2008_VentricularActionPotential.xml", "runge_kutta", 0.01, 4); // Physiology physio = new Physiology("circulation/Iyer2007_Arrhythmia_CardiacDeath.xml", "adams_bashforth", 0.01, 4); Physiology.testModel(physio, Paths.get("too_weak.csv"), inputs); // try { // // Run with all default parameters // MultiTable results = physio.run(new HashMap()); // Block mainBlock = results.getBlock(0); // int numRows = mainBlock.getRowCount(); // for(String param : mainBlock.getIdentifiers()) { // System.out.println("Param: \"" + param + "\": " + mainBlock.getColumn(param).getValue(numRows-1)); // } catch (DerivativeException ex) { // System.out.println("Error solving the differential equation"); } }
package org.nuxeo.common.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * TODO Please document me. * * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> */ public class TextTemplate { private static final Pattern PATTERN = Pattern.compile("\\$\\{([a-zA-Z_0-9\\-\\.]+)\\}"); private final Properties vars; private boolean trim = false; public boolean isTrim() { return trim; } /** * Set to true in order to trim invisible characters (spaces) from values * @param trim */ public void setTrim(boolean trim) { this.trim = trim; } public TextTemplate() { vars = new Properties(); } /** * @deprecated prefer use of {@link #TextTemplate(Properties)} */ public TextTemplate(Map<String, String> vars) { this.vars = new Properties(); this.vars.putAll(vars); } /** * @param vars Properties containing keys and values for template processing */ public TextTemplate(Properties vars) { this.vars = vars; } /** * @deprecated prefer use of {@link #getVariables()} then {@link Properties} * .load() */ public void setVariables(Map<String, String> vars) { this.vars.putAll(vars); } public void setVariable(String name, String value) { vars.setProperty(name, value); } public String getVariable(String name) { return vars.getProperty(name); } public Properties getVariables() { return vars; } public String process(CharSequence text) { Matcher m = PATTERN.matcher(text); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String value = getVariable(var); if (value != null) { if (trim) { value = value.trim(); } // Allow use of backslash and dollars characters String valueL = Matcher.quoteReplacement(value); m.appendReplacement(sb, valueL); } } m.appendTail(sb); return sb.toString(); } public String process(InputStream in) throws IOException { String text = FileUtils.read(in); return process(text); } public void process(InputStream in, OutputStream out) throws IOException { String text = FileUtils.read(in); out.write(process(text).getBytes()); } /** * Recursive call {@link #process(InputStream, OutputStream)} on each file * from "in" directory to "out" directory * * @param in Directory to read files from * @param out Directory to write files to */ public void processDirectory(File in, File out) throws FileNotFoundException, IOException { if (in.isFile()) { if (out.isDirectory()) { out = new File(out, in.getName()); } FileInputStream is = null; FileOutputStream os = new FileOutputStream(out); try { is = new FileInputStream(in); process(is, os); } finally { if (is != null) { is.close(); } os.close(); } } else if (in.isDirectory()) { if (!out.exists()) { // allow renaming destination directory out.mkdirs(); } else if (!out.getName().equals(in.getName())) { // allow copy over existing arborescence out = new File(out, in.getName()); out.mkdir(); } for (File file : in.listFiles()) { processDirectory(file, out); } } } }
package de.ptb.epics.eve.editor.views.axeschannelsview.classiccomposite.channels; import org.eclipse.jface.viewers.ColumnLabelProvider; import de.ptb.epics.eve.data.ComparisonTypes; import de.ptb.epics.eve.data.measuringstation.event.MonitorEvent; import de.ptb.epics.eve.data.scandescription.Channel; import de.ptb.epics.eve.data.scandescription.ControlEvent; import de.ptb.epics.eve.data.scandescription.channelmode.ChannelModes; /** * @author Marcus Michalsky * @since 1.34 */ public class ParametersColumnLabelProvider extends ColumnLabelProvider { private static final String DASH = Character.toString('\u2014'); private static final String STOPPED_BY = Character.toString('\u21E5'); private static final String REDO = Character.toString('\u27F2'); private static final String SIGMA = Character.toString('\u03C3'); private static final String LESS_OR_EQUAL = Character.toString('\u2264'); private static final String GREATER_OR_EQUAL = Character.toString('\u2267'); /** * {@inheritDoc} */ @Override public String getText(Object element) { Channel channel = (Channel)element; if (channel.getScanModule().isUsedAsNormalizeChannel(channel)) { return DASH; } switch (channel.getChannelMode()) { case INTERVAL: StringBuilder sbInterval = new StringBuilder(); sbInterval.append(channel.getTriggerInterval() + "s"); if (channel.getStoppedBy() != null) { sbInterval.append(" " + STOPPED_BY + " " + channel.getStoppedBy().getName()); } return sbInterval.toString(); case STANDARD: StringBuilder sbStandard = new StringBuilder(); sbStandard.append("n = " + channel.getAverageCount()); if (channel.getMaxDeviation() != null) { sbStandard.append(", " + SIGMA + " " + LESS_OR_EQUAL + " " + channel.getMaxDeviation() + " %"); } if (channel.getMinimum() != null) { sbStandard.append(", x " + GREATER_OR_EQUAL + " " + channel.getMinimum()); } if (channel.getMaxAttempts() != null) { sbStandard.append(", a " + LESS_OR_EQUAL + " " + channel.getMaxAttempts()); } if (!channel.getRedoEvents().isEmpty()) { sbStandard.append(", " + REDO); } return sbStandard.toString(); default: return DASH; } } /** * {@inheritDoc} */ @Override public String getToolTipText(Object element) { Channel channel = (Channel)element; if (channel.getChannelMode().equals(ChannelModes.INTERVAL)) { return null; } StringBuilder sb = new StringBuilder(); for (ControlEvent controlEvent : channel.getRedoEvents()) { sb.append("Redo Event: " + controlEvent.getEvent().getName()); if (controlEvent.getEvent() instanceof MonitorEvent) { sb.append(", Operator: " + ComparisonTypes.typeToString( controlEvent.getLimit().getComparison())); } if (controlEvent.getEvent() instanceof MonitorEvent) { sb.append(", Limit: " + controlEvent.getLimit().getValue()); } sb.append("\n"); } if (sb.toString().isEmpty()) { return null; } // cut last line break return sb.toString().substring(0, sb.toString().length()-1); } }
package org.suporma.gears; import java.util.AbstractCollection; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Predicate; public class HashedLinkedDeque<T> extends AbstractCollection<T> implements Deque<T> { private final Map<T, EquivalenceList> nodeMap; private Node front, back; private int size = 0; private class Node { private Node prev, next; private EquivalenceNode equivalenceNode; private T val; public Node(T val) { this.val = val; this.prev = null; this.next = null; } } private class EquivalenceNode { private final Node node; private EquivalenceNode prev, next; public EquivalenceNode(Node node) { this.node = node; this.prev = null; this.next = null; } } private class EquivalenceList { private EquivalenceNode front, back; private int size; public EquivalenceList() { front = new EquivalenceNode(null); back = new EquivalenceNode(null); front.next = back; back.prev = front; size = 0; } public void shift(Node node) { EquivalenceNode simpleNode = new EquivalenceNode(node); simpleNode.next = front.next; simpleNode.prev = front; front.next = simpleNode; simpleNode.next.prev = simpleNode; ++size; } public Node unshift() { EquivalenceNode node = front.next; EquivalenceNode next = node.next; front.next = next; next.prev = front; --size; return node.node; } public void push(Node node) { EquivalenceNode simpleNode = new EquivalenceNode(node); simpleNode.next = back; simpleNode.prev = back.prev; back.prev = simpleNode; simpleNode.prev.next = simpleNode; ++size; } public Node pop() { EquivalenceNode node = back.prev; EquivalenceNode prev = node.prev; back.prev = prev; prev.next = back; --size; return node.node; } public Node remove(Node node) { EquivalenceNode equivalenceNode = node.equivalenceNode; EquivalenceNode prev = equivalenceNode.prev; EquivalenceNode next = equivalenceNode.next; prev.next = next; next.prev = prev; --size; return equivalenceNode.node; } public int size() { return size; } public Node first() { return front.next.node; } public Node last() { return back.prev.node; } } public HashedLinkedDeque() { nodeMap = new HashMap<>(); front = new Node(null); back = new Node(null); front.next = back; back.prev = front; size = 0; } public int count(T val) { return nodeMap.get(val).size(); } private void removeNode(Node node) { Node prev = node.prev; Node next = node.next; prev.next = next; next.prev = prev; EquivalenceList eqList = nodeMap.get(node.val); eqList.remove(node); if (eqList.size() == 0) { nodeMap.remove(node.val); } } public boolean removeIf(Predicate<? super T> filter) { boolean elementsRemoved = false; Node node = front.next; while (node != back) { if (filter.test(node.val)) { removeNode(node); --size; elementsRemoved = true; } node = node.next; } return elementsRemoved; } public int size() { return size; } private class HashedLinkedIterator implements Iterator<T> { private Node node; private int index; public HashedLinkedIterator() { node = front; index = -1; } public boolean hasNext() { return node.next != back; } public T next() { T val = node.val; node = node.next; ++index; return val; } public boolean hasPrevious() { return node != front && node != front.next; } public T previous() { node = node.prev; return node.val; } public int nextIndex() { return index + 1; } public int previousIndex() { return index - 1; } public void remove() { removeNode(node); } public void set(T e) { node.val = e; } } public void addFirst(T e) { Node node = new Node(e); node.prev = front; node.next = front.next; front.next = node; node.next.prev = node; EquivalenceList list = nodeMap.computeIfAbsent(e, (val) -> new EquivalenceList()); list.shift(node); } public void addLast(T e) { Node node = new Node(e); node.next = back; node.prev = back.prev; back.prev = node; node.prev.next = node; EquivalenceList list = nodeMap.computeIfAbsent(e, (val) -> new EquivalenceList()); list.push(node); } public boolean offerFirst(T e) { addFirst(e); return true; } public boolean offerLast(T e) { addLast(e); return true; } public T removeFirst() { if (size > 0) { return pollFirst(); } else { throw new NoSuchElementException(); } } public T removeLast() { if (size > 0) { return pollLast(); } else { throw new NoSuchElementException(); } } @Override public T pollFirst() { if (size > 0) { Node node = front.next; removeNode(node); return node.val; } else { return null; } } @Override public T pollLast() { if (size > 0) { Node node = front.next; removeNode(node); return node.val; } else { return null; } } @Override public T getFirst() { if (size > 0) { return front.next.val; } else { throw new NoSuchElementException(); } } @Override public T getLast() { if (size > 0) { return back.prev.val; } else { throw new NoSuchElementException(); } } @Override public T peekFirst() { if (size > 0) { return front.next.val; } else { return null; } } @Override public T peekLast() { if (size > 0) { return back.prev.val; } else { return null; } } @Override public boolean removeFirstOccurrence(Object o) { EquivalenceList eqList = nodeMap.get(o); if (eqList != null) { Node node = eqList.first(); removeNode(node); return true; } else { return false; } } @Override public boolean removeLastOccurrence(Object o) { EquivalenceList eqList = nodeMap.get(o); if (eqList != null) { Node node = eqList.last(); removeNode(node); return true; } else { return false; } } @Override public boolean offer(T e) { return offerLast(e); } @Override public T remove() { return removeFirst(); } @Override public T poll() { return pollFirst(); } @Override public T element() { return getFirst(); } @Override public T peek() { return peekFirst(); } @Override public void push(T e) { addFirst(e); } @Override public T pop() { return removeFirst(); } @Override public Iterator<T> descendingIterator() { // TODO Auto-generated method stub return null; } @Override public Iterator<T> iterator() { return new HashedLinkedIterator(); } }
package permafrost.tundra.lang; import com.wm.data.IData; import com.wm.data.IDataCursor; import com.wm.data.IDataFactory; import com.wm.data.IDataUtil; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.io.StreamHelper; import permafrost.tundra.math.BigDecimalHelper; import permafrost.tundra.math.BigIntegerHelper; import permafrost.tundra.time.DateTimeHelper; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A collection of convenience methods for working with String objects. */ public class StringHelper { /** * Disallow instantiation of this class. */ private StringHelper() {} /** * Normalizes the given byte[] as a string. * * @param bytes A byte[] to be converted to a string. * @return A string representation of the given byte[]. */ public static String normalize(byte[] bytes) { return normalize(bytes, CharsetHelper.DEFAULT_CHARSET); } /** * Converts the given byte[] as a string. * * @param bytes A byte[] to be converted to a string. * @param charsetName The character set name to use. * @return A string representation of the given byte[]. */ public static String normalize(byte[] bytes, String charsetName) { return normalize(bytes, CharsetHelper.normalize(charsetName)); } /** * Converts the given byte[] as a string. * * @param bytes A byte[] to be converted to a string. * @param charset The character set to use. * @return A string representation of the given byte[]. */ public static String normalize(byte[] bytes, Charset charset) { if (bytes == null) return null; return new String(bytes, CharsetHelper.normalize(charset)); } /** * Converts the given java.io.InputStream as a String, and closes the stream. * * @param inputStream A java.io.InputStream to be converted to a string. * @return A string representation of the given java.io.InputStream. * @throws IOException If the given encoding is unsupported, or if there is an error reading from the * java.io.InputStream. */ public static String normalize(InputStream inputStream) throws IOException { return normalize(inputStream, CharsetHelper.DEFAULT_CHARSET); } /** * Converts the given java.io.InputStream as a String, and closes the stream. * * @param inputStream A java.io.InputStream to be converted to a string. * @param charsetName The character set to use. * @return A string representation of the given java.io.InputStream. * @throws IOException If the given encoding is unsupported, or if there is an error reading from the * java.io.InputStream. */ public static String normalize(InputStream inputStream, String charsetName) throws IOException { return normalize(inputStream, CharsetHelper.normalize(charsetName)); } /** * Converts the given java.io.InputStream as a String, and closes the stream. * * @param inputStream A java.io.InputStream to be converted to a string. * @param charset The character set to use. * @return A string representation of the given java.io.InputStream. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String normalize(InputStream inputStream, Charset charset) throws IOException { if (inputStream == null) return null; Writer writer = new StringWriter(); StreamHelper.copy(new InputStreamReader(StreamHelper.normalize(inputStream), CharsetHelper.normalize(charset)), writer); return writer.toString(); } /** * Normalizes the given String, byte[], or java.io.InputStream object to a String. * * @param object The object to be normalized to a string. * @return A string representation of the given object. * @throws IOException If the given encoding is unsupported, or if there is an error reading from the * java.io.InputStream. */ public static String normalize(Object object) throws IOException { return normalize(object, CharsetHelper.DEFAULT_CHARSET); } /** * Normalizes the given String, byte[], or java.io.InputStream object to a String. * * @param object The object to be normalized to a string. * @param charsetName The character set to use. * @return A string representation of the given object. * @throws IOException If the given encoding is unsupported, or if there is an error reading from the * java.io.InputStream. */ public static String normalize(Object object, String charsetName) throws IOException { return normalize(object, CharsetHelper.normalize(charsetName)); } /** * Normalizes the given String, byte[], or java.io.InputStream object to a String. * * @param object The object to be normalized to a string. * @param charset The character set to use. * @return A string representation of the given object. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String normalize(Object object, Charset charset) throws IOException { if (object == null) return null; String output; if (object instanceof byte[]) { output = normalize((byte[])object, charset); } else if (object instanceof String) { output = (String)object; } else if (object instanceof InputStream) { output = normalize((InputStream)object, charset); } else { throw new IllegalArgumentException("object must be a String, byte[], or java.io.InputStream"); } return output; } /** * Normalizes the list of String, byte[], or InputStream to a String list. * * @param array The array of objects to be normalized. * @param charset The character set to use. * @return The resulting String list representing the given array. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String[] normalize(Object[] array, Charset charset) throws IOException { if (array == null) return null; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = normalize(array[i], charset); } return output; } /** * Normalizes the list of String, byte[], or InputStream to a String list. * * @param array The array of objects to be normalized. * @param charsetName The character set to use. * @return The resulting String list representing the given array. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String[] normalize(Object[] array, String charsetName) throws IOException { return normalize(array, CharsetHelper.normalize(charsetName)); } /** * Returns a substring starting at the given index for the given length. * * @param input The string to be sliced. * @param index The zero-based starting index of the slice. * @param length The length in characters of the slice. * @return The resulting substring. */ public static String slice(String input, int index, int length) { if (input == null || input.equals("")) return input; String output = ""; int inputLength = input.length(), endIndex = 0; // support reverse length if (length < 0) { // support reverse indexing if (index < 0) { endIndex = index + inputLength + 1; } else { if (index >= inputLength) index = inputLength - 1; endIndex = index + 1; } index = endIndex + length; } else { // support reverse indexing if (index < 0) index += inputLength; endIndex = index + length; } if (index < inputLength && endIndex > 0) { if (index < 0) index = 0; if (endIndex > inputLength) endIndex = inputLength; output = input.substring(index, endIndex); } return output; } /** * Returns an empty string if given string is null, otherwise returns the given string. * * @param string The string to blankify. * @return An empty string if the given string is null, otherwise the given string. */ public static String blankify(String string) { if (string == null) string = ""; return string; } /** * Capitalizes the first character in either the first word or all words in the given string. * * @param string The string to capitalize. * @param firstWordOnly Whether only the first word should be capitalized, or all words. * @return The capitalized string. */ public static String capitalize(String string, boolean firstWordOnly) { if (string == null) return null; char[] characters = string.toCharArray(); boolean capitalize = true; for (int i = 0; i < characters.length; i++) { char character = characters[i]; if (Character.isWhitespace(character)) { capitalize = true; } else if (capitalize) { characters[i] = Character.toTitleCase(character); capitalize = false; if (firstWordOnly) break; } } return new String(characters); } /** * Returns the given string as a list of characters. * * @param string The string. * @return The characters in the given string. */ public static Character[] characters(String string) { if (string == null) return null; char[] chars = string.toCharArray(); Character[] characters = new Character[chars.length]; for (int i = 0; i < chars.length; i++) { characters[i] = chars[i]; } return characters; } /** * Returns the given string with leading and trailing whitespace removed. * * @param string The string to be trimmed. * @return The trimmed string. */ public static String trim(String string) { String output = null; if (string != null) output = string.trim(); return output; } /** * Returns the length or number of characters of the string. * * @param string The string to be measured. * @return The length of the given string. */ public static int length(String string) { int length = 0; if (string != null) length = string.length(); return length; } /** * Returns all the groups captured by the given regular expression pattern in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return The capture groups from the regular expression pattern match against the string. */ public static IData[] capture(String string, String pattern) { if (string == null || pattern == null) return null; List<IData> captures = new ArrayList<IData>(); Pattern regex = Pattern.compile(pattern); Matcher matcher = regex.matcher(string); while (matcher.find()) { int count = matcher.groupCount(); List<IData> groups = new ArrayList<IData>(count); for (int i = 0; i <= count; i++) { int index = matcher.start(i); int length = matcher.end(i) - index; String content = matcher.group(i); boolean captured = index >= 0; IData group = IDataFactory.create(); IDataCursor groupCursor = group.getCursor(); IDataUtil.put(groupCursor, "captured?", "" + captured); if (captured) { IDataUtil.put(groupCursor, "index", "" + index); IDataUtil.put(groupCursor, "length", "" + length); IDataUtil.put(groupCursor, "content", content); } groupCursor.destroy(); groups.add(group); } IData capture = IDataFactory.create(); IDataCursor captureCursor = capture.getCursor(); IDataUtil.put(captureCursor, "groups", groups.toArray(new IData[groups.size()])); IDataUtil.put(captureCursor, "groups.length", "" + groups.size()); captureCursor.destroy(); captures.add(capture); } return captures.toArray(new IData[captures.size()]); } /** * Returns true if the given regular expression pattern is found anywhere in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return True if the regular expression pattern was found anywhere in the given string. */ public static boolean find(String string, String pattern) { return find(string, pattern, false); } * /** Returns true if the given pattern is found anywhere in the given string. * * @param string The string to match against the regular expression. * @param pattern The literal of regular expression pattern. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return True if the pattern was found anywhere in the given string. */ public static boolean find(String string, String pattern, boolean literal) { boolean found = false; if (string != null && pattern != null) { if (literal) { found = string.contains(pattern); } else { Pattern regex = Pattern.compile(pattern); Matcher matcher = regex.matcher(string); found = matcher.find(); } } return found; } /** * Returns true if the given regular expression pattern matches the entirety of the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return True if the regular expression matches the entirety of the given string. */ public static boolean match(String string, String pattern) { return match(string, pattern, false); } /** * Returns true if the pattern matches the entirety of the given string. * * @param string The string to match against the regular expression. * @param pattern The literal or regular expression pattern. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return True if the pattern matches the entirety of the given string. */ public static boolean match(String string, String pattern, boolean literal) { boolean match = false; if (string != null && pattern != null) { if (literal) { match = string.equals(pattern); } else { match = string.matches(pattern); } } return match; } /** * Removes all occurrences of the given regular expression in the given string. * * @param string The string to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @return The given string with all occurrences of the given pattern removed. */ public static String remove(String string, String pattern) { return remove(string, pattern, false); } /** * Removes either the first or all occurrences of the given regular expression in the given string. * * @param string The string to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @param firstOnly If true, only the first occurrence is removed, otherwise all occurrences are removed. * @return The given string with either the first or all occurrences of the given pattern removed. */ public static String remove(String string, String pattern, boolean firstOnly) { return replace(string, pattern, "", true, firstOnly); } /** * Replaces all occurrences of the given regular expression in the given string with the given replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param literal Whether the replacement string is literal and therefore requires quoting. * @return The replaced string. */ public static String replace(String string, String pattern, String replacement, boolean literal) { return replace(string, pattern, replacement, literal, false); } /** * Replaces either the first or all occurrences of the given regular expression in the given string with the given * replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param literal Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The replaced string. */ public static String replace(String string, String pattern, String replacement, boolean literal, boolean firstOnly) { String output = string; if (string != null && pattern != null && replacement != null) { if (literal) replacement = Matcher.quoteReplacement(replacement); Matcher matcher = Pattern.compile(pattern).matcher(string); if (firstOnly) { output = matcher.replaceFirst(replacement); } else { output = matcher.replaceAll(replacement); } } return output; } /** * Splits a string around each match of the given regular expression pattern. * * @param string The string to be split. * @param pattern The regular expression pattern to split around. * @return The array of strings computed by splitting the given string around matches of this pattern. */ public static String[] split(String string, String pattern) { return split(string, pattern, false); } /** * Splits a string around each match of the given pattern. * * @param string The string to be split. * @param pattern The literal or regular expression pattern to split around. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return The array of strings computed by splitting the given string around matches of this pattern. */ public static String[] split(String string, String pattern, boolean literal) { String[] output = null; if (string != null && pattern != null) { if (literal) pattern = quote(pattern); output = Pattern.compile(pattern).split(string); } else if (string != null) { output = new String[1]; output[0] = string; } return output; } /** * Returns all the lines in the given string as an array. * * @param string The string to be split into lines. * @return The array of lines from the given string. */ public static String[] lines(String string) { return split(string, "\n"); } /** * Trims the given string of leading and trailing whitespace, and optionally replaces runs of whitespace characters * with a single space character. * * @param string The string to be squeezed. * @param internal Whether runs of whitespace characters should be replaced with a single space character. * @return The squeezed string. */ public static String squeeze(String string, boolean internal) { if (string == null) return null; string = string.trim(); if (internal) string = replace(string, "\\s+", " ", false); return string.equals("") ? null : string; } /** * Trims the given string of leading and trailing whitespace, and replaces runs of whitespace characters with a * single space character. * * @param string The string to be squeezed. * @return The squeezed string. */ public static String squeeze(String string) { return squeeze(string, true); } /** * Returns a literal regular expression pattern for the given string. * * @param string The string to quote. * @return A regular expression pattern which literally matches the given string. */ public static String quote(String string) { if (string == null) return null; return Pattern.quote(string); } /** * Returns a regular expression pattern that matches any of the values in the given string list. * * @param array The list of strings to be matched. * @return A regular expression which literally matches any of the given strings. */ public static String quote(String[] array) { if (array == null) return null; int last = array.length - 1; StringBuilder builder = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (i == 0) builder.append("("); builder.append(quote(array[i])); if (i < last) builder.append("|"); if (i == last) builder.append(")"); } return builder.toString(); } /** * Pads a string with the given character to the given length. * * @param string The string to pad. * @param length The desired length of the string. If less than 0 the string is padded right to left, otherwise * it is padded from left to right. * @param character The character to pad the string with. * @return The padded string. */ public static String pad(String string, int length, char character) { if (string == null) string = ""; boolean left = length >= 0; if (length < 0) length = length * -1; if (string.length() >= length) return string; StringBuilder builder = new StringBuilder(length); if (!left) builder.append(string); for (int i = string.length(); i < length; i++) { builder.append(character); } if (left) builder.append(string); return builder.toString(); } /** * Compares two strings lexicographically. * * @param string1 The first string to compare. * @param string2 The second string to compare. * @param caseInsensitive Whether the comparison should be case insensitive. * @return Less than 0 if the first string is less than the second string, equal to 0 if the two strings are equal, * or greater than 0 if the first string is greater than the second string. */ public static int compare(String string1, String string2, boolean caseInsensitive) { if (string1 == null && string2 == null) return 0; if (string1 == null) return -1; if (string2 == null) return 1; if (caseInsensitive) { return string1.compareToIgnoreCase(string2); } else { return string1.compareTo(string2); } } public static String format(Locale locale, String pattern, IData[] arguments, IData record) { List<Object> args = new ArrayList<Object>(arguments == null? 0 : arguments.length); if (arguments != null) { for (IData argument : arguments) { if (argument != null) { IDataCursor cursor = argument.getCursor(); String key = IDataUtil.getString(cursor, "key"); Object value = IDataUtil.get(cursor, "value"); String type = IDataUtil.getString(cursor, "type"); String argPattern = IDataUtil.getString(cursor, "pattern"); cursor.destroy(); if (key != null && value == null) value = IDataHelper.get(record, key); if (value != null) { if (type == null || type.equalsIgnoreCase("string")) { value = value.toString(); } else if (type.equalsIgnoreCase("integer")) { value = BigIntegerHelper.normalize(value); } else if (type.equalsIgnoreCase("decimal")) { value = BigDecimalHelper.normalize(value); } else if (type.equalsIgnoreCase("datetime")) { value = DateTimeHelper.normalize(value, argPattern); } } args.add(value); } } } return String.format(locale, pattern, args.toArray(new Object[args.size()])); } public static String format(Locale locale, String pattern, IData[] arguments, String recordSeparator, IData ... records) { if (records == null) return null; StringBuilder builder = new StringBuilder(); for (IData record : records) { builder.append(format(locale, pattern, arguments, record)); if (recordSeparator != null) builder.append(recordSeparator); } return builder.toString(); } }
package controllers.api; import java.util.Date; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import models.FeedSource; import models.FeedVersion; import models.JsonViews; import models.Model; import models.Note; import models.Note.NoteType; import models.User.ProjectPermissions; import models.User; import controllers.Secured; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; @Security.Authenticated(Secured.class) public class NoteController extends Controller { private static JsonManager<Note> json = new JsonManager<Note>(Note.class, JsonViews.UserInterface.class); public static Result getAll () throws JsonProcessingException { User currentUser = User.getUserByUsername(session("username")); String typeStr = request().getQueryString("type"); String objectId = request().getQueryString("objectId"); if (typeStr == null || objectId == null) { return badRequest("Please specify objectId and type"); } NoteType type; try { type = NoteType.valueOf(typeStr); } catch (IllegalArgumentException e) { return badRequest("Please specify a valid type"); } Model model; switch (type) { case FEED_SOURCE: model = FeedSource.get(objectId); break; case FEED_VERSION: model = FeedVersion.get(objectId); break; default: // this shouldn't ever happen, but Java requires that every case be covered somehow so model can't be used uninitialized return badRequest("Unsupported type for notes"); } FeedSource s; if (model instanceof FeedSource) { s = (FeedSource) model; } else { s = ((FeedVersion) model).getFeedSource(); } if (currentUser.admin || currentUser.equals(s.getUser()) || currentUser.hasReadAccess(s.id)) { return ok(json.write(model.getNotes())).as("application/json"); } else { return unauthorized(); } } public static Result create () throws JsonProcessingException { User currentUser = User.getUserByUsername(session("username")); JsonNode params = request().body().asJson(); String typeStr = params.get("type").asText(); String objectId = params.get("objectId").asText(); if (typeStr == null || objectId == null) { return badRequest("Please specify objectId and type"); } NoteType type; try { type = NoteType.valueOf(typeStr); } catch (IllegalArgumentException e) { return badRequest("Please specify a valid type"); } Model model; switch (type) { case FEED_SOURCE: model = FeedSource.get(objectId); break; case FEED_VERSION: model = FeedVersion.get(objectId); break; default: // this shouldn't ever happen, but Java requires that every case be covered somehow so model can't be used uninitialized return badRequest("Unsupported type for notes"); } FeedSource s; if (model instanceof FeedSource) { s = (FeedSource) model; } else { s = ((FeedVersion) model).getFeedSource(); } if (currentUser.admin || currentUser.equals(s.getUser()) || currentUser.hasWriteAccess(s.id)) { Note n = new Note(); n.note = params.get("note").asText(); // folks can't make comments as other folks n.userId = currentUser.id; n.date = new Date(); n.type = type; model.addNote(n); n.save(); model.save(); return ok(json.write(n)).as("application/json"); } else { return unauthorized(); } } }
package tigase.server.bosh; import tigase.xml.Element; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Describe class BoshSessionCache here. * * * Created: Mon Feb 25 23:54:57 2008 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class BoshSessionCache { private static final Logger log = Logger.getLogger("tigase.server.bosh.BoshSessionCache"); /** Field description */ public static final String DEF_ID = ""; /** Field description */ public static final String ROSTER_ID = "bosh-roster"; /** Field description */ public static final String RESOURCE_BIND_ID = "bosh-resource-bind"; /** Field description */ public static final String MESSAGE_ID = "bosh-message"; private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); /** * Cache elements stored by the Bosh client. The cache elements are grouped * by IDs. There can be any number of Elements under each ID. */ private Map<String, List<Element>> id_cache = null; /** * Cached time of the first message to/from some jid * to speedup message caching processing */ protected Map<String, Long> jid_msg_start = null; /** * Cached presence elements automaticaly stored by the Bosh component. * There is only 1 presence element stored for each JID which means the * cache stores the last presence element for each JID. */ private Map<String, Element> jid_presence = null; /** * Creates a new <code>BoshSessionCache</code> instance. * */ public BoshSessionCache() { id_cache = new LinkedHashMap<String, List<Element>>(); jid_presence = new LinkedHashMap<String, Element>(); jid_msg_start = new LinkedHashMap<String, Long>(); } /** * Method description * * * @param id * @param data */ public void add(String id, List<Element> data) { if (id == null) { id = DEF_ID; } List<Element> cached_data = id_cache.get(id); if (cached_data == null) { cached_data = new ArrayList<Element>(); id_cache.put(id, cached_data); } cached_data.addAll(data); if (log.isLoggable(Level.FINEST)) { log.finest("ADD, id = " + id + ", DATA: " + data.toString()); } } /** * Method description * * * @param message */ public void addFromMessage(Element message) { Element body = message.findChild("/message/body"); if (body == null) { return; } String jid = message.getAttribute("from"); addMsgBody(jid, "from", body); } /** * Method description * * * @param presence */ public void addPresence(Element presence) { String from = presence.getAttribute("from"); jid_presence.put(from, presence); if (log.isLoggable(Level.FINEST)) { log.finest("ADD_PRESENCE, from = " + from + ", PRESENCE: " + presence.toString()); } } /** * Method description * * * @param roster */ public void addRoster(Element roster) { add(ROSTER_ID, Arrays.asList(roster)); if (log.isLoggable(Level.FINEST)) { log.finest("ADD_ROSTER, ROSTER: " + roster.toString()); } } /** * Method description * * * @param message */ public void addToMessage(Element message) { Element body = message.findChild("/message/body"); if (body == null) { return; } String jid = message.getAttribute("to"); addMsgBody(jid, "to", body); } /** * Method description * * * @param id * * @return */ public List<Element> get(String id) { if (id == null) { id = DEF_ID; } List<Element> data = id_cache.get(id); if (log.isLoggable(Level.FINEST)) { log.finest("GET, id = " + id + ", DATA: " + data.toString()); } return data; } /** * Method description * * * @return */ public List<Element> getAll() { List<Element> result = new ArrayList<Element>(); for (List<Element> cache_data : id_cache.values()) { result.addAll(cache_data); } result.addAll(jid_presence.values()); if (log.isLoggable(Level.FINEST)) { log.finest("GET_ALL, DATA: " + result.toString()); } return result; } /** * Method description * * * @return */ public List<Element> getAllPresences() { return new ArrayList<Element>(jid_presence.values()); } /** * Method description * * * @param from * * @return */ public List<Element> getPresence(String... from) { List<Element> result = new ArrayList<Element>(); for (String f : from) { Element presence = jid_presence.get(f); if (presence != null) { result.add(presence); } } return result; } /** * Method description * * * @param id * * @return */ public List<Element> remove(String id) { if (id == null) { id = DEF_ID; } List<Element> data = id_cache.remove(id); if (log.isLoggable(Level.FINEST)) { log.finest("REMOVED, id = " + id + ", DATA: " + data.toString()); } return data; } /** * Method description * * * @param id * @param data */ public void set(String id, List<Element> data) { if (id == null) { id = DEF_ID; } List<Element> cached_data = new ArrayList<Element>(); id_cache.put(id, cached_data); cached_data.addAll(data); if (log.isLoggable(Level.FINEST)) { log.finest("SET, id = " + id + ", DATA: " + data.toString()); } } private void addMsgBody(String jid, String direction, Element body) { long start_time = getMsgStartTime(jid); List<Element> msg_history_l = id_cache.get(MESSAGE_ID + jid); Element msg_history = null; if (msg_history_l == null) { msg_history = createMessageHistory(jid); add(MESSAGE_ID + jid, Arrays.asList(msg_history)); } else { msg_history = msg_history_l.get(0); } long current_secs = (System.currentTimeMillis() / 1000) - start_time; msg_history.findChild("/iq/chat").addChild(new Element(direction, new Element[] { body }, new String[] { "secs" }, new String[] { "" + current_secs })); } private Element createMessageHistory(String jid) { String sdf_string = null; synchronized (sdf) { sdf_string = sdf.format(new Date()); } return new Element("iq", new Element[] { new Element("chat", new String[] { "xmlns", "with", "start" }, new String[] { "urn:xmpp:tmp:archive", jid, sdf_string }) }, new String[] { "type", "id" }, new String[] { "result", "" + System.currentTimeMillis() }); } private long getMsgStartTime(String jid) { Long start_time = jid_msg_start.get(jid); if (start_time == null) { start_time = (System.currentTimeMillis() / 1000); jid_msg_start.put(jid, start_time); } return start_time; } } //~ Formatted in Sun Code Convention
package wasdev.sample.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SimpleServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().print("Hello World!22222222222222222"); }
package ibis.ipl.impl.registry.central.server; import ibis.ipl.impl.IbisIdentifier; import ibis.ipl.impl.Location; import ibis.ipl.impl.registry.Connection; import ibis.ipl.impl.registry.central.Election; import ibis.ipl.impl.registry.central.ElectionSet; import ibis.ipl.impl.registry.central.Event; import ibis.ipl.impl.registry.central.EventList; import ibis.ipl.impl.registry.central.ListMemberSet; import ibis.ipl.impl.registry.central.Member; import ibis.ipl.impl.registry.central.MemberSet; import ibis.ipl.impl.registry.central.Protocol; import ibis.ipl.impl.registry.central.TreeMemberSet; import ibis.ipl.impl.registry.statistics.Statistics; import ibis.smartsockets.virtual.VirtualSocketFactory; import ibis.util.ThreadPool; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Formatter; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.log4j.Logger; final class Pool implements Runnable { public static final int BOOTSTRAP_LIST_SIZE = 25; // 10 seconds connect timeout private static final int CONNECT_TIMEOUT = 10000; private static final Logger logger = Logger.getLogger(Pool.class); private final VirtualSocketFactory socketFactory; // list of all joins, leaves, elections, etc. private final EventList events; private final boolean peerBootstrap; // private final boolean gossip; // private final boolean tree; private final long heartbeatInterval; private int currentEventTime; private int minEventTime; private final ElectionSet elections; private final MemberSet members; private final OndemandEventPusher pusher; private final String name; private final String ibisImplementationIdentifier; private final boolean closedWorld; // size of this pool (if closed world) private final int fixedSize; private final boolean printEvents; private final boolean printErrors; // statistics are only kept on the request of the user private final Statistics statistics; // simple statistics which are always kept, // so the server can print them if so requested private final int[] eventStats; private final Map<String, Integer> sequencers; private int nextID; private boolean ended = false; private boolean closed = false; Pool(String name, VirtualSocketFactory socketFactory, boolean peerBootstrap, long heartbeatInterval, long eventPushInterval, boolean gossip, long gossipInterval, boolean adaptGossipInterval, boolean tree, boolean closedWorld, int poolSize, boolean keepStatistics, long statisticsInterval, String ibisImplementationIdentifier, boolean printEvents, boolean printErrors) { this.name = name; this.socketFactory = socketFactory; this.peerBootstrap = peerBootstrap; this.heartbeatInterval = heartbeatInterval; // this.gossip = gossip; // this.tree = tree; this.closedWorld = closedWorld; this.fixedSize = poolSize; this.ibisImplementationIdentifier = ibisImplementationIdentifier; this.printEvents = printEvents; this.printErrors = printErrors; if (keepStatistics) { statistics = new Statistics(Protocol.OPCODE_NAMES); statistics.setID("server", name); statistics.startWriting(statisticsInterval); } else { ; statistics = null; } currentEventTime = 0; minEventTime = 0; nextID = 0; sequencers = new HashMap<String, Integer>(); events = new EventList(); eventStats = new int[Event.NR_OF_TYPES]; elections = new ElectionSet(); if (gossip) { members = new ListMemberSet(); new IterativeEventPusher(this, eventPushInterval, false, false); new RandomEventPusher(this, gossipInterval, adaptGossipInterval); } else if (tree) { members = new TreeMemberSet(); // on new event send to children in tree // FIXME: hack? also check for needed updates every second? new IterativeEventPusher(this, 1000, true, true); // once in a while forward to everyone new IterativeEventPusher(this, eventPushInterval, false, false); } else { // central members = new ListMemberSet(); new IterativeEventPusher(this, eventPushInterval, true, false); } pusher = new OndemandEventPusher(this); ThreadPool.createNew(this, "pool pinger thread"); } private static void print(String message) { DateFormat format = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.FRANCE); System.out.println(format.format(new Date(System.currentTimeMillis())) + " Central Registry: " + message); } synchronized int getEventTime() { return currentEventTime; } synchronized int getMinEventTime() { return minEventTime; } synchronized Event addEvent(int type, String description, IbisIdentifier... ibisses) { Event event = new Event(currentEventTime, type, description, ibisses); logger.debug("adding new event: " + event); events.add(event); eventStats[type]++; currentEventTime++; notifyAll(); return event; } synchronized void waitForEventTime(int time, long timeout) { long deadline = System.currentTimeMillis() + timeout; if (timeout == 0) { deadline = Long.MAX_VALUE; } while (getEventTime() < time) { if (hasEnded()) { return; } long currentTime = System.currentTimeMillis(); if (currentTime >= deadline) { return; } try { wait(deadline - currentTime); } catch (InterruptedException e) { // IGNORE } } } synchronized int getSize() { return members.size(); } int getFixedSize() { return fixedSize; } public boolean isClosedWorld() { return closedWorld; } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#ended() */ synchronized boolean hasEnded() { return ended; } synchronized boolean isClosed() { return closed; } synchronized void end() { ended = true; pusher.enqueue(null); if (statistics != null) { statistics.write(); statistics.end(); } } public void saveStatistics() { if (statistics != null) { statistics.write(); } } String getName() { return name; } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#join(byte[], byte[], * ibis.ipl.impl.Location) */ synchronized Member join(byte[] implementationData, byte[] clientAddress, Location location, String ibisImplementationIdentifier) throws IOException { if (hasEnded()) { throw new IOException("Pool already ended"); } if (isClosed()) { throw new IOException("Closed-World Pool already closed"); } if (!ibisImplementationIdentifier.equals(this.ibisImplementationIdentifier)) { throw new IOException("Ibis implementation " + ibisImplementationIdentifier + " does not match pool's Ibis implementation: " + this.ibisImplementationIdentifier); } logger.debug("ibis version: " + ibisImplementationIdentifier); String id = Integer.toString(nextID); nextID++; IbisIdentifier identifier = new IbisIdentifier(id, implementationData, clientAddress, location, name); Event event = addEvent(Event.JOIN, null, identifier); Member member = new Member(identifier, event); member.setCurrentTime(getMinEventTime()); member.updateLastSeenTime(); members.add(member); if (logger.isDebugEnabled()) { logger.debug("members now: " + members); } if (statistics != null) { statistics.newPoolSize(members.size()); } if (printEvents) { print(identifier + " joined pool \"" + name + "\" now " + members.size() + " members"); } if (closedWorld && nextID >= fixedSize) { closed = true; if (printEvents) { print("pool \"" + name + "\" now closed"); } addEvent(Event.POOL_CLOSED, null, new IbisIdentifier[0]); } return member; } void writeBootstrapList(DataOutputStream out) throws IOException { if (!peerBootstrap) { // send a list containing 0 members. It is not used anyway out.writeInt(0); return; } Member[] peers = getRandomMembers(BOOTSTRAP_LIST_SIZE); out.writeInt(peers.length); for (Member member : peers) { member.getIbis().writeTo(out); } } public void writeState(DataOutputStream out, int joinTime) throws IOException { ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(arrayOut); // create byte array of data synchronized (this) { dataOut.writeInt(currentEventTime); members.writeTo(dataOut); elections.writeTo(dataOut); Event[] signals = events.getSignalEvents(joinTime, currentEventTime); dataOut.writeInt(signals.length); for (Event event : signals) { event.writeTo(dataOut); } dataOut.writeBoolean(closed); } dataOut.flush(); byte[] bytes = arrayOut.toByteArray(); out.writeInt(bytes.length); out.write(bytes); logger.debug("pool state size = " + bytes.length); } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#leave(ibis.ipl.impl.IbisIdentifier) */ synchronized void leave(IbisIdentifier identifier) throws Exception { if (members.remove(identifier) == null) { logger.error("unknown ibis " + identifier + " tried to leave"); throw new Exception("ibis unknown: " + identifier); } if (printEvents) { print(identifier + " left pool \"" + name + "\" now " + members.size() + " members"); } addEvent(Event.LEAVE, null, identifier); if (statistics != null) { statistics.newPoolSize(members.size()); } Election[] deadElections = elections.getElectionsWonBy(identifier); for (Election election : deadElections) { addEvent(Event.UN_ELECT, election.getName(), election.getWinner()); if (statistics != null) { statistics.electionEvent(); } } if (members.size() == 0) { end(); if (printEvents) { print("pool \"" + name + "\" ended"); } else { logger.info("Central Registry: " + "pool \"" + name + "\" ended"); } notifyAll(); } } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#dead(ibis.ipl.impl.IbisIdentifier) */ synchronized void dead(IbisIdentifier identifier, Exception exception) { Member member = members.remove(identifier); if (member == null) { // member removed already return; } if (printEvents) { if (printErrors) { print(identifier + " died in pool \"" + name + "\" now " + members.size() + " members, caused by:"); exception.printStackTrace(System.out); } else { print(identifier + " died in pool \"" + name + "\" now " + members.size() + " members"); } } addEvent(Event.DIED, null, identifier); if (statistics != null) { statistics.newPoolSize(members.size()); } Election[] deadElections = elections.getElectionsWonBy(identifier); for (Election election : deadElections) { addEvent(Event.UN_ELECT, election.getName(), election.getWinner()); if (statistics != null) { statistics.electionEvent(); } elections.remove(election.getName()); } if (members.size() == 0) { end(); if (printEvents) { print("pool " + name + " ended"); } else { logger.info("Central Registry: " + "pool \"" + name + "\" ended"); } notifyAll(); } pusher.enqueue(member); } synchronized Event[] getEvents(int startTime) { return events.getList(startTime); } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#elect(java.lang.String, * ibis.ipl.impl.IbisIdentifier) */ synchronized IbisIdentifier elect(String electionName, IbisIdentifier candidate) { Election election = elections.get(electionName); if (election == null) { // Do the election now. The caller WINS! :) Event event = addEvent(Event.ELECT, electionName, candidate); if (statistics != null) { statistics.electionEvent(); } election = new Election(event); elections.put(election); if (printEvents) { print(candidate + " won election \"" + electionName + "\" in pool \"" + name + "\""); } } return election.getWinner(); } synchronized long getSequenceNumber(String name) { Integer currentValue = sequencers.get(name); if (currentValue == null) { currentValue = new Integer(0); } int result = currentValue; sequencers.put(name, currentValue + 1); return result; } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#maybeDead(ibis.ipl.impl.IbisIdentifier) */ synchronized void maybeDead(IbisIdentifier identifier) { Member member = members.get(identifier); if (member != null) { member.clearLastSeenTime(); // wake up checker thread, this suspect now (among) the oldest notifyAll(); } } /* * (non-Javadoc) * * @see ibis.ipl.impl.registry.central.SuperPool#signal(java.lang.String, * ibis.ipl.impl.IbisIdentifier[]) */ synchronized void signal(String signal, IbisIdentifier[] victims) { ArrayList<IbisIdentifier> result = new ArrayList<IbisIdentifier>(); for (IbisIdentifier victim : victims) { if (members.contains(victim)) { result.add(victim); } } addEvent(Event.SIGNAL, signal, result.toArray(new IbisIdentifier[result.size()])); notifyAll(); } void ping(Member member) { long start = System.currentTimeMillis(); if (hasEnded()) { return; } if (!isMember(member)) { return; } logger.debug("pinging " + member); Connection connection = null; try { logger.debug("creating connection to " + member); connection = new Connection(member.getIbis(), CONNECT_TIMEOUT, true, socketFactory); logger.debug("connection created to " + member + ", send opcode, checking for reply"); connection.out().writeByte(Protocol.CLIENT_MAGIC_BYTE); connection.out().writeByte(Protocol.VERSION); connection.out().writeByte(Protocol.OPCODE_PING); connection.out().flush(); // get reply connection.getAndCheckReply(); IbisIdentifier result = new IbisIdentifier(connection.in()); connection.close(); if (!result.equals(member.getIbis())) { throw new Exception("ping ended up at wrong ibis"); } logger.debug("ping to " + member + " successful"); member.updateLastSeenTime(); if (statistics != null) { statistics.add(Protocol.OPCODE_PING, System.currentTimeMillis() - start, connection.read(), connection.written(), false); } } catch (Exception e) { logger.debug("error on pinging ibis " + member, e); if (connection != null) { connection.close(); } dead(member.getIbis(), e); } } /** * Push events to the given member. Checks if the pool has not ended, and * the peer is still a current member of this pool. * * @param member * The member to push events to * @param force * if true, events are always pushed, even if the pool has ended * or the peer is no longer a member. */ void push(Member member, boolean force, boolean isBroadcast) { byte opcode; if (isBroadcast) { opcode = Protocol.OPCODE_BROADCAST; } else { opcode = Protocol.OPCODE_PUSH; } long start = System.currentTimeMillis(); if (hasEnded()) { if (!force) { return; } } if (!isMember(member)) { if (!force) { return; } } if (force) { logger.debug("forced pushing entries to " + member); } else { logger.debug("pushing entries to " + member); } Connection connection = null; try { long connecting = System.currentTimeMillis(); logger.debug("creating connection to push events to " + member); connection = new Connection(member.getIbis(), CONNECT_TIMEOUT, true, socketFactory); long connected = System.currentTimeMillis(); logger.debug("connection to " + member + " created"); connection.out().writeByte(Protocol.CLIENT_MAGIC_BYTE); connection.out().writeByte(Protocol.VERSION); connection.out().writeByte(opcode); connection.out().writeUTF(getName()); connection.out().flush(); long writtenOpcode = System.currentTimeMillis(); logger.debug("waiting for info of peer " + member); boolean requestBootstrap = connection.in().readBoolean(); int joinTime = connection.in().readInt(); int requestedEventTime = connection.in().readInt(); long readInfo = System.currentTimeMillis(); connection.sendOKReply(); long sendOk = System.currentTimeMillis(); if (requestBootstrap) { // peer requests bootstrap data writeState(connection.out(), joinTime); } long writtenState = System.currentTimeMillis(); member.setCurrentTime(requestedEventTime); Event[] events = getEvents(requestedEventTime); long gotEvents = System.currentTimeMillis(); logger.debug("sending " + events.length + " entries to " + member); connection.out().writeInt(events.length); for (int i = 0; i < events.length; i++) { events[i].writeTo(connection.out()); } long writtenEvents = System.currentTimeMillis(); connection.out().writeInt(getMinEventTime()); connection.out().flush(); long writtenAll = System.currentTimeMillis(); connection.close(); long closedConnection = System.currentTimeMillis(); logger.debug("connection to " + member + " closed"); member.updateLastSeenTime(); long done = System.currentTimeMillis(); if (statistics != null) { long end = System.currentTimeMillis(); statistics.add(opcode, end - start, connection.read(), connection.written(), false); } if (logger.isInfoEnabled()) { logger.info("connecting = " + (connecting - start) + ", connected = " + (connected - connecting) + ", writtenOpcode = " + (writtenOpcode - connected) + ", readInfo = " + (readInfo - writtenOpcode) + ", sendOk = " + (sendOk - readInfo) + ", writtenState (" + requestBootstrap + ") = " + (writtenState - sendOk) + "\n\t\t\t" + "gotEvents = " + (gotEvents - writtenState) + ", writtenEvents = " + (writtenEvents - gotEvents) + ", writtenAll = " + (writtenAll - writtenEvents) + ", closedConnection = " + (closedConnection - writtenAll) + ", done = " + (done - closedConnection)); } } catch (IOException e) { if (isMember(member)) { if (printErrors) { print("cannot reach " + member + " to push events to"); // e.printStackTrace(System.out); } } } finally { if (connection != null) { connection.close(); } } } private synchronized Member getSuspectMember() { while (!hasEnded()) { Member oldest = members.getLeastRecentlySeen(); logger.debug("oldest = " + oldest); long currentTime = System.currentTimeMillis(); long timeout; if (oldest == null) { timeout = 1000; } else { timeout = (oldest.getLastSeen() + heartbeatInterval) - currentTime; } if (timeout <= 0) { logger.debug(oldest + " now a suspect"); return oldest; } // wait a while, get oldest again (might have changed) try { logger.debug(timeout + " milliseconds until " + oldest + " needs checking"); wait(timeout); } catch (InterruptedException e) { // IGNORE } } return null; } synchronized void gotHeartbeat(IbisIdentifier identifier) { Member member = members.get(identifier); logger.debug("updating last seen time for " + member); if (member != null) { member.updateLastSeenTime(); } } synchronized Member[] getRandomMembers(int size) { return members.getRandom(size); } synchronized Member getRandomMember() { return members.getRandom(); } synchronized boolean isMember(Member member) { return members.contains(member); } synchronized Member[] getMembers() { return members.asArray(); } /** * Returns the children of the root node */ synchronized Member[] getChildren() { return members.getRootChildren(); } public String toString() { return "Pool " + name + ": value = " + getSize() + ", event time = " + getEventTime(); } public synchronized String getStatsString() { StringBuilder message = new StringBuilder(); Formatter formatter = new Formatter(message); if (isClosedWorld()) { formatter.format( "%s\n %12d %5d %6d %5d %9d %7d %10d %6b %5b\n", getName(), getSize(), eventStats[Event.JOIN], eventStats[Event.LEAVE], eventStats[Event.DIED], eventStats[Event.ELECT], eventStats[Event.SIGNAL], getFixedSize(), isClosed(), ended); } else { formatter.format( "%s\n %12d %5d %6d %5d %9d %7d %10s %6b %5b\n", getName(), getSize(), eventStats[Event.JOIN], eventStats[Event.LEAVE], eventStats[Event.DIED], eventStats[Event.ELECT], eventStats[Event.SIGNAL], "N.A.", isClosed(), ended); } return message.toString(); } /** * Remove events from the event history to make space. * */ synchronized void purgeHistory() { int newMinimum = members.getMinimumTime(); //FIXME: disabled event purging... newMinimum = 0; if (newMinimum == -1) { // pool is empty, clear out all events newMinimum = getEventTime(); } if (newMinimum < minEventTime) { logger.error("tried to set minimum event time backwards"); return; } events.setMinimum(newMinimum); minEventTime = newMinimum; } /** * contacts any suspect nodes when asked */ public void run() { logger.debug("new pinger thread started"); Member suspect = getSuspectMember(); // fake we saw this member so noone else tries to ping it too if (suspect != null) { suspect.updateLastSeenTime(); } if (hasEnded()) { return; } // start a new thread for pining another suspect ThreadPool.createNew(this, "pool pinger thread"); if (suspect != null) { ping(suspect); } } Statistics getStatistics() { return statistics; } }
package org.deviceconnect.android.deviceplugin.uvc.profile; import android.content.Intent; import android.os.Bundle; import org.deviceconnect.android.deviceplugin.uvc.recorder.MediaRecorder; import org.deviceconnect.android.deviceplugin.uvc.recorder.UVCRecorder; import org.deviceconnect.android.deviceplugin.uvc.recorder.preview.PreviewServer; import org.deviceconnect.android.deviceplugin.uvc.service.UVCService; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.MediaStreamRecordingProfile; import org.deviceconnect.android.profile.api.DConnectApi; import org.deviceconnect.android.profile.api.DeleteApi; import org.deviceconnect.android.profile.api.GetApi; import org.deviceconnect.android.profile.api.PutApi; import org.deviceconnect.message.DConnectMessage; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * UVC MediaStream Recording Profile. * * @author NTT DOCOMO, INC. */ public class UVCMediaStreamRecordingProfile extends MediaStreamRecordingProfile { private final ExecutorService mExecutor = Executors.newSingleThreadExecutor(); private final DConnectApi mGetMediaRecorderApi = new GetApi() { @Override public String getAttribute() { return ATTRIBUTE_MEDIARECORDER; } @Override public boolean onRequest(final Intent request, final Intent response) { mExecutor.execute(() -> { try { UVCRecorder recorder = getUVCRecorder(); if (recorder == null) { MessageUtils.setNotFoundServiceError(response); return; } if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "device is not connected."); return; } setMediaRecorders(response, recorder); setResult(response, DConnectMessage.RESULT_OK); } finally { sendResponse(response); } }); return false; } }; private final DConnectApi mGetOptionsApi = new GetApi() { @Override public String getAttribute() { return ATTRIBUTE_OPTIONS; } @Override public boolean onRequest(final Intent request, final Intent response) { mExecutor.execute(() -> { try { if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "device is not connected."); return; } UVCRecorder recorder = getUVCRecorder(); if (recorder == null) { MessageUtils.setNotFoundServiceError(response); return; } setOptions(response, recorder); setResult(response, DConnectMessage.RESULT_OK); } finally { sendResponse(response); } }); return false; } }; private final DConnectApi mPutOptionsApi = new PutApi() { @Override public String getAttribute() { return ATTRIBUTE_OPTIONS; } @Override public boolean onRequest(final Intent request, final Intent response) { mExecutor.execute(() -> { try { Integer imageWidth = getImageWidth(request); Integer imageHeight = getImageHeight(request); Integer previewWidth = getPreviewWidth(request); Integer previewHeight = getPreviewHeight(request); Double previewMaxFrameRate = getPreviewMaxFrameRate(request); UVCRecorder recorder = getUVCRecorder(); if (recorder == null) { MessageUtils.setNotFoundServiceError(response); return; } if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "device is not connected."); return; } if (imageWidth == null && imageHeight != null || imageWidth != null && imageHeight == null) { MessageUtils.setInvalidRequestParameterError(response, "imageWidth or imageHeight is not set."); return; } if (previewWidth == null && previewHeight != null || previewWidth != null && previewHeight == null) { MessageUtils.setInvalidRequestParameterError(response, "previewWidth or previewHeight is not set."); return; } if (imageWidth != null && imageHeight != null) { recorder.setPictureSize(new MediaRecorder.Size(imageWidth, imageHeight)); } if (previewWidth != null && previewHeight != null) { recorder.setPreviewSize(new MediaRecorder.Size(previewWidth, previewHeight)); } if (previewMaxFrameRate != null) { recorder.setMaxFrameRate(previewMaxFrameRate); } setResult(response, DConnectMessage.RESULT_OK); } finally { sendResponse(response); } }); return false; } }; private final DConnectApi mPutPreviewApi = new PutApi() { @Override public String getAttribute() { return ATTRIBUTE_PREVIEW; } @Override public boolean onRequest(final Intent request, final Intent response) { mExecutor.execute(() -> { try { if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "device is not connected."); return; } UVCRecorder recorder = getUVCRecorder(); List<PreviewServer> servers = recorder.startPreview(); if (servers.isEmpty()) { MessageUtils.setIllegalDeviceStateError(response, "Failed to start a preview server."); } else { String defaultUri = null; List<Bundle> streams = new ArrayList<>(); for (PreviewServer server : servers) { // Motion-JPEG if ("video/x-mjpeg".equals(server.getMimeType())) { defaultUri = server.getUrl(); } Bundle stream = new Bundle(); stream.putString("mimeType", server.getMimeType()); stream.putString("uri", server.getUrl()); streams.add(stream); } setResult(response, DConnectMessage.RESULT_OK); setUri(response, defaultUri != null ? defaultUri : ""); response.putExtra("streams", streams.toArray(new Bundle[streams.size()])); } } finally { sendResponse(response); } }); return false; } }; private final DConnectApi mDeletePreviewApi = new DeleteApi() { @Override public String getAttribute() { return ATTRIBUTE_PREVIEW; } @Override public boolean onRequest(final Intent request, final Intent response) { mExecutor.execute(() -> { try { UVCRecorder recorder = getUVCRecorder(); if (recorder != null) { recorder.stopPreview(); } if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "device is not connected."); return; } setResult(response, DConnectMessage.RESULT_OK); } finally { sendResponse(response); } }); return false; } }; public UVCMediaStreamRecordingProfile() { addApi(mGetMediaRecorderApi); addApi(mGetOptionsApi); addApi(mPutOptionsApi); addApi(mPutPreviewApi); addApi(mDeletePreviewApi); } private UVCRecorder getUVCRecorder() { UVCService service = (UVCService) getService(); return service != null ? service.getUVCRecorder() : null; } private static void setMediaRecorders(final Intent response, final UVCRecorder uvcRecorder) { List<Bundle> recorderList = new ArrayList<>(); Bundle recorder = new Bundle(); setMediaRecorder(recorder, uvcRecorder); recorderList.add(recorder); setRecorders(response, recorderList); } private static void setMediaRecorder(final Bundle recorder, final UVCRecorder uvcRecorder) { MediaRecorder.Size previewSize = uvcRecorder.getPreviewSize(); setRecorderId(recorder, uvcRecorder.getId()); setRecorderName(recorder, uvcRecorder.getName()); setRecorderState(recorder, uvcRecorder.isStartedPreview() ? RecorderState.RECORDING : RecorderState.INACTIVE); setRecorderPreviewWidth(recorder, previewSize.getWidth()); setRecorderPreviewHeight(recorder, previewSize.getHeight()); setRecorderPreviewMaxFrameRate(recorder, uvcRecorder.getMaxFrameRate()); setRecorderMIMEType(recorder, uvcRecorder.getMimeType()); setRecorderConfig(recorder, ""); } private static void setOptions(final Intent response, final UVCRecorder recorder) { List<MediaRecorder.Size> options = recorder.getSupportedPreviewSizes(); List<Bundle> previewSizes = new ArrayList<>(); for (MediaRecorder.Size option : options) { Bundle size = new Bundle(); setWidth(size, option.getWidth()); setHeight(size, option.getHeight()); previewSizes.add(size); } setPreviewSizes(response, previewSizes); setMIMEType(response.getExtras(), recorder.getSupportedMimeTypes()); } }
package org.csstudio.display.builder.representation.javafx.widgets; import static org.csstudio.display.builder.representation.ToolkitRepresentation.logger; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import org.csstudio.display.builder.model.DirtyFlag; import org.csstudio.display.builder.model.DisplayModel; import org.csstudio.display.builder.model.UntypedWidgetPropertyListener; import org.csstudio.display.builder.model.WidgetProperty; import org.csstudio.display.builder.model.WidgetPropertyListener; import org.csstudio.display.builder.model.util.ModelResourceUtil; import org.csstudio.display.builder.model.util.VTypeUtil; import org.csstudio.display.builder.model.widgets.BoolButtonWidget; import org.csstudio.display.builder.representation.javafx.JFXUtil; import org.csstudio.javafx.Styles; import org.diirt.vtype.VEnum; import org.diirt.vtype.VType; import javafx.application.Platform; import javafx.scene.control.Button; import javafx.scene.control.ButtonBase; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Paint; import javafx.scene.paint.Stop; import javafx.scene.shape.Ellipse; /** Creates JavaFX item for model widget * @author Megan Grodowitz */ @SuppressWarnings("nls") public class BoolButtonRepresentation extends RegionBaseRepresentation<ButtonBase, BoolButtonWidget> { private final DirtyFlag dirty_representation = new DirtyFlag(); private final DirtyFlag dirty_enablement = new DirtyFlag(); private final DirtyFlag dirty_value = new DirtyFlag(); /** State: 0 or 1 */ private volatile int on_state = 1; private volatile int use_bit = 0; private volatile Integer rt_value = 0; // Design decision: Plain Button. // JFX ToggleButton appears natural to reflect two states, // but this type of button is updated by both the user // (press to 'push', 'release') and the PV. // When user pushes button, value is sent to PV // and the button should update its state as the // update is received from the PV. // The ToggleButton, however, will 'select' or not // just because of the user interaction. // If this is then in addition updated by the PV, // the ToggleButton tends to 'flicker'. private volatile Button button; private volatile Ellipse led; private volatile String background; private volatile Color foreground; private volatile Color[] state_colors; private volatile Color value_color; private volatile String[] state_labels; private volatile String value_label; private volatile ImageView[] state_images; private volatile ImageView value_image; private final UntypedWidgetPropertyListener imagesChangedListener = this::imagesChanged; private final UntypedWidgetPropertyListener representationChangedListener = this::representationChanged; private final WidgetPropertyListener<Integer> bitChangedListener = this::bitChanged; private final WidgetPropertyListener<Boolean> enablementChangedListener = this::enablementChanged; private final WidgetPropertyListener<VType> valueChangedListener = this::valueChanged; @Override public ButtonBase createJFXNode() throws Exception { led = new Ellipse(); led.getStyleClass().add("led"); button = new Button("BoolButton", led); button.getStyleClass().add("action_button"); button.setOnAction(event -> handlePress()); button.setMnemonicParsing(false); // Model has width/height, but JFX widget has min, pref, max size. // updateChanges() will set the 'pref' size, so make min use that as well. button.setMinSize(ButtonBase.USE_PREF_SIZE, ButtonBase.USE_PREF_SIZE); toolkit.execute( ( ) -> Platform.runLater(button::requestLayout)); return button; } /** @param respond to button press */ private void handlePress() { logger.log(Level.FINE, "{0} pressed", model_widget); Platform.runLater(this::confirm); } private void confirm() { final boolean prompt; switch (model_widget.propConfirmDialog().getValue()) { case BOTH: prompt = true; break; case PUSH: prompt = on_state == 0; break; case RELEASE: prompt = on_state == 1; break; case NONE: default: prompt = false; } if (prompt) { final String message = model_widget.propConfirmMessage().getValue(); final String password = model_widget.propPassword().getValue(); if (password.length() > 0) { if (toolkit.showPasswordDialog(model_widget, message, password) == null) return; } else if ( !toolkit.showConfirmationDialog(model_widget, message)) return; } final int new_val = (rt_value ^ ((use_bit < 0) ? 1 : (1 << use_bit)) ); toolkit.fireWrite(model_widget, new_val); } @Override protected void registerListeners() { super.registerListeners(); representationChanged(null,null,null); model_widget.propWidth().addUntypedPropertyListener(representationChangedListener); model_widget.propHeight().addUntypedPropertyListener(representationChangedListener); model_widget.propOffLabel().addUntypedPropertyListener(representationChangedListener); model_widget.propOffImage().addUntypedPropertyListener(imagesChangedListener); model_widget.propOffColor().addUntypedPropertyListener(representationChangedListener); model_widget.propOnLabel().addUntypedPropertyListener(representationChangedListener); model_widget.propOnImage().addUntypedPropertyListener(imagesChangedListener); model_widget.propOnColor().addUntypedPropertyListener(representationChangedListener); model_widget.propShowLED().addUntypedPropertyListener(representationChangedListener); model_widget.propFont().addUntypedPropertyListener(representationChangedListener); model_widget.propForegroundColor().addUntypedPropertyListener(representationChangedListener); model_widget.propBackgroundColor().addUntypedPropertyListener(representationChangedListener); model_widget.propEnabled().addPropertyListener(enablementChangedListener); model_widget.runtimePropPVWritable().addPropertyListener(enablementChangedListener); model_widget.propBit().addPropertyListener(bitChangedListener); model_widget.runtimePropValue().addPropertyListener(valueChangedListener); imagesChanged(null, null, null); bitChanged(model_widget.propBit(), null, model_widget.propBit().getValue()); enablementChanged(null, null, null); valueChanged(null, null, model_widget.runtimePropValue().getValue()); } @Override protected void unregisterListeners() { model_widget.propWidth().removePropertyListener(representationChangedListener); model_widget.propHeight().removePropertyListener(representationChangedListener); model_widget.propOffLabel().removePropertyListener(representationChangedListener); model_widget.propOffImage().removePropertyListener(imagesChangedListener); model_widget.propOffColor().removePropertyListener(representationChangedListener); model_widget.propOnLabel().removePropertyListener(representationChangedListener); model_widget.propOnImage().removePropertyListener(imagesChangedListener); model_widget.propOnColor().removePropertyListener(representationChangedListener); model_widget.propShowLED().removePropertyListener(representationChangedListener); model_widget.propFont().removePropertyListener(representationChangedListener); model_widget.propForegroundColor().removePropertyListener(representationChangedListener); model_widget.propBackgroundColor().removePropertyListener(representationChangedListener); model_widget.propEnabled().removePropertyListener(enablementChangedListener); model_widget.runtimePropPVWritable().removePropertyListener(enablementChangedListener); model_widget.propBit().removePropertyListener(bitChangedListener); model_widget.runtimePropValue().removePropertyListener(valueChangedListener); super.unregisterListeners(); } private void stateChanged() { on_state = ((use_bit < 0) ? (rt_value != 0) : (((rt_value >> use_bit) & 1) == 1)) ? 1 : 0; value_color = state_colors[on_state]; value_label = state_labels[on_state]; value_image = state_images[on_state]; dirty_value.mark(); toolkit.scheduleUpdate(this); } private void bitChanged(final WidgetProperty<Integer> property, final Integer old_value, final Integer new_value) { use_bit = new_value; stateChanged(); } private void valueChanged(final WidgetProperty<VType> property, final VType old_value, final VType new_value) { if ((new_value instanceof VEnum) && model_widget.propLabelsFromPV().getValue()) { final List<String> labels = ((VEnum) new_value).getLabels(); if (labels.size() == 2) { model_widget.propOffLabel().setValue(labels.get(0)); model_widget.propOnLabel().setValue(labels.get(1)); } } rt_value = VTypeUtil.getValueNumber(new_value).intValue(); stateChanged(); } private void imagesChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value) { state_images = new ImageView[] { loadImage(model_widget.propOffImage().getValue()), loadImage(model_widget.propOnImage().getValue()) }; } private ImageView loadImage(final String path) { if (path.isEmpty()) return null; try { // Resolve image file relative to the source widget model (not 'top'!) final DisplayModel widget_model = model_widget.getDisplayModel(); final String resolved = ModelResourceUtil.resolveResource(widget_model, path); return new ImageView(new Image(ModelResourceUtil.openResourceStream(resolved))); } catch (Exception ex) { logger.log(Level.WARNING, model_widget + " cannot load image", ex); } return null; } private void representationChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value) { foreground = JFXUtil.convert(model_widget.propForegroundColor().getValue()); background = JFXUtil.shadedStyle(model_widget.propBackgroundColor().getValue()); state_colors = new Color[] { JFXUtil.convert(model_widget.propOffColor().getValue()), JFXUtil.convert(model_widget.propOnColor().getValue()) }; state_labels = new String[] { model_widget.propOffLabel().getValue(), model_widget.propOnLabel().getValue() }; value_color = state_colors[on_state]; value_label = state_labels[on_state]; dirty_representation.mark(); toolkit.scheduleUpdate(this); } private void enablementChanged(final WidgetProperty<Boolean> property, final Boolean old_value, final Boolean new_value) { dirty_enablement.mark(); toolkit.scheduleUpdate(this); } private Paint editColor ( ) { final Color[] save_colors = state_colors; return new LinearGradient(0, 0, 1, 1, true, CycleMethod.NO_CYCLE, Arrays.asList( new Stop(0.0, save_colors[0]), new Stop(0.5, save_colors[0]), new Stop(0.5, save_colors[1]), new Stop(1.0, save_colors[1]) )); } @Override public void updateChanges() { super.updateChanges(); boolean update_value = dirty_value.checkAndClear(); if (dirty_representation.checkAndClear()) { final int wid = model_widget.propWidth().getValue(), hei = model_widget.propHeight().getValue(); jfx_node.setPrefSize(wid, hei); jfx_node.setFont(JFXUtil.convert(model_widget.propFont().getValue())); jfx_node.setTextFill(foreground); jfx_node.setStyle(background); if (model_widget.propShowLED().getValue()) { led.setVisible(true); final int size = Math.min(wid, hei); led.setRadiusX(size / 3.7); led.setRadiusY(size / 3.7); } else { led.setVisible(false); // Give all room to label led.setRadiusX(0); led.setRadiusY(0); } update_value = true; } if (dirty_enablement.checkAndClear()) { final boolean enabled = model_widget.propEnabled().getValue() && model_widget.runtimePropPVWritable().getValue(); jfx_node.setDisable(! enabled); Styles.update(jfx_node, Styles.NOT_ENABLED, !enabled); } if (update_value) { jfx_node.setText(value_label); final ImageView image = value_image; if (image == null) { jfx_node.setGraphic(led); // Put highlight in top-left corner, about 0.2 wide, // relative to actual size of LED led.setFill(toolkit.isEditMode() ? editColor() : value_color); } else jfx_node.setGraphic(image); } } }
package org.csstudio.display.builder.representation.javafx.widgets; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.csstudio.display.builder.model.DirtyFlag; import org.csstudio.display.builder.model.UntypedWidgetPropertyListener; import org.csstudio.display.builder.model.WidgetProperty; import org.csstudio.display.builder.model.WidgetPropertyListener; import org.csstudio.display.builder.model.persist.NamedWidgetColors; import org.csstudio.display.builder.model.persist.WidgetColorService; import org.csstudio.display.builder.model.util.VTypeUtil; import org.csstudio.display.builder.model.widgets.ThumbWheelWidget; import org.csstudio.display.builder.representation.javafx.JFXUtil; import org.csstudio.javafx.Styles; import org.diirt.vtype.Display; import org.diirt.vtype.VType; import org.diirt.vtype.ValueUtil; import javafx.scene.paint.Color; import javafx.scene.text.Font; import se.europeanspallationsource.javafx.control.thumbwheel.ThumbWheel; /** * @author claudiorosati, European Spallation Source ERIC * @version 1.0.0 13 Dec 2017 */ public class ThumbWheelRepresentation extends RegionBaseRepresentation<ThumbWheel, ThumbWheelWidget> { protected static final Color ALARM_MAJOR_COLOR = JFXUtil.convert(WidgetColorService.getColor(NamedWidgetColors.ALARM_MAJOR)); protected static final Color ALARM_MINOR_COLOR = JFXUtil.convert(WidgetColorService.getColor(NamedWidgetColors.ALARM_MINOR)); private final UntypedWidgetPropertyListener contentChangedListener = this::contentChanged; private final DirtyFlag dirtyContent = new DirtyFlag(); private final DirtyFlag dirtyGeometry = new DirtyFlag(); private final DirtyFlag dirtyLimits = new DirtyFlag(); private final DirtyFlag dirtyLook = new DirtyFlag(); private final DirtyFlag dirtyStyle = new DirtyFlag(); private final DirtyFlag dirtyValue = new DirtyFlag(); private final UntypedWidgetPropertyListener geometryChangedListener = this::geometryChanged; private final UntypedWidgetPropertyListener limitsChangedListener = this::limitsChanged; private final UntypedWidgetPropertyListener lookChangedListener = this::lookChanged; private volatile double max = 100.0; private volatile double min = 0.0; private final UntypedWidgetPropertyListener styleChangedListener = this::styleChanged; private final AtomicBoolean updatingValue = new AtomicBoolean(false); private final WidgetPropertyListener<VType> valueChangedListener = this::valueChanged; @Override public void updateChanges ( ) { super.updateChanges(); Object value; if ( dirtyContent.checkAndClear() ) { value = model_widget.propDecimalDigits().getValue(); if ( !Objects.equals(value, jfx_node.getDecimalDigits()) ) { jfx_node.setDecimalDigits((int) value); } value = model_widget.propIntegerDigits().getValue(); if ( !Objects.equals(value, jfx_node.getIntegerDigits()) ) { jfx_node.setIntegerDigits((int) value); } // Since jfx_node.isManaged() == false, need to trigger layout jfx_node.layout(); } if ( dirtyGeometry.checkAndClear() ) { value = model_widget.propVisible().getValue(); if ( !Objects.equals(value, jfx_node.isVisible()) ) { jfx_node.setVisible((boolean) value); } jfx_node.setLayoutX(model_widget.propX().getValue()); jfx_node.setLayoutY(model_widget.propY().getValue()); jfx_node.resize(model_widget.propWidth().getValue(), model_widget.propHeight().getValue()); } if ( dirtyLook.checkAndClear() ) { value = JFXUtil.convert(model_widget.propBackgroundColor().getValue()); if ( !Objects.equals(value, jfx_node.getBackgroundColor()) ) { jfx_node.setBackgroundColor((Color) value); } value = JFXUtil.convert(model_widget.propButtonsColor().getValue()); if ( !Objects.equals(value, jfx_node.getDecrementButtonsColor()) ) { jfx_node.setDecrementButtonsColor((Color) value); } if ( !Objects.equals(value, jfx_node.getIncrementButtonsColor()) ) { jfx_node.setIncrementButtonsColor((Color) value); } value = JFXUtil.convert(model_widget.propFont().getValue()); if ( !Objects.equals(value, jfx_node.getFont()) ) { jfx_node.setFont((Font) value); } value = JFXUtil.convert(model_widget.propForegroundColor().getValue()); if ( !Objects.equals(value, jfx_node.getForegroundColor()) ) { jfx_node.setForegroundColor((Color) value); } value = JFXUtil.convert(model_widget.propInvalidColor().getValue()); if ( !Objects.equals(value, jfx_node.getInvalidColor()) ) { jfx_node.setInvalidColor((Color) value); } } if ( dirtyLimits.checkAndClear() ) { if ( !Objects.equals(max, jfx_node.getMaxValue()) ) { jfx_node.setMaxValue(max); } if ( !Objects.equals(min, jfx_node.getMinValue()) ) { jfx_node.setMinValue(min); } } if ( dirtyStyle.checkAndClear() ) { Styles.update(jfx_node, Styles.NOT_ENABLED, !model_widget.propEnabled().getValue()); value = model_widget.propScrollEnabled().getValue(); if ( !Objects.equals(value, jfx_node.isScrollEnabled()) ) { jfx_node.setScrollEnabled((boolean) value); } } if ( dirtyValue.checkAndClear() && updatingValue.compareAndSet(false, true) ) { try { double newVal = VTypeUtil.getValueNumber(model_widget.runtimePropValue().getValue()).doubleValue(); if ( Double.isFinite(newVal) ) { jfx_node.setValue(clamp(newVal, min, max)); // Since jfx_node.isManaged() == false, need to trigger layout jfx_node.layout(); } else { // TODO: CR: do something!!! } } finally { updatingValue.set(false); } } } @Override protected ThumbWheel createJFXNode ( ) throws Exception { updateLimits(false); ThumbWheel thumbwheel = new ThumbWheel(); thumbwheel.setGraphicVisible(true); thumbwheel.setSpinnerShaped(true); if (! toolkit.isEditMode()) thumbwheel.valueProperty().addListener((observable, oldValue, newValue) -> { if ( !updatingValue.get() ) toolkit.fireWrite(model_widget, newValue); }); toolkit.schedule( ( ) -> { jfx_node.setPrefWidth(model_widget.propWidth().getValue()); jfx_node.setPrefHeight(model_widget.propHeight().getValue()); }, 111, TimeUnit.MILLISECONDS); dirtyContent.mark(); dirtyGeometry.mark(); dirtyLimits.mark(); dirtyLook.mark(); dirtyStyle.mark(); dirtyValue.mark(); toolkit.scheduleUpdate(this); // This code manages layout, // because otherwise for example border changes would trigger // expensive Node.notifyParentOfBoundsChange() recursing up the scene graph thumbwheel.setManaged(false); return thumbwheel; } @Override protected boolean isFilteringEditModeClicks() { return true; } @Override protected void registerListeners ( ) { super.registerListeners(); model_widget.propDecimalDigits().addUntypedPropertyListener(contentChangedListener); model_widget.propIntegerDigits().addUntypedPropertyListener(contentChangedListener); model_widget.propPVName().addUntypedPropertyListener(contentChangedListener); model_widget.propVisible().addUntypedPropertyListener(geometryChangedListener); model_widget.propX().addUntypedPropertyListener(geometryChangedListener); model_widget.propY().addUntypedPropertyListener(geometryChangedListener); model_widget.propWidth().addUntypedPropertyListener(geometryChangedListener); model_widget.propHeight().addUntypedPropertyListener(geometryChangedListener); model_widget.propBackgroundColor().addUntypedPropertyListener(lookChangedListener); model_widget.propButtonsColor().addUntypedPropertyListener(lookChangedListener); model_widget.propFont().addUntypedPropertyListener(lookChangedListener); model_widget.propForegroundColor().addUntypedPropertyListener(lookChangedListener); model_widget.propInvalidColor().addUntypedPropertyListener(lookChangedListener); model_widget.propLimitsFromPV().addUntypedPropertyListener(limitsChangedListener); model_widget.propMaximum().addUntypedPropertyListener(limitsChangedListener); model_widget.propMinimum().addUntypedPropertyListener(limitsChangedListener); model_widget.propEnabled().addUntypedPropertyListener(styleChangedListener); model_widget.propScrollEnabled().addUntypedPropertyListener(styleChangedListener); if ( toolkit.isEditMode() ) { dirtyValue.checkAndClear(); } else { model_widget.runtimePropValue().addPropertyListener(valueChangedListener); valueChanged(null, null, null); } } @Override protected void unregisterListeners ( ) { model_widget.propDecimalDigits().removePropertyListener(contentChangedListener); model_widget.propIntegerDigits().removePropertyListener(contentChangedListener); model_widget.propPVName().removePropertyListener(contentChangedListener); model_widget.propVisible().removePropertyListener(geometryChangedListener); model_widget.propX().removePropertyListener(geometryChangedListener); model_widget.propY().removePropertyListener(geometryChangedListener); model_widget.propWidth().removePropertyListener(geometryChangedListener); model_widget.propHeight().removePropertyListener(geometryChangedListener); model_widget.propBackgroundColor().removePropertyListener(lookChangedListener); model_widget.propButtonsColor().removePropertyListener(lookChangedListener); model_widget.propFont().removePropertyListener(lookChangedListener); model_widget.propForegroundColor().removePropertyListener(lookChangedListener); model_widget.propInvalidColor().removePropertyListener(lookChangedListener); model_widget.propLimitsFromPV().removePropertyListener(limitsChangedListener); model_widget.propMaximum().removePropertyListener(limitsChangedListener); model_widget.propMinimum().removePropertyListener(limitsChangedListener); model_widget.propEnabled().removePropertyListener(styleChangedListener); model_widget.propScrollEnabled().removePropertyListener(styleChangedListener); if ( !toolkit.isEditMode() ) { model_widget.runtimePropValue().removePropertyListener(valueChangedListener); } super.unregisterListeners(); } private double clamp ( double value, double minValue, double maxValue ) { return ( value < minValue ) ? minValue : ( value > maxValue ) ? maxValue : value; } private void contentChanged ( final WidgetProperty<?> property, final Object old_value, final Object new_value ) { dirtyContent.mark(); toolkit.scheduleUpdate(this); } private void geometryChanged ( final WidgetProperty<?> property, final Object old_value, final Object new_value ) { dirtyGeometry.mark(); toolkit.scheduleUpdate(this); } private void limitsChanged ( final WidgetProperty<?> property, final Object old_value, final Object new_value ) { updateLimits(model_widget.propLimitsFromPV().getValue()); dirtyLimits.mark(); toolkit.scheduleUpdate(this); } private void lookChanged ( final WidgetProperty<?> property, final Object old_value, final Object new_value ) { dirtyLook.mark(); toolkit.scheduleUpdate(this); } private void styleChanged ( final WidgetProperty<?> property, final Object old_value, final Object new_value ) { dirtyStyle.mark(); toolkit.scheduleUpdate(this); } /** * Updates, if required, the limits and zones. * * @param limitsFromPV {@code true} if PV limits must be used. * @return {@code true} is something changed and and UI update is required. */ private boolean updateLimits ( boolean limitsFromPV ) { boolean somethingChanged = false; // Model's values. double newMin = model_widget.propMinimum().getValue(); double newMax = model_widget.propMaximum().getValue(); // If invalid limits, fall back to 0..100 range. if ( !Double.isFinite(newMin) || !Double.isFinite(newMax) || newMin > newMax ) { newMin = 0.0; newMax = 100.0; } if ( limitsFromPV ) { // Try to get display range from PV. final Display display_info = ValueUtil.displayOf(model_widget.runtimePropValue().getValue()); if ( display_info != null ) { double infoMin = display_info.getLowerCtrlLimit(); double infoMax = display_info.getUpperCtrlLimit(); if ( Double.isFinite(infoMin) && Double.isFinite(infoMax) && infoMin < infoMax ) { newMin = infoMin; newMax = infoMax; } } } if ( min != newMin ) { min = newMin; somethingChanged = true; } if ( max != newMax ) { max = newMax; somethingChanged = true; } return somethingChanged; } private void valueChanged ( final WidgetProperty<? extends VType> property, final VType old_value, final VType new_value ) { Boolean limitsFromPV = model_widget.propLimitsFromPV().getValue(); if ( limitsFromPV ) { updateLimits(limitsFromPV); dirtyLimits.mark(); } dirtyValue.mark(); toolkit.scheduleUpdate(this); } }
package org.yeastrc.proxl.import_xml_to_db.constants; public class Proxl_XSD_XML_Schema_Enabled_And_Filename_With_Path_Constant { /** * If true, then schema validation will be done */ public static final boolean PROXL_XSD_XML_SCHEMA_VALIDATION_ENABLED = true; /** * The "/" specifies to start at the root of the package path */ public static final String PROXL_XSD_XML_SCHEMA_FILENAME_WITH_PATH = "/proxl-xml-v1.4.1.xsd"; }
package org.jpos.ee; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.List; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.ObjectNotFoundException; import org.hibernate.criterion.Restrictions; import org.jpos.iso.ISOUtil; import org.jpos.security.SystemSeed; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; /** * @author Alejandro Revilla */ public class UserManager { DB db; VERSION version; public UserManager (DB db) { super (); this.db = db; version = VERSION.ZERO; } public UserManager (DB db, VERSION version) { super (); this.db = db; this.version = version; } /** * @return all users * @throws HibernateException on low level hibernate related exception */ public List findAll () throws HibernateException { return db.session().createCriteria (User.class) .add (Restrictions.eq ("deleted", Boolean.FALSE)) .list(); } public User getUserByNick (String nick) throws HibernateException { return getUserByNick(nick, false); } public User getUserByNick (String nick, boolean includeDeleted) throws HibernateException { try { Criteria crit = db.session().createCriteria (User.class) .add (Restrictions.eq ("nick", nick)); if (!includeDeleted) crit = crit.add (Restrictions.eq ("deleted", Boolean.FALSE)); return (User) crit.uniqueResult(); } catch (ObjectNotFoundException ignored) { } return null; } /** * @param nick name. * @param pass hash * @return the user * @throws BLException if invalid user/pass * @throws HibernateException on low level hibernate related exception */ public User getUserByNick (String nick, String pass) throws HibernateException, BLException { User u = getUserByNick(nick); assertNotNull (u, "User does not exist"); assertTrue(checkPassword(u, pass), "Invalid password"); return u; } public boolean checkPassword (User u, String clearpass) throws HibernateException, BLException { assertNotNull(clearpass, "Invalid pass"); String passwordHash = u.getPassword(); assertNotNull(passwordHash, "Password is null"); VERSION v = VERSION.getVersion(passwordHash); assertTrue(v != VERSION.UNKNOWN, "Unknown password"); switch (v.getVersion()) { case (byte) 0: return (passwordHash.equals(getV0Hash(u.getId(), clearpass))); case (byte) 1: byte[] b = Base64.decode(passwordHash); byte[] salt = new byte[VERSION.ONE.getSalt().length]; byte[] clientSalt = new byte[VERSION.ONE.getSalt().length]; System.arraycopy (b, 1, salt, 0, salt.length); System.arraycopy(b, 1 + salt.length, clientSalt, 0, clientSalt.length); clearpass = clearpass.startsWith("v1:") ? clearpass.substring(3) : upgradeClearPassword(clearpass, clientSalt); String computedPasswordHash = genV1Hash(clearpass, VERSION.ONE.getSalt(salt), clientSalt); return computedPasswordHash.equals(u.getPassword()); } return false; } /** * @param u the user * @param clearpass new password in clear * @return true if password is in PasswordHistory */ public boolean checkNewPassword (User u, String clearpass) { // TODO - we need to reuse client hash in order to check duplicates String newHash = getV0Hash(u.getId(), clearpass); if (newHash.equals(u.getPassword())) return false; for (PasswordHistory p : u.getPasswordhistory()) { if (p.getValue().equals(newHash)) return false; } return true; } public void setPassword(User u, String clearpass) throws BLException { setPassword(u, clearpass, null); } public void setPassword (User u, String clearpass, User author) throws BLException { if (u.getPassword() != null) u.addPasswordHistoryValue(u.getPassword()); switch (version) { case ZERO: setV0Password(u, clearpass); break; case ONE: setV1Password (u, clearpass); break; } RevisionManager revmgr = new RevisionManager(db); if (author == null) author = u; revmgr.createRevision (author, "user." + u.getId(), "Password changed"); db.session().saveOrUpdate(u); } // VERSION ZERO IMPLEMENTATION private static String getV0Hash (long id, String pass) { String hash = null; try { MessageDigest md = MessageDigest.getInstance ("SHA"); md.update (Long.toString(id,16).getBytes()); hash = ISOUtil.hexString ( md.digest (pass.getBytes()) ).toLowerCase(); } catch (NoSuchAlgorithmException e) { // should never happen } return hash; } private void setV0Password (User u, String clearpass) { u.setPassword(getV0Hash(u.getId(), clearpass)); } // VERSION ONE IMPLEMENTATION private String upgradeClearPassword (String clearpass, byte[] salt) { return ISOUtil.hexString(genV1ClientHash(clearpass, salt)); } private byte[] genSalt(int l) { SecureRandom sr; try { sr = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[l]; sr.nextBytes(salt); return salt; } catch (NoSuchAlgorithmException ignored) { // Should never happen, SHA1PRNG is a supported algorithm } return null; } public boolean upgradePassword (User u, String clearpass) throws HibernateException, BLException { assertNotNull(clearpass, "Invalid pass"); String passwordHash = u.getPassword(); assertNotNull(passwordHash, "Password is null"); VERSION v = VERSION.getVersion(passwordHash); if (v == VERSION.ZERO && passwordHash.equals(getV0Hash(u.getId(), clearpass))) { setV1Password(u, clearpass); return true; } return false; } private void setV1Password (User u, String pass) throws BLException { assertNotNull(pass, "Invalid password"); byte[] clientSalt; byte[] serverSalt = genSalt(VERSION.ONE.getSalt().length); if (pass.startsWith("v1:")) { byte[] b = Base64.decode(u.getPassword()); clientSalt = new byte[VERSION.ONE.getSalt().length]; System.arraycopy (b, 1+clientSalt.length, clientSalt, 0, clientSalt.length); pass = pass.substring(3); } else { clientSalt = genSalt(VERSION.ONE.getSalt().length); pass = upgradeClearPassword(pass, clientSalt); } u.setPassword(genV1Hash(pass, serverSalt, clientSalt)); } private String genV1Hash(String password, byte[] salt, byte[] clientSalt) throws BLException { try { SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); int iterations = VERSION.ONE.getIterations(); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, 2048); return org.bouncycastle.util.encoders.Base64.toBase64String( Arrays.concatenate( new byte[]{VERSION.ONE.getVersion()}, VERSION.ONE.getSalt(salt), clientSalt, skf.generateSecret(spec).getEncoded()) ); } catch (Exception e) { throw new BLException (e.getLocalizedMessage()); } } private byte[] genV1ClientHash (String clearpass, byte[] seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); int iterations = VERSION.ONE.getIterations(); byte[] passAsBytes = clearpass.getBytes(StandardCharsets.UTF_8); for (int i=0; i<iterations; i++) { if (i % 7 == 0) md.update(seed); md.update(passAsBytes); } return md.digest(); } catch (NoSuchAlgorithmException e) { // should never happen, SHA-256 is a supported algorithm } return null; } // HELPER METHODS protected void assertNotNull (Object obj, String error) throws BLException { if (obj == null) throw new BLException (error); } protected void assertTrue (boolean condition, String error) throws BLException { if (!condition) throw new BLException (error); } public enum VERSION { UNKNOWN((byte)0xFF, 0, 0, 0, null), ZERO((byte)0, 0, 160, 40, null), ONE((byte) 1,100000,2048, 388, Base64.decode("K7f2dgQQHK5CW6Wz+CscUA==")); private byte version; private int iterations; private int keylength; private int encodedLength; private byte[] salt; VERSION(byte version, int iterations, int keylength, int encodedLength, byte[] salt) { this.version = version; this.iterations = iterations; this.keylength = keylength; this.encodedLength = encodedLength; this.salt = salt; } public byte getVersion() { return version; } public int getIterations() { return iterations; } public int getKeylength() { return keylength; } public int getEncodedLength() { return encodedLength; } public byte[] getSalt() { return ISOUtil.xor(salt, SystemSeed.getSeed(salt.length, salt.length)); } public byte[] getSalt(byte[] salt) { return ISOUtil.xor(salt, getSalt()); } public static VERSION getVersion (String hash) { for (VERSION v : VERSION.values()) { if (v.getEncodedLength() == hash.length()) return v; if (v != UNKNOWN && v != ZERO) { byte[] b = Base64.decode(hash); if (b[0] == v.getVersion()) return v; } } return UNKNOWN; } } }
package org.xwiki.test.integration.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Validate logs against default excludes/expected lines and those registered by the tests. * * @version $Id$ * @since 11.4RC1 */ public class LogCaptureValidator { private static final Logger LOGGER = LoggerFactory.getLogger(LogCaptureValidator.class); private static final String NL = "\n"; private static final List<String> SEARCH_STRINGS = Arrays.asList( "Deprecated usage of", "ERROR", "WARN", "JavaScript error"); private static final List<Line> GLOBAL_EXCLUDES = Arrays.asList( new Line("Could not validate integrity of download from file"), // Warning that can happen on Tomcat when the generation of the random takes a bit long to execute. // TODO: fix this so that it doesn't happen. It could mean that we're not using the right secure random // implementation and we're using a too slow one. new Line("Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took"), // Firefox Selenium Driver warning new Line("Marionette\tWARN"), new Line("Loading extension 'screenshots@mozilla.org': "), // The LibreOffice container outputs this error on startup. We should try to understand why it kills LO before // restarting it. new Line("Office process died with exit code 81; restarting it"), // When executing tests on PosgtreSQL we get the following errors when the hibernate upgrade code kicks in at // XWiki startup new Line("relation \"xwikidbversion\" does not exist at character 45"), new Line("relation \"xwikidoc\" does not exist at character 29"), new Line("relation \"hibernate_sequence\" already exists"), // Remove once "latest" image of the Jetty container doesn't have the issue anymore new Line("Unknown asm implementation version, assuming version"), // Note: Happens when verbose is turned on new Line("Collision between core extension [javax.annotation:javax.annotation-api"), new Line("MavenExtensionScanner - [javax.annotation:javax.annotation-api/"), new Line("Collision between core extension [javax.transaction:javax.transaction-api"), new Line("MavenExtensionScanner - [javax.transaction:javax.transaction-api/"), // Appears only for PostgreSQL database. new Line("WARNING: enabling \"trust\" authentication for local connections"), // Those errors appears from time to time, mainly on the CI, related to various JS resources such as: // jsTree, jQuery, keypress, xwiki-events-bridge, iScroll, etc. // This seems to be related to actions being performed before all the resources have been correctly loaded. new Line("require.min.js?r=1, line 7"), // Cannot reproduce locally but happened on the CI for MenuIT. new Line("jstree.min.js, line 2: TypeError: c is undefined"), new Line("Failed to save job status"), // When updating a collection Hibernate start by deleting the existing elements and HSQLDB complains when there // is actually nothing to delete it seems new Line("SQL Warning Code: -1100, SQLState: 02000"), new Line("no data"), new Line("SQL Error: -104, SQLState: 23505"), new Line("integrity constraint violation: unique constraint or index violation; SYS_PK_10260 table: XWIKILOCK"), new Line("Exception while setting up lock"), new Line("com.xpn.xwiki.XWikiException: Error number 13006 in 3: Exception while locking document for lock" + " [userName = [XWiki.superadmin], docId = [6152552094868048244]," + " date = [Tue Jun 18 12:21:51 CEST 2019]]"), new Line("Caused by: javax.persistence.PersistenceException:" + " org.hibernate.exception.ConstraintViolationException: could not execute statement"), new Line("Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement"), new Line("Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: " + "unique constraint or index violation; SYS_PK_10260 table: XWIKILOCK"), new Line("Caused by: org.hsqldb.HsqlException: integrity constraint violation:" + " unique constraint or index violation; SYS_PK_10260 table: XWIKILOCK"), // Solr brings since 8.1.1 jetty dependencies in the classloader, so the upgrade might warn about collisions new Line("Collision between core extension [org.eclipse.jetty:jetty-http"), new Line("MavenExtensionScanner - [org.eclipse.jetty:jetty-http"), new Line("Collision between core extension [org.eclipse.jetty:jetty-io"), new Line("MavenExtensionScanner - [org.eclipse.jetty:jetty-io"), new Line("Collision between core extension [org.eclipse.jetty:jetty-util"), new Line("MavenExtensionScanner - [org.eclipse.jetty:jetty-util"), // This warning is not coming from XWiki but from one jetty dependency, apparently a configuration is not // properly used on Solr part. More details can be found there: new Line("No Client EndPointIdentificationAlgorithm configured for SslContextFactory"), // Java 11 restriction on field access new Line("WARNING: An illegal reflective access operation has occurred"), new Line("WARNING: Illegal reflective access by "), new Line("WARNING: Please consider reporting this to the maintainers of"), new Line("WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective " + "access operations"), new Line("WARNING: All illegal access operations will be denied in a future release") ); private static final List<Line> GLOBAL_EXPECTED = Arrays.asList( // Broken pipes can happen when the browser moves away from the current page and there are unfinished // queries happening on the server side. These are normal errors that can happen for normal users too and // we shouldn't consider them faults. new Line("Caused by: java.io.IOException: Broken pipe"), // Warning coming from the XWikiDockerExtension when in verbose mode (which is our default on the CI) new Line("Failure when attempting to lookup auth config") ); private static final StackTraceLogParser LOG_PARSER = new StackTraceLogParser(); /** * @param logContent the log content to validate * @param configuration the user-registered excludes and expected log lines */ public void validate(String logContent, LogCaptureConfiguration configuration) { List<Line> allExcludes = new ArrayList<>(); allExcludes.addAll(GLOBAL_EXCLUDES); allExcludes.addAll(configuration.getExcludedLines()); List<Line> allExpected = new ArrayList<>(); allExpected.addAll(GLOBAL_EXPECTED); allExpected.addAll(configuration.getExpectedLines()); List<String> matchingExcludes = new ArrayList<>(); List<Line> matchingDefinitions = new ArrayList<>(); List<String> matchingLines = LOG_PARSER.parse(logContent).stream() .filter(p -> { for (String searchString : SEARCH_STRINGS) { if (p.contains(searchString)) { return true; } } return false; }) .filter(p -> { for (Line excludedLine : allExcludes) { if (isMatching(p, excludedLine)) { matchingExcludes.add(p); matchingDefinitions.add(excludedLine); return false; } } for (Line expectedLine : allExpected) { if (isMatching(p, expectedLine)) { matchingDefinitions.add(expectedLine); return false; } } return true; }) .collect(Collectors.toList()); // At the end of the tests, output warnings for matching excluded lines so that developers can see that // there are excludes that need to be fixed. if (!matchingExcludes.isEmpty()) { LOGGER.warn("The following lines were matching excluded patterns and need to be fixed: [\n{}\n]", StringUtils.join(matchingExcludes, NL)); } // Also display not matching excludes and expected so that developers can notice them and realize that the // issues that existed might have been fixed. Note however that currently we can't have exclude/expected by // configuration (for Docker-based tests) and thus it's possible that there are non matching excludes/expected // simply because they exist only in a different configuration. displayMissingWarning(configuration.getExcludedLines(), matchingDefinitions, "excludes"); displayMissingWarning(configuration.getExpectedLines(), matchingDefinitions, "expected"); // Fail the test if there are matching lines that have no exclude or no expected. if (!matchingLines.isEmpty()) { throw new AssertionError(String.format("The following lines were matching forbidden content:[\n%s\n]", matchingLines.stream().collect(Collectors.joining(NL)))); } } private void displayMissingWarning(List<Line> definitions, List<Line> matchingDefinitions, String missingType) { List<String> notMatchingLines = new ArrayList<>(); for (Line line : definitions) { if (!matchingDefinitions.contains(line)) { notMatchingLines.add(line.getContent()); } } if (!notMatchingLines.isEmpty()) { LOGGER.warn("The following {} were not matched and could be candidates for removal " + "(beware of configs): [\n{}\n]", missingType, StringUtils.join(notMatchingLines, NL)); } } private boolean isMatching(String lineToMatch, Line line) { return (line.isRegex() && lineToMatch.matches(line.getContent())) || (!line.isRegex() && lineToMatch.contains(line.getContent())); } }
package org.xwiki.rendering.internal.parser.wikimodel; import java.io.StringReader; import org.xwiki.rendering.listener.InlineFilterListener; import org.xwiki.rendering.listener.Listener; import org.xwiki.rendering.listener.WrappingListener; import org.xwiki.rendering.parser.ParseException; import org.xwiki.rendering.parser.StreamParser; import org.xwiki.rendering.util.ParserUtils; /** * Methods for helping in parsing. * * @version $Id$ * @since 1.8M1 */ public class WikiModelParserUtils extends ParserUtils { public void parseInline(StreamParser parser, String content, Listener listener) throws ParseException { parseInline(parser, content, listener, false); } /** * @since 6.0RC1 * @since 5.4.5 */ public void parseInline(StreamParser parser, String content, Listener listener, boolean prefix) throws ParseException { if (prefix) { WrappingListener inlineFilterListener = new InlineFilterListener() { private boolean foundWord = false; private boolean foundSpace = false; @Override public void onWord(String word) { if (this.foundWord) { super.onWord(word); } else { this.foundWord = true; } } @Override public void onSpace() { if (this.foundSpace) { super.onSpace(); } else { this.foundSpace = true; } } }; inlineFilterListener.setWrappedListener(listener); parser.parse(new StringReader("wikimarker " + content), inlineFilterListener); } else { WrappingListener inlineFilterListener = new InlineFilterListener(); inlineFilterListener.setWrappedListener(listener); parser.parse(new StringReader(content), inlineFilterListener); } } }
package org.openhab.binding.zwave.internal.protocol.commandclass; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.ZWaveSerialMessageException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamOmitField; /** * Handles the protection command class. * * @author Chris Jackson */ @XStreamAlias("protectionCommandClass") public class ZWaveProtectionCommandClass extends ZWaveCommandClass { @XStreamOmitField private static final Logger logger = LoggerFactory.getLogger(ZWaveProtectionCommandClass.class); private static final int PROTECTION_SET = 1; private static final int PROTECTION_GET = 2; private static final int PROTECTION_REPORT = 3; /** * Creates a new instance of the ZWaveProtectionCommandClass class. * * @param node the node this command class belongs to * @param controller the controller to use * @param endpoint the endpoint this Command class belongs to */ public ZWaveProtectionCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) { super(node, controller, endpoint); } /** * {@inheritDoc} */ @Override public CommandClass getCommandClass() { return CommandClass.PROTECTION; } /** * {@inheritDoc} * * @throws ZWaveSerialMessageException */ @Override public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint) throws ZWaveSerialMessageException { logger.debug("NODE {}: Received protection command (v{})", this.getNode().getNodeId(), this.getVersion()); int command = serialMessage.getMessagePayloadByte(offset); switch (command) { default: logger.warn(String.format("NODE %d: Unsupported Command %d for command class %s (0x%02X).", this.getNode().getNodeId(), command, this.getCommandClass().getLabel(), this.getCommandClass().getKey())); } } }
package ru.job4j.map; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; public class User { private String name; private int children; private Calendar birthday; public User(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + children; result = 31 * result + (birthday != null ? birthday.hashCode() : 0); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (children != user.children) return false; if (name != null ? !name.equals(user.name) : user.name != null) return false; return birthday != null ? birthday.equals(user.birthday) : user.birthday == null; } public static void main(String[] args) { User first = new User("Ivan", 1, new GregorianCalendar(1980, Calendar.NOVEMBER, 15)); User second = new User("Ivan", 1, new GregorianCalendar(1980, Calendar.NOVEMBER, 15)); Map<User, Object> map = new HashMap<>(); map.put(first, "first"); map.put(second, "second"); System.out.println(map); } }
package org.codehaus.groovy.syntax.parser; import java.io.IOException; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.TokenStream; import org.codehaus.groovy.syntax.lexer.Lexer; import org.codehaus.groovy.syntax.lexer.LexerTokenStream; import org.codehaus.groovy.syntax.lexer.StringCharStream; public class Parser { private static final int[] identifierTokens = { Token.IDENTIFIER, Token.KEYWORD_CLASS, Token.KEYWORD_DEF }; private TokenStream tokenStream; private boolean lastTokenStatementSeparator; public Parser(TokenStream tokenStream) { this.tokenStream = tokenStream; } public TokenStream getTokenStream() { return this.tokenStream; } public void optionalSemicolon() throws IOException, SyntaxException { while (lt_bare() == Token.SEMICOLON || lt_bare() == Token.NEWLINE) { consume_bare(lt_bare()); } } public void optionalNewlines() throws IOException, SyntaxException { while (lt_bare() == Token.NEWLINE) { consume_bare(lt_bare()); } } public CSTNode compilationUnit() throws IOException, SyntaxException { CSTNode compilationUnit = new CSTNode(); CSTNode packageDeclaration = null; if (lt() == Token.KEYWORD_PACKAGE) { packageDeclaration = packageDeclaration(); optionalSemicolon(); } else { packageDeclaration = new CSTNode(Token.keyword(-1, -1, "package")); packageDeclaration.addChild(new CSTNode()); } compilationUnit.addChild(packageDeclaration); CSTNode imports = new CSTNode(); compilationUnit.addChild(imports); while (lt() == Token.KEYWORD_IMPORT) { imports.addChild(importStatement()); optionalSemicolon(); } while (lt() != -1) { compilationUnit.addChild(typeDeclaration()); } return compilationUnit; } public CSTNode packageDeclaration() throws IOException, SyntaxException { CSTNode packageDeclaration = rootNode(Token.KEYWORD_PACKAGE); CSTNode cur = rootNode(Token.IDENTIFIER); while (lt() == Token.DOT) { CSTNode dot = rootNode(Token.DOT, cur); consume(dot, Token.IDENTIFIER); cur = dot; } packageDeclaration.addChild(cur); return packageDeclaration; } public CSTNode importStatement() throws IOException, SyntaxException { CSTNode importStatement = rootNode(Token.KEYWORD_IMPORT); CSTNode cur = rootNode(Token.IDENTIFIER); while (lt() == Token.DOT) { CSTNode dot = rootNode(Token.DOT, cur); consume(dot, Token.IDENTIFIER); cur = dot; } importStatement.addChild(cur); if (lt() == Token.KEYWORD_AS) { CSTNode as = rootNode(Token.KEYWORD_AS); consume(as, Token.IDENTIFIER); importStatement.addChild(as); } else { importStatement.addChild(new CSTNode()); } return importStatement; } public CSTNode typeDeclaration() throws IOException, SyntaxException { CSTNode declaration = null; CSTNode modifiers = new CSTNode(); if (lt() == Token.KEYWORD_DEF) { consume(lt()); while (isModifier(lt())) { consume(modifiers, lt()); } CSTNode type = methodReturnType(); CSTNode identifier = methodIdentifier(); return methodDeclaration(modifiers, type, identifier); } while (isModifier(lt())) { consume(modifiers, lt()); } switch (lt()) { case (Token.KEYWORD_CLASS) : { declaration = classDeclaration(modifiers); break; } case (Token.KEYWORD_INTERFACE) : { declaration = interfaceDeclaration(modifiers); break; } default : { declaration = statement(); /* throwExpected( new int[] { Token.KEYWORD_CLASS, Token.KEYWORD_INTERFACE } ); */ } } return declaration; } public CSTNode classDeclaration(CSTNode modifiers) throws IOException, SyntaxException { CSTNode classDeclaration = rootNode(Token.KEYWORD_CLASS); classDeclaration.addChild(modifiers); consume(classDeclaration, Token.IDENTIFIER); if (lt() == Token.KEYWORD_EXTENDS) { CSTNode extendsNode = rootNode(Token.KEYWORD_EXTENDS); classDeclaration.addChild(extendsNode); CSTNode datatype = datatype(); extendsNode.addChild(datatype); } else { classDeclaration.addChild(new CSTNode()); } if (lt() == Token.KEYWORD_IMPLEMENTS) { CSTNode implementsNode = rootNode(Token.KEYWORD_IMPLEMENTS); classDeclaration.addChild(implementsNode); CSTNode datatype = datatype(); implementsNode.addChild(datatype); while (lt() == Token.COMMA) { consume(Token.COMMA); datatype = datatype(); implementsNode.addChild(datatype); } } else { classDeclaration.addChild(new CSTNode()); } consume(Token.LEFT_CURLY_BRACE); CSTNode body = new CSTNode(); classDeclaration.addChild(body); BODY_LOOP : while (true) { switch (lt()) { case (-1) : { break BODY_LOOP; } case (Token.RIGHT_CURLY_BRACE) : { break BODY_LOOP; } default : { body.addChild(bodyStatement()); } } } consume(Token.RIGHT_CURLY_BRACE); return classDeclaration; } public CSTNode interfaceDeclaration(CSTNode modifiers) throws IOException, SyntaxException { CSTNode interfaceDeclaration = rootNode(Token.KEYWORD_INTERFACE); interfaceDeclaration.addChild(modifiers); consume(interfaceDeclaration, Token.IDENTIFIER); interfaceDeclaration.addChild(new CSTNode()); if (lt() == Token.KEYWORD_EXTENDS) { CSTNode extendsNode = rootNode(Token.KEYWORD_EXTENDS); interfaceDeclaration.addChild(extendsNode); CSTNode datatype = datatype(); extendsNode.addChild(datatype); while (lt() == Token.COMMA) { consume(Token.COMMA); datatype = datatype(); extendsNode.addChild(datatype); } } consume(Token.LEFT_CURLY_BRACE); consume(Token.RIGHT_CURLY_BRACE); return interfaceDeclaration; } public CSTNode bodyStatement() throws IOException, SyntaxException { CSTNode bodyStatement = null; CSTNode modifiers = new CSTNode(); while (isModifier(lt())) { consume(modifiers, lt()); } // lets consume a property keyword until we deprecate it if (lt() == Token.KEYWORD_PROPERTY) { consume(lt()); } // lets consume any newlines while (lt_bare() == Token.NEWLINE) { consume_bare(lt_bare()); } CSTNode type = methodReturnType(); CSTNode identifier = methodIdentifier(); // now we must be either a property or method // not that after the identifier, the left parenthesis *must* be on the same line switch (lt_bare()) { case Token.LEFT_PARENTHESIS : bodyStatement = methodDeclaration(modifiers, type, identifier); break; case Token.EQUAL : case Token.SEMICOLON : case Token.NEWLINE : case Token.RIGHT_CURLY_BRACE : case -1 : bodyStatement = propertyDeclaration(modifiers, type, identifier); optionalSemicolon(); break; default : throwExpected( new int[] { Token.LEFT_PARENTHESIS, Token.EQUAL, Token.SEMICOLON, Token.NEWLINE, Token.RIGHT_CURLY_BRACE }); } return bodyStatement; } protected CSTNode methodIdentifier() throws IOException, SyntaxException { return new CSTNode(consume_bare(Token.IDENTIFIER)); } protected CSTNode methodReturnType() throws IOException, SyntaxException { // lets consume the type if present // either an identifier, void or foo.bar.whatnot CSTNode type = new CSTNode(); if (lt_bare() == Token.IDENTIFIER) { // could be method name or could be part of datatype switch (lt_bare(2)) { case Token.DOT : { // has datatype type = datatype(); break; } case (Token.IDENTIFIER) : { type = new CSTNode(consume_bare(lt())); break; } } } else { switch (lt_bare()) { case (Token.KEYWORD_VOID) : case (Token.KEYWORD_INT) : case (Token.KEYWORD_FLOAT) : case (Token.KEYWORD_DOUBLE) : case (Token.KEYWORD_CHAR) : case (Token.KEYWORD_BYTE) : case (Token.KEYWORD_SHORT) : case (Token.KEYWORD_LONG) : case (Token.KEYWORD_BOOLEAN) : { type = new CSTNode(consume_bare(lt_bare())); } } } return type; } public CSTNode propertyDeclaration(CSTNode modifiers, CSTNode type, CSTNode identifier) throws IOException, SyntaxException { CSTNode propertyDeclaration = new CSTNode(Token.keyword(-1, -1, "property")); propertyDeclaration.addChild(modifiers); propertyDeclaration.addChild(identifier); propertyDeclaration.addChild(type); if (lt() == Token.EQUAL) { consume(lt()); propertyDeclaration.addChild(expression()); } return propertyDeclaration; } public CSTNode methodDeclaration(CSTNode modifiers, CSTNode type, CSTNode identifier) throws IOException, SyntaxException { CSTNode methodDeclaration = new CSTNode(Token.syntheticMethod()); methodDeclaration.addChild(modifiers); methodDeclaration.addChild(identifier); methodDeclaration.addChild(type); CSTNode paramsRoot = rootNode(Token.LEFT_PARENTHESIS); methodDeclaration.addChild(paramsRoot); while (lt() != Token.RIGHT_PARENTHESIS) { switch (lt(2)) { case (Token.DOT) : case (Token.IDENTIFIER) : case (Token.LEFT_SQUARE_BRACKET) : { type = datatype(); break; } default : { type = new CSTNode(); } } CSTNode param = new CSTNode(); paramsRoot.addChild(param); consume(param, Token.IDENTIFIER); param.addChild(type); if (lt() == Token.COMMA) { consume(Token.COMMA); } } consume(Token.RIGHT_PARENTHESIS); methodDeclaration.addChild(statementBlock()); return methodDeclaration; } protected CSTNode parameterDeclarationList() throws IOException, SyntaxException { CSTNode parameterDeclarationList = new CSTNode(); while (lt() == Token.IDENTIFIER || lt() == Token.KEYWORD_BOOLEAN || lt() == Token.KEYWORD_BYTE || lt() == Token.KEYWORD_CHAR || lt() == Token.KEYWORD_DOUBLE || lt() == Token.KEYWORD_FLOAT || lt() == Token.KEYWORD_INT || lt() == Token.KEYWORD_LONG || lt() == Token.KEYWORD_SHORT) { parameterDeclarationList.addChild(parameterDeclaration()); if (lt() == Token.COMMA) { consume(Token.COMMA); } else { break; } } return parameterDeclarationList; } protected CSTNode parameterDeclaration() throws IOException, SyntaxException { CSTNode parameterDeclaration = null; // TODO: deal with array declarations // { int a[] switch (lt(2)) { case (Token.IDENTIFIER) : case (Token.LEFT_SQUARE_BRACKET) : case (Token.DOT) : { parameterDeclaration = parameterDeclarationWithDatatype(); break; } default : { parameterDeclaration = parameterDeclarationWithoutDatatype(); break; } } return parameterDeclaration; } protected CSTNode parameterDeclarationWithDatatype() throws IOException, SyntaxException { CSTNode parameterDeclaration = new CSTNode(Token.syntheticParameterDeclaration()); CSTNode datatype = datatype(); parameterDeclaration.addChild(datatype); consume(parameterDeclaration, Token.IDENTIFIER); return parameterDeclaration; } protected CSTNode parameterDeclarationWithoutDatatype() throws IOException, SyntaxException { CSTNode parameterDeclaration = new CSTNode(Token.syntheticParameterDeclaration()); consume(parameterDeclaration, Token.IDENTIFIER); parameterDeclaration.addChild(new CSTNode()); return parameterDeclaration; } protected CSTNode datatype() throws IOException, SyntaxException { CSTNode datatype = datatypeWithoutArray(); if (datatype != null) { if (lt_bare() == Token.LEFT_SQUARE_BRACKET && lt_bare(2) == Token.RIGHT_SQUARE_BRACKET) { CSTNode newRoot = new CSTNode(Token.leftSquareBracket(-1, -1)); newRoot.addChild(datatype); datatype = newRoot; //datatype = rootNode( Token.LEFT_SQUARE_BRACKET, datatype ); consume_bare(datatype, Token.LEFT_SQUARE_BRACKET); consume_bare(Token.RIGHT_SQUARE_BRACKET); } } return datatype; } protected CSTNode datatypeWithoutArray() throws IOException, SyntaxException { CSTNode datatype = null; switch (lt()) { case (Token.KEYWORD_VOID) : case (Token.KEYWORD_INT) : case (Token.KEYWORD_FLOAT) : case (Token.KEYWORD_DOUBLE) : case (Token.KEYWORD_CHAR) : case (Token.KEYWORD_BYTE) : case (Token.KEYWORD_SHORT) : case (Token.KEYWORD_LONG) : case (Token.KEYWORD_BOOLEAN) : { datatype = rootNode(lt()); break; } default : { datatype = rootNode(Token.IDENTIFIER); while (lt() == Token.DOT) { CSTNode dot = rootNode(Token.DOT, datatype); consume(dot, Token.IDENTIFIER); datatype = dot; } } } return datatype; } protected CSTNode statementOrStatementBlock() throws IOException, SyntaxException { if (la().getType() == Token.LEFT_CURLY_BRACE) { return statementBlock(); } else { return statement(); } } protected CSTNode statementBlock() throws IOException, SyntaxException { CSTNode statementBlock = rootNode(Token.LEFT_CURLY_BRACE); statementsUntilRightCurly(statementBlock); consume(Token.RIGHT_CURLY_BRACE); return statementBlock; } protected void statementsUntilRightCurly(CSTNode root) throws IOException, SyntaxException { while (lt() != Token.RIGHT_CURLY_BRACE) { root.addChild(statement()); if (lt_bare() == Token.RIGHT_CURLY_BRACE) { break; } else { optionalSemicolon(); if (lt_bare() == -1) { throwExpected(new int[] { Token.RIGHT_CURLY_BRACE }); } if (!lastTokenStatementSeparator) { throwExpected(new int[] { Token.NEWLINE, Token.SEMICOLON, Token.RIGHT_CURLY_BRACE }); } } } } protected CSTNode statement() throws IOException, SyntaxException { CSTNode statement = null; switch (lt()) { case (Token.KEYWORD_FOR) : { statement = forStatement(); break; } case (Token.KEYWORD_WHILE) : { statement = whileStatement(); break; } case (Token.KEYWORD_DO) : { statement = doWhileStatement(); break; } case (Token.KEYWORD_CONTINUE) : { statement = continueStatement(); break; } case (Token.KEYWORD_BREAK) : { statement = breakStatement(); break; } case (Token.KEYWORD_IF) : { statement = ifStatement(); break; } case (Token.KEYWORD_TRY) : { statement = tryStatement(); break; } case (Token.KEYWORD_THROW) : { statement = throwStatement(); break; } case (Token.KEYWORD_SYNCHRONIZED) : { statement = synchronizedStatement(); break; } case (Token.KEYWORD_SWITCH) : { statement = switchStatement(); break; } case (Token.KEYWORD_RETURN) : { statement = returnStatement(); optionalSemicolon(); break; } case (Token.KEYWORD_ASSERT) : { statement = assertStatement(); optionalSemicolon(); break; } default : { statement = expression(); optionalSemicolon(); } } return statement; } protected CSTNode switchStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_SWITCH); consume(Token.LEFT_PARENTHESIS); statement.addChild(expression()); consume(Token.RIGHT_PARENTHESIS); consume(Token.LEFT_CURLY_BRACE); while (lt() == Token.KEYWORD_CASE) { CSTNode caseBlock = rootNode(Token.KEYWORD_CASE); caseBlock.addChild(expression()); consume(Token.COLON); while (lt() != Token.RIGHT_CURLY_BRACE && lt() != Token.KEYWORD_CASE && lt() != Token.KEYWORD_DEFAULT) { caseBlock.addChild(statement()); if (lt() == Token.RIGHT_CURLY_BRACE) { break; } else if (lt() == -1) { throwExpected(new int[] { Token.RIGHT_CURLY_BRACE }); } } statement.addChild(caseBlock); } if (lt() == Token.KEYWORD_DEFAULT) { CSTNode caseBlock = rootNode(Token.KEYWORD_DEFAULT); consume(Token.COLON); while (lt() != Token.RIGHT_CURLY_BRACE) { caseBlock.addChild(statement()); if (lt() == Token.RIGHT_CURLY_BRACE) { break; } else if (lt() == -1) { throwExpected(new int[] { Token.RIGHT_CURLY_BRACE }); } } statement.addChild(caseBlock); } consume(Token.RIGHT_CURLY_BRACE); return statement; } protected CSTNode breakStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_BREAK); if (lt() == Token.IDENTIFIER) { statement.addChild(rootNode(lt())); } optionalSemicolon(); return statement; } protected CSTNode continueStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_CONTINUE); if (lt() == Token.IDENTIFIER) { statement.addChild(rootNode(lt())); } optionalSemicolon(); return statement; } protected CSTNode throwStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_THROW); statement.addChild(expression()); return statement; } protected CSTNode synchronizedStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_SYNCHRONIZED); statement.addChild(expression()); statement.addChild(statementBlock()); return statement; } protected CSTNode ifStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_IF); consume(Token.LEFT_PARENTHESIS); statement.addChild(expression()); consume(Token.RIGHT_PARENTHESIS); statement.addChild(statementOrStatementBlock()); CSTNode cur = statement; while (lt() == Token.KEYWORD_ELSE && lt(2) == Token.KEYWORD_IF) { consume(Token.KEYWORD_ELSE); CSTNode next = ifStatement(); cur.addChild(next); cur = next; } if (lt() == Token.KEYWORD_ELSE) { CSTNode next = rootNode(Token.KEYWORD_ELSE); next.addChild(statementOrStatementBlock()); cur.addChild(next); } return statement; } protected CSTNode tryStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_TRY); statement.addChild(statementBlock()); CSTNode catches = new CSTNode(); while (lt() == Token.KEYWORD_CATCH) { CSTNode catchBlock = rootNode(Token.KEYWORD_CATCH); consume(Token.LEFT_PARENTHESIS); catchBlock.addChild(datatype()); consume(catchBlock, Token.IDENTIFIER); consume(Token.RIGHT_PARENTHESIS); catchBlock.addChild(statementBlock()); catches.addChild(catchBlock); } if (lt() == Token.KEYWORD_FINALLY) { consume(Token.KEYWORD_FINALLY); statement.addChild(statementBlock()); } else { statement.addChild(new CSTNode()); } statement.addChild(catches); return statement; } protected CSTNode returnStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_RETURN); statement.addChild(expression()); return statement; } protected CSTNode whileStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_WHILE); consume(Token.LEFT_PARENTHESIS); statement.addChild(expression()); consume(Token.RIGHT_PARENTHESIS); statement.addChild(statementOrStatementBlock()); return statement; } protected CSTNode doWhileStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_DO); statement.addChild(statementOrStatementBlock()); consume(Token.KEYWORD_WHILE); consume(Token.LEFT_PARENTHESIS); statement.addChild(expression()); consume(Token.RIGHT_PARENTHESIS); return statement; } protected CSTNode forStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_FOR); consume(Token.LEFT_PARENTHESIS); consume(statement, Token.IDENTIFIER); Token potentialIn = consume(Token.IDENTIFIER); if (!potentialIn.getText().equals("in")) { throw new UnexpectedTokenException(potentialIn, new int[] { }); } CSTNode expr = expression(); statement.addChild(expr); consume(Token.RIGHT_PARENTHESIS); statement.addChild(statementOrStatementBlock()); return statement; } protected CSTNode assertStatement() throws IOException, SyntaxException { CSTNode statement = rootNode(Token.KEYWORD_ASSERT); statement.addChild(ternaryExpression()); if (lt() == Token.COLON) { consume(Token.COLON); statement.addChild(expression()); } else { statement.addChild(new CSTNode()); } return statement; } protected CSTNode expression() throws IOException, SyntaxException { optionalNewlines(); return assignmentExpression(); } protected CSTNode assignmentExpression() throws IOException, SyntaxException { CSTNode expr = null; if (lt_bare() == Token.IDENTIFIER && lt_bare(2) == Token.IDENTIFIER && lt_bare(3) == Token.EQUAL) { // a typed variable declaration CSTNode typeExpr = new CSTNode(consume_bare(lt_bare())); expr = new CSTNode(consume_bare(lt_bare())); expr.addChild(typeExpr); } else { expr = ternaryExpression(); } switch (lt_bare()) { case (Token.EQUAL) : case (Token.PLUS_EQUAL) : case (Token.MINUS_EQUAL) : case (Token.DIVIDE_EQUAL) : case (Token.MULTIPLY_EQUAL) : case (Token.MOD_EQUAL) : { expr = rootNode(lt_bare(), expr); optionalNewlines(); expr.addChild(ternaryExpression()); break; } } return expr; } protected CSTNode ternaryExpression() throws IOException, SyntaxException { CSTNode expr = logicalOrExpression(); if (lt_bare() == Token.QUESTION) { expr = rootNode(Token.QUESTION, expr); optionalNewlines(); expr.addChild(assignmentExpression()); optionalNewlines(); consume(Token.COLON); optionalNewlines(); expr.addChild(ternaryExpression()); } return expr; } protected CSTNode logicalOrExpression() throws IOException, SyntaxException { CSTNode expr = logicalAndExpression(); while (lt_bare() == Token.LOGICAL_OR) { expr = rootNode(Token.LOGICAL_OR, expr); optionalNewlines(); expr.addChild(logicalAndExpression()); } return expr; } protected CSTNode logicalAndExpression() throws IOException, SyntaxException { CSTNode expr = equalityExpression(); while (lt_bare() == Token.LOGICAL_AND) { expr = rootNode(Token.LOGICAL_AND, expr); optionalNewlines(); expr.addChild(equalityExpression()); } return expr; } protected CSTNode equalityExpression() throws IOException, SyntaxException { CSTNode expr = relationalExpression(); switch (lt_bare()) { case (Token.COMPARE_EQUAL) : case (Token.COMPARE_NOT_EQUAL) : case (Token.COMPARE_IDENTICAL) : { expr = rootNode(lt_bare(), expr); optionalNewlines(); expr.addChild(relationalExpression()); break; } } return expr; } protected CSTNode relationalExpression() throws IOException, SyntaxException { CSTNode expr = rangeExpression(); switch (lt_bare()) { case (Token.COMPARE_LESS_THAN) : case (Token.COMPARE_LESS_THAN_EQUAL) : case (Token.COMPARE_GREATER_THAN) : case (Token.COMPARE_GREATER_THAN_EQUAL) : case (Token.FIND_REGEX) : case (Token.MATCH_REGEX) : case (Token.KEYWORD_INSTANCEOF) : { expr = rootNode(lt_bare(), expr); optionalNewlines(); expr.addChild(rangeExpression()); break; } } return expr; } protected CSTNode rangeExpression() throws IOException, SyntaxException { CSTNode expr = additiveExpression(); if (lt_bare() == Token.DOT_DOT) { expr = rootNode(Token.DOT_DOT, expr); optionalNewlines(); expr.addChild(additiveExpression()); } else if (lt_bare() == Token.DOT_DOT_DOT) { expr = rootNode(Token.DOT_DOT_DOT, expr); optionalNewlines(); expr.addChild(additiveExpression()); } return expr; } protected CSTNode additiveExpression() throws IOException, SyntaxException { CSTNode expr = multiplicativeExpression(); LOOP : while (true) { SWITCH : switch (lt_bare()) { case (Token.PLUS) : case (Token.MINUS) : case (Token.LEFT_SHIFT) : case (Token.RIGHT_SHIFT) : { expr = rootNode(lt_bare(), expr); optionalNewlines(); expr.addChild(multiplicativeExpression()); break SWITCH; } default : { break LOOP; } } } return expr; } protected CSTNode multiplicativeExpression() throws IOException, SyntaxException { CSTNode expr = unaryExpression(); LOOP : while (true) { SWITCH : switch (lt_bare()) { case (Token.MULTIPLY) : case (Token.DIVIDE) : case (Token.MOD) : case (Token.COMPARE_TO) : { expr = rootNode(lt_bare(), expr); optionalNewlines(); expr.addChild(unaryExpression()); break SWITCH; } default : { break LOOP; } } } return expr; } protected CSTNode unaryExpression() throws IOException, SyntaxException { CSTNode expr = null; switch (lt_bare()) { case (Token.MINUS) : case (Token.NOT) : case (Token.PLUS) : { expr = rootNode(lt_bare()); expr.addChild(postfixExpression()); break; } case (Token.PLUS_PLUS) : case (Token.MINUS_MINUS) : { expr = new CSTNode(Token.syntheticPrefix()); CSTNode prefixExpr = rootNode(lt_bare()); expr.addChild(prefixExpr); prefixExpr.addChild(primaryExpression()); break; } default : { expr = postfixExpression(); break; } } return expr; } protected CSTNode postfixExpression() throws IOException, SyntaxException { CSTNode expr = primaryExpression(); Token laToken = la(); if (laToken != null) { switch (laToken.getType()) { case (Token.PLUS_PLUS) : case (Token.MINUS_MINUS) : { CSTNode primaryExpr = expr; expr = new CSTNode(Token.syntheticPostfix()); expr.addChild(rootNode(lt_bare(), primaryExpr)); } } } return expr; } protected CSTNode primaryExpression() throws IOException, SyntaxException { CSTNode expr = null; CSTNode identifier = null; PREFIX_SWITCH : switch (lt_bare()) { case (Token.KEYWORD_TRUE) : case (Token.KEYWORD_FALSE) : case (Token.KEYWORD_NULL) : { expr = rootNode(lt_bare()); break PREFIX_SWITCH; } case (Token.KEYWORD_NEW) : { expr = newExpression(); break PREFIX_SWITCH; } case (Token.LEFT_PARENTHESIS) : { expr = parentheticalExpression(); break PREFIX_SWITCH; } case (Token.INTEGER_NUMBER) : case (Token.FLOAT_NUMBER) : case (Token.SINGLE_QUOTE_STRING) : { expr = rootNode(lt_bare()); break PREFIX_SWITCH; } case (Token.DOUBLE_QUOTE_STRING) : { expr = doubleQuotedString(); break PREFIX_SWITCH; } case (Token.LEFT_SQUARE_BRACKET) : { expr = listOrMapExpression(); break PREFIX_SWITCH; } case (Token.LEFT_CURLY_BRACE) : { expr = closureExpression(); break PREFIX_SWITCH; } case (Token.KEYWORD_THIS) : { expr = thisExpression(); identifier = rootNode(lt_bare()); break PREFIX_SWITCH; } case (Token.KEYWORD_SUPER) : { expr = new CSTNode(Token.keyword(-1, -1, "super")); identifier = rootNode(lt_bare()); break PREFIX_SWITCH; } case (Token.PATTERN_REGEX) : { expr = regexPattern(); break PREFIX_SWITCH; } default : { expectIdentifier(); Token token = consume(lt_bare()); identifier = new CSTNode(Token.identifier(token.getStartLine(), token.getStartColumn(), token.getText())); expr = identifier; break PREFIX_SWITCH; } } if (identifier != null) { if (lt_bare() == Token.LEFT_PARENTHESIS || lt_bare() == Token.LEFT_CURLY_BRACE) { if (expr == identifier) { CSTNode replacementExpr = new CSTNode(); CSTNode resultExpr = sugaryMethodCallExpression(replacementExpr, identifier, null); if (resultExpr != replacementExpr) { expr = resultExpr; } } else { expr = sugaryMethodCallExpression(expr, identifier, null); } } else { CSTNode methodCall = tryParseMethodCallWithoutParenthesis(thisExpression(), identifier); if (methodCall != null) { expr = methodCall; } } } while (lt_bare() == Token.LEFT_SQUARE_BRACKET || lookAheadForMethodCall()) { if (lt_bare() == Token.LEFT_SQUARE_BRACKET) { expr = subscriptExpression(expr); } else { expr = methodCallOrPropertyExpression(expr); } } return expr; } protected CSTNode thisExpression() { return new CSTNode(Token.keyword(-1, -1, "this")); } protected CSTNode subscriptExpression(CSTNode expr) throws SyntaxException, IOException { expr = rootNode_bare(lt_bare(), expr); optionalNewlines(); CSTNode rangeExpr = rangeExpression(); // lets support the list notation inside subscript operators if (lt_bare() != Token.COMMA) { expr.addChild(rangeExpr); } else { consume_bare(Token.COMMA); CSTNode listExpr = new CSTNode(Token.syntheticList()); expr.addChild(listExpr); listExpr.addChild(rangeExpr); while (true) { optionalNewlines(); listExpr.addChild(rangeExpression()); if (lt_bare() == Token.COMMA) { consume_bare(Token.COMMA); } else { break; } } } optionalNewlines(); consume(Token.RIGHT_SQUARE_BRACKET); return expr; } protected CSTNode methodCallOrPropertyExpression(CSTNode expr) throws SyntaxException, IOException { CSTNode dotExpr = rootNode_bare(lt_bare()); CSTNode identifier = rootNode_bare(lt_bare()); switch (lt_bare()) { case (Token.LEFT_PARENTHESIS) : case (Token.LEFT_CURLY_BRACE) : { expr = sugaryMethodCallExpression(expr, identifier, dotExpr); break; } default : { // lets try parse a method call CSTNode methodCall = tryParseMethodCallWithoutParenthesis(expr, identifier); if (methodCall != null) { expr = methodCall; } else { dotExpr.addChild(expr); dotExpr.addChild(identifier); expr = dotExpr; } break; } } return expr; } protected CSTNode sugaryMethodCallExpression(CSTNode expr, CSTNode identifier, CSTNode dotExpr) throws IOException, SyntaxException { CSTNode methodExpr = null; CSTNode paramList = null; if (lt_bare() == Token.LEFT_PARENTHESIS) { methodExpr = rootNode_bare(Token.LEFT_PARENTHESIS); optionalNewlines(); methodExpr.addChild(expr); methodExpr.addChild(identifier); paramList = parameterList(Token.RIGHT_PARENTHESIS); methodExpr.addChild(paramList); optionalNewlines(); consume_bare(Token.RIGHT_PARENTHESIS); } if (lt_bare() == Token.LEFT_CURLY_BRACE) { if (methodExpr == null) { methodExpr = new CSTNode(Token.leftParenthesis(-1, -1)); methodExpr.addChild(expr); methodExpr.addChild(identifier); paramList = parameterList(Token.LEFT_CURLY_BRACE); methodExpr.addChild(paramList); } paramList.addChild(closureExpression()); } if (methodExpr != null) { expr = methodExpr; if (dotExpr != null) { expr.addChild(dotExpr); } } return expr; } protected CSTNode tryParseMethodCallWithoutParenthesis(CSTNode expr, CSTNode identifier) throws SyntaxException, IOException { switch (lt_bare()) { case Token.IDENTIFIER : case Token.DOUBLE_QUOTE_STRING : case Token.SINGLE_QUOTE_STRING : case Token.FLOAT_NUMBER : case Token.INTEGER_NUMBER : case Token.KEYWORD_NEW : // lets try parse a method call getTokenStream().checkpoint(); try { return methodCallWithoutParenthesis(expr, identifier); } catch (Exception e) { getTokenStream().restore(); } } return null; } protected CSTNode methodCallWithoutParenthesis(CSTNode expr, CSTNode identifier) throws SyntaxException, IOException { CSTNode methodExpr = new CSTNode(Token.leftParenthesis(-1, -1)); methodExpr.addChild(expr); methodExpr.addChild(identifier); CSTNode parameterList = new CSTNode(Token.syntheticList()); parameterList.addChild(expression()); while (lt_bare() == Token.COMMA) { consume_bare(lt_bare()); optionalNewlines(); parameterList.addChild(expression()); } methodExpr.addChild(parameterList); return methodExpr; } protected boolean lookAheadForMethodCall() throws IOException, SyntaxException { return (lt_bare() == Token.DOT || lt_bare() == Token.NAVIGATE) && (isIdentifier(lt(2))); } protected CSTNode regexPattern() throws IOException, SyntaxException { Token token = consume(Token.PATTERN_REGEX); CSTNode expr = new CSTNode(token); CSTNode regexString = doubleQuotedString(); expr.addChild(regexString); return expr; } protected CSTNode doubleQuotedString() throws IOException, SyntaxException { Token token = consume(Token.DOUBLE_QUOTE_STRING); String text = token.getText(); CSTNode expr = new CSTNode(token); int textStart = 0; int cur = 0; int len = text.length(); while (cur < len) { int exprStart = text.indexOf("${", cur); if (exprStart < 0) { break; } if (exprStart > 0) { if (text.charAt(exprStart - 1) == '$') { StringBuffer buf = new StringBuffer(text); buf.replace(exprStart - 1, exprStart, ""); text = buf.toString(); cur = exprStart + 1; continue; } } if (exprStart != textStart) { expr.addChild( new CSTNode( Token.singleQuoteString( token.getStartLine(), token.getStartColumn() + cur + 1, text.substring(textStart, exprStart)))); } int exprEnd = text.indexOf("}", exprStart); String exprText = text.substring(exprStart + 2, exprEnd); StringCharStream exprStream = new StringCharStream(exprText); Lexer lexer = new Lexer(exprStream); Parser parser = new Parser(new LexerTokenStream(lexer)); CSTNode embeddedExpr = parser.expression(); expr.addChild(embeddedExpr); cur = exprEnd + 1; textStart = cur; } if (textStart < len) { expr.addChild( new CSTNode( Token.singleQuoteString( token.getStartLine(), token.getStartColumn() + textStart + 1, text.substring(textStart)))); } return expr; } protected CSTNode parentheticalExpression() throws IOException, SyntaxException { consume(Token.LEFT_PARENTHESIS); if (lt_bare() == Token.IDENTIFIER && lt_bare(2) == Token.RIGHT_PARENTHESIS) { // we could be a cast boolean valid = true; switch (lt_bare(3)) { case Token.SEMICOLON : case Token.NEWLINE : case Token.RIGHT_CURLY_BRACE : case -1 : valid = false; } if (valid) { // lets assume we're a cast expression CSTNode castExpr = new CSTNode(Token.syntheticCast()); castExpr.addChild(new CSTNode(consume_bare(lt_bare()))); consume_bare(lt_bare()); castExpr.addChild(expression()); return castExpr; } } CSTNode expr = expression(); consume(Token.RIGHT_PARENTHESIS); return expr; } protected CSTNode parameterList(int endOfListDemarc) throws IOException, SyntaxException { if (isIdentifier(lt_bare()) && lt_bare(2) == Token.COLON) { return namedParameterList(endOfListDemarc); } CSTNode parameterList = new CSTNode(Token.syntheticList()); while (lt_bare() != endOfListDemarc) { parameterList.addChild(expression()); if (lt_bare() == Token.COMMA) { consume_bare(Token.COMMA); optionalNewlines(); } else { break; } } return parameterList; } protected boolean isIdentifier(int type) { for (int i = 0; i < identifierTokens.length; i++) { if (type == identifierTokens[i]) { return true; } } return false; } /** * Tests that the next token is an identifier */ protected void expectIdentifier() throws SyntaxException, IOException { if (!isIdentifier(lt_bare())) { throwExpected(identifierTokens); } } protected CSTNode namedParameterList(int endOfListDemarc) throws IOException, SyntaxException { CSTNode parameterList = new CSTNode(Token.syntheticList()); while (lt() != endOfListDemarc) { expectIdentifier(); CSTNode name = rootNode(lt_bare()); CSTNode namedParam = rootNode_bare(Token.COLON, name); namedParam.addChild(expression()); parameterList.addChild(namedParam); if (lt_bare() == Token.COMMA) { consume_bare(Token.COMMA); optionalNewlines(); } else { break; } } return parameterList; } protected CSTNode newExpression() throws IOException, SyntaxException { CSTNode expr = rootNode(Token.KEYWORD_NEW); expr.addChild(datatypeWithoutArray()); /* consume( Token.LEFT_PARENTHESIS ); expr.addChild( parameterList( Token.RIGHT_PARENTHESIS ) ); consume( Token.RIGHT_PARENTHESIS ); */ if (lt_bare() == Token.LEFT_PARENTHESIS) { consume_bare(Token.LEFT_PARENTHESIS); expr.addChild(parameterList(Token.RIGHT_PARENTHESIS)); consume(Token.RIGHT_PARENTHESIS); } else if (lt_bare() == Token.LEFT_CURLY_BRACE) { consume_bare(Token.LEFT_CURLY_BRACE); CSTNode paramList = parameterList(Token.RIGHT_CURLY_BRACE); expr.addChild(paramList); paramList.addChild(closureExpression()); } else if (lt_bare() == Token.LEFT_SQUARE_BRACKET) { expr.addChild(new CSTNode(consume_bare(Token.LEFT_SQUARE_BRACKET))); if (lt_bare() == Token.RIGHT_SQUARE_BRACKET) { // no size so must use a size expression consume_bare(Token.RIGHT_SQUARE_BRACKET); expr.addChild(new CSTNode(consume_bare(Token.LEFT_CURLY_BRACE))); CSTNode paramList = parameterList(Token.RIGHT_CURLY_BRACE); consume(Token.RIGHT_CURLY_BRACE); expr.addChild(paramList); } else { expr.addChild(expression()); consume_bare(Token.RIGHT_SQUARE_BRACKET); } } return expr; } protected CSTNode closureExpression() throws IOException, SyntaxException { CSTNode expr = rootNode(Token.LEFT_CURLY_BRACE); boolean pipeRequired = false; // { statement(); // { a, b | // { A a | // { A a, B b | // { int[] a, char b | if (lt(1) == Token.KEYWORD_BOOLEAN || lt(1) == Token.KEYWORD_BYTE || lt(1) == Token.KEYWORD_CHAR || lt(1) == Token.KEYWORD_DOUBLE || lt(1) == Token.KEYWORD_FLOAT || lt(1) == Token.KEYWORD_INT || lt(1) == Token.KEYWORD_LONG || lt(1) == Token.KEYWORD_SHORT || lt(2) == Token.PIPE || lt(2) == Token.COMMA || lt(3) == Token.PIPE || lt(3) == Token.COMMA) { expr.addChild(parameterDeclarationList()); pipeRequired = true; } else { expr.addChild(new CSTNode()); } if (pipeRequired || lt() == Token.PIPE) { consume(Token.PIPE); } CSTNode block = new CSTNode(); statementsUntilRightCurly(block); consume(Token.RIGHT_CURLY_BRACE); expr.addChild(block); return expr; } protected CSTNode listOrMapExpression() throws IOException, SyntaxException { CSTNode expr = null; consume(Token.LEFT_SQUARE_BRACKET); if (lt() == Token.COLON) { // it is an empty map consume(Token.COLON); expr = new CSTNode(Token.syntheticMap()); } else if (lt() == Token.RIGHT_SQUARE_BRACKET) { // it is an empty list expr = new CSTNode(Token.syntheticList()); } else { CSTNode firstExpr = expression(); if (lt() == Token.COLON) { expr = mapExpression(firstExpr); } else { expr = listExpression(firstExpr); } } consume(Token.RIGHT_SQUARE_BRACKET); return expr; } protected CSTNode mapExpression(CSTNode key) throws IOException, SyntaxException { CSTNode expr = new CSTNode(Token.syntheticMap()); CSTNode entry = rootNode(Token.COLON, key); CSTNode value = expression(); entry.addChild(value); expr.addChild(entry); while (lt() == Token.COMMA) { consume(Token.COMMA); key = expression(); entry = rootNode(Token.COLON, key); entry.addChild(expression()); expr.addChild(entry); } return expr; } protected CSTNode listExpression(CSTNode entry) throws IOException, SyntaxException { CSTNode expr = new CSTNode(Token.syntheticList()); expr.addChild(entry); while (lt() == Token.COMMA) { consume(Token.COMMA); entry = expression(); expr.addChild(entry); } return expr; } /* protected CSTNode listExpression() throws IOException, SyntaxException { CSTNode expr = rootNode( Token.LEFT_SQUARE_BRACKET ); while ( lt() != Token.RIGHT_SQUARE_BRACKET ) { expr.addChild( expression() ); if ( lt() == Token.COMMA ) { consume( Token.COMMA ); } else { break; } } consume( Token.RIGHT_SQUARE_BRACKET ); return expr; } */ protected CSTNode argumentList() throws IOException, SyntaxException { CSTNode argumentList = new CSTNode(); while (lt() != Token.RIGHT_PARENTHESIS) { argumentList.addChild(expression()); if (lt() == Token.COMMA) { consume(Token.COMMA); } else { break; } } return argumentList; } protected static boolean isModifier(int type) { switch (type) { case (Token.KEYWORD_PUBLIC) : case (Token.KEYWORD_PROTECTED) : case (Token.KEYWORD_PRIVATE) : case (Token.KEYWORD_STATIC) : case (Token.KEYWORD_FINAL) : case (Token.KEYWORD_SYNCHRONIZED) : { return true; } default : { return false; } } } protected void throwExpected(int[] expectedTypes) throws IOException, SyntaxException { throw new UnexpectedTokenException(la(), expectedTypes); } protected void consumeUntil(int type) throws IOException, SyntaxException { while (lt() != -1) { consume(lt()); if (lt() == type) { consume(lt()); break; } } } protected Token la() throws IOException, SyntaxException { return la(1); } protected int lt() throws IOException, SyntaxException { Token token = la(); if (token == null) { return -1; } return token.getType(); } protected Token la(int k) throws IOException, SyntaxException { Token token = null; for (int pivot = 1, count = 0; count < k; pivot++) { token = getTokenStream().la(pivot); if (token == null || token.getType() != Token.NEWLINE) { count++; } } return token; } protected int lt(int k) throws IOException, SyntaxException { Token token = la(k); if (token == null) { return -1; } return token.getType(); } protected Token consume(int type) throws IOException, SyntaxException { if (lt() != type) { throw new UnexpectedTokenException(la(), type); } while (true) { Token token = getTokenStream().la(); if (token == null || token.getType() != Token.NEWLINE) { break; } getTokenStream().consume(Token.NEWLINE); } return getTokenStream().consume(type); } protected void consume(CSTNode root, int type) throws IOException, SyntaxException { root.addChild(new CSTNode(consume(type))); } // bare versions of the token methods which don't ignore newlines protected void consumeUntil_bare(int type) throws IOException, SyntaxException { while (lt_bare() != -1) { consume_bare(lt_bare()); if (lt_bare() == type) { consume(lt_bare()); break; } } } protected Token la_bare() throws IOException, SyntaxException { return la_bare(1); } protected int lt_bare() throws IOException, SyntaxException { Token token = la_bare(); if (token == null) { return -1; } return token.getType(); } protected Token la_bare(int k) throws IOException, SyntaxException { return getTokenStream().la(k); } protected int lt_bare(int k) throws IOException, SyntaxException { Token token = la_bare(k); if (token == null) { return -1; } return token.getType(); } protected Token consume_bare(int type) throws IOException, SyntaxException { if (lt_bare() != type) { throw new UnexpectedTokenException(la_bare(), type); } lastTokenStatementSeparator = type == Token.SEMICOLON || type == Token.NEWLINE; return getTokenStream().consume(type); } protected void consume_bare(CSTNode root, int type) throws IOException, SyntaxException { root.addChild(new CSTNode(consume_bare(type))); } protected CSTNode rootNode(int type) throws IOException, SyntaxException { return new CSTNode(consume(type)); } protected CSTNode rootNode_bare(int type) throws IOException, SyntaxException { return new CSTNode(consume_bare(type)); } protected CSTNode rootNode(int type, CSTNode child) throws IOException, SyntaxException { CSTNode root = new CSTNode(consume(type)); root.addChild(child); return root; } protected CSTNode rootNode_bare(int type, CSTNode child) throws IOException, SyntaxException { CSTNode root = new CSTNode(consume_bare(type)); root.addChild(child); return root; } }
// This source code is available under agreement available at // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France package org.talend.components.simplefileio.runtime; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.talend.components.common.datastore.DatastoreDefinition; import org.talend.components.simplefileio.SimpleFileIoDatastoreDefinition; import org.talend.components.simplefileio.SimpleFileIoDatastoreProperties; import org.talend.daikon.runtime.RuntimeInfo; import org.talend.daikon.runtime.RuntimeUtil; /** * Unit tests for {@link SimpleFileIoDatastoreRuntime}. */ public class SimpleFileIoDatastoreRuntimeTest { /** * Instance to test. Definitions are immutable. */ private final DatastoreDefinition<?> def = new SimpleFileIoDatastoreDefinition(); static { RuntimeUtil.registerMavenUrlHandler(); } /** * @return the properties for this datastore, fully initialized with the default values. */ public static SimpleFileIoDatastoreProperties createDatastoreProperties() { // Configure the datastore. SimpleFileIoDatastoreProperties datastoreProps = new SimpleFileIoDatastoreProperties(null); datastoreProps.init(); return datastoreProps; } /** * Checks the {@link RuntimeInfo} of the definition. */ @Test @Ignore("This can't work unless the runtime jar is already installed in maven!") public void testRuntimeInfo() throws MalformedURLException { RuntimeInfo runtimeInfo = def.getRuntimeInfo(null, null); // We test the maven dependencies in this runtime class, where they are available. List<URL> dependencies = runtimeInfo.getMavenUrlDependencies(); assertThat(dependencies, notNullValue()); assertThat(dependencies, hasItem(new URL("mvn:org.apache.beam/beam-sdks-java-io-hdfs/0.3.0-incubating/jar"))); assertThat(dependencies, hasSize(greaterThan(100))); } }
package org.parser.marpa; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public enum ESLIFLoggerLevel { TRACE (0), DEBUG (1), INFO (2), NOTICE (3), WARNING (4), ERROR (5), CRITICAL (6), ALERT (7), EMERGENCY(8); private int code; private static final Map<Integer,ESLIFLoggerLevel> lookup = new HashMap<Integer,ESLIFLoggerLevel>(); static { for(ESLIFLoggerLevel s : EnumSet.allOf(ESLIFLoggerLevel.class)) { lookup.put(s.getCode(), s); } } private ESLIFLoggerLevel(int code) { this.code = code; } /** * Get the log level value associated to an instance of ESLIFLoggerLevel. * * @return the log level value */ public int getCode() { return code; } /** * Get an instance of ESLIFLoggerLevel from a log level value * * @return the ESLIFLoggerLevel instance */ public static ESLIFLoggerLevel get(int code) { return lookup.get(code); } }
package com.vaklinov.zcashui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.EtchedBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableColumn; public class AddressBookPanel extends JPanel { private static class AddressBookEntry { final String name,address; AddressBookEntry(String name, String address) { this.name = name; this.address = address; } } private final List<AddressBookEntry> entries = new ArrayList<>(); private final Set<String> names = new HashSet<>(); private JTable table; private JButton sendCashButton, deleteContactButton,copyToClipboardButton; private final SendCashPanel sendCashPanel; private final JTabbedPane tabs; private JPanel buildButtonsPanel() { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3)); JButton newContactButton = new JButton("New contact..."); newContactButton.addActionListener(new NewContactActionListener()); panel.add(newContactButton); sendCashButton = new JButton("Send ZCash"); sendCashButton.addActionListener(new SendCashActionListener()); sendCashButton.setEnabled(false); panel.add(sendCashButton); copyToClipboardButton = new JButton("Copy address to clipboard"); copyToClipboardButton.setEnabled(false); copyToClipboardButton.addActionListener(new CopyToClipboardActionListener()); panel.add(copyToClipboardButton); deleteContactButton = new JButton("Delete contact"); deleteContactButton.setEnabled(false); deleteContactButton.addActionListener(new DeleteAddressActionListener()); panel.add(deleteContactButton); return panel; } private JScrollPane buildTablePanel() { table = new JTable(new AddressBookTableModel(),new DefaultTableColumnModel()); TableColumn nameColumn = new TableColumn(0); TableColumn addressColumn = new TableColumn(1); table.addColumn(nameColumn); table.addColumn(addressColumn); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // one at a time table.getSelectionModel().addListSelectionListener(new AddressListSelectionListener()); table.addMouseListener(new AddressMouseListener()); JScrollPane scrollPane = new JScrollPane(table); return scrollPane; } public AddressBookPanel(SendCashPanel sendCashPanel, JTabbedPane tabs) throws IOException { this.sendCashPanel = sendCashPanel; this.tabs = tabs; BoxLayout boxLayout = new BoxLayout(this,BoxLayout.Y_AXIS); setLayout(boxLayout); add(buildTablePanel()); add(buildButtonsPanel()); loadEntriesFromDisk(); } private void loadEntriesFromDisk() throws IOException { File addressBookFile = new File(OSUtil.getSettingsDirectory(),"addressBook.csv"); if (!addressBookFile.exists()) return; try (BufferedReader bufferedReader = new BufferedReader(new FileReader(addressBookFile))) { String line; while((line = bufferedReader.readLine()) != null) { // format is address,name - this way name can contain commas ;-) int addressEnd = line.indexOf(','); if (addressEnd < 0) throw new IOException("Address Book is corrupted!"); String address = line.substring(0, addressEnd); String name = line.substring(addressEnd + 1); if (!names.add(name)) continue; // duplicate entries.add(new AddressBookEntry(name,address)); } } } private void saveEntriesToDisk() { try { File addressBookFile = new File(OSUtil.getSettingsDirectory(),"addressBook.csv"); try (PrintWriter printWriter = new PrintWriter(new FileWriter(addressBookFile))) { for (AddressBookEntry entry : entries) printWriter.println(entry.address+","+entry.name); } } catch (IOException bad) { System.out.println("Saving Address Book Failed!!!!"); bad.printStackTrace(); } } private class DeleteAddressActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; AddressBookEntry entry = entries.get(row); entries.remove(row); names.remove(entry.name); deleteContactButton.setEnabled(false); sendCashButton.setEnabled(false); copyToClipboardButton.setEnabled(false); table.repaint(); SwingUtilities.invokeLater(new Runnable() { public void run() { saveEntriesToDisk(); } }); } } private class CopyToClipboardActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; AddressBookEntry entry = entries.get(row); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new StringSelection(entry.address), null); } } private class NewContactActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { String name = (String) JOptionPane.showInputDialog(AddressBookPanel.this, "Please enter the name of the contact:", "Add new contact step 1", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (name == null || "".equals(name)) return; // cancelled // TODO: check for dupes names.add(name); String address = (String) JOptionPane.showInputDialog(AddressBookPanel.this, "Pleae enter the t-address or z-address of "+name, "Add new contact step 2", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (address == null || "".equals(address)) return; // cancelled entries.add(new AddressBookEntry(name,address)); table.invalidate(); table.repaint(); SwingUtilities.invokeLater(new Runnable() { public void run() { saveEntriesToDisk(); } }); } } private class SendCashActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; AddressBookEntry entry = entries.get(row); sendCashPanel.prepareForSending(entry.address); tabs.setSelectedIndex(2); } } private class AddressMouseListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { if (e.isConsumed() || (!e.isPopupTrigger())) return; int row = table.rowAtPoint(e.getPoint()); int column = table.columnAtPoint(e.getPoint()); table.changeSelection(row, column, false, false); AddressBookEntry entry = entries.get(row); JPopupMenu menu = new JPopupMenu(); JMenuItem sendCash = new JMenuItem("Send Zcash to "+entry.name); sendCash.addActionListener(new SendCashActionListener()); menu.add(sendCash); JMenuItem copyAddress = new JMenuItem("Copy address to clipboard"); copyAddress.addActionListener(new CopyToClipboardActionListener()); menu.add(copyAddress); JMenuItem deleteEntry = new JMenuItem("Delete "+entry.name+" from contacts"); deleteEntry.addActionListener(new DeleteAddressActionListener()); menu.add(deleteEntry); menu.show(e.getComponent(), e.getPoint().x, e.getPoint().y); e.consume(); } } private class AddressListSelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { int row = table.getSelectedRow(); if (row < 0) { sendCashButton.setEnabled(false); deleteContactButton.setEnabled(false); copyToClipboardButton.setEnabled(false); return; } String name = entries.get(row).name; sendCashButton.setText("Send Zcash to "+name); sendCashButton.setEnabled(true); deleteContactButton.setText("Delete contact "+name); deleteContactButton.setEnabled(true); copyToClipboardButton.setEnabled(true); } } private class AddressBookTableModel extends AbstractTableModel { @Override public int getRowCount() { return entries.size(); } @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0 : return "name"; case 1 : return "address"; default: throw new IllegalArgumentException("invalid column "+columnIndex); } } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { AddressBookEntry entry = entries.get(rowIndex); switch(columnIndex) { case 0 : return entry.name; case 1 : return entry.address; default: throw new IllegalArgumentException("bad column "+columnIndex); } } } }
package org.eclipse.smarthome.binding.lifx.internal; import java.nio.ByteBuffer; import java.time.Duration; import java.time.LocalDateTime; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.eclipse.smarthome.binding.lifx.LifxBindingConstants; import org.eclipse.smarthome.binding.lifx.handler.LifxLightHandler.CurrentLightState; import org.eclipse.smarthome.binding.lifx.internal.fields.MACAddress; import org.eclipse.smarthome.binding.lifx.internal.listener.LifxResponsePacketListener; import org.eclipse.smarthome.binding.lifx.internal.protocol.GetEchoRequest; import org.eclipse.smarthome.binding.lifx.internal.protocol.GetServiceRequest; import org.eclipse.smarthome.binding.lifx.internal.protocol.Packet; import org.eclipse.smarthome.core.common.ThreadPoolManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link LifxLightOnlineStateUpdater} sets the state of a light offline when it no longer responds to echo packets. * * @author Wouter Born - Extracted class from LifxLightHandler */ public class LifxLightOnlineStateUpdater implements LifxResponsePacketListener { private static final int ECHO_POLLING_INTERVAL = 15; private static final int MAXIMUM_POLLING_RETRIES = 3; private final Logger logger = LoggerFactory.getLogger(LifxLightOnlineStateUpdater.class); private final String macAsHex; private final CurrentLightState currentLightState; private final LifxLightCommunicationHandler communicationHandler; private final ReentrantLock lock = new ReentrantLock(); private final ScheduledExecutorService scheduler = ThreadPoolManager .getScheduledPool(LifxBindingConstants.THREADPOOL_NAME); private ScheduledFuture<?> echoJob; private LocalDateTime lastSeen = LocalDateTime.MIN; private int unansweredEchoPackets; public LifxLightOnlineStateUpdater(MACAddress macAddress, CurrentLightState currentLightState, LifxLightCommunicationHandler communicationHandler) { this.macAsHex = macAddress.getHex(); this.currentLightState = currentLightState; this.communicationHandler = communicationHandler; } private Runnable echoRunnable = new Runnable() { @Override public void run() { try { lock.lock(); logger.trace("{} : Polling", macAsHex); if (currentLightState.isOnline()) { if (Duration.between(lastSeen, LocalDateTime.now()).getSeconds() > ECHO_POLLING_INTERVAL) { if (unansweredEchoPackets < MAXIMUM_POLLING_RETRIES) { ByteBuffer payload = ByteBuffer.allocate(Long.SIZE / 8); payload.putLong(System.currentTimeMillis()); GetEchoRequest request = new GetEchoRequest(); request.setResponseRequired(true); request.setPayload(payload); communicationHandler.sendPacket(request); unansweredEchoPackets++; } else { currentLightState.setOfflineByCommunicationError(); unansweredEchoPackets = 0; } } } else { // are we not configured? let's broadcast instead logger.trace("{} : The light is not online, let's broadcast instead", macAsHex); GetServiceRequest packet = new GetServiceRequest(); communicationHandler.broadcastPacket(packet); } } catch (Exception e) { logger.error("Error occurred while polling online state", e); } finally { lock.unlock(); } } }; public void start() { try { lock.lock(); communicationHandler.addResponsePacketListener(this); if (echoJob == null || echoJob.isCancelled()) { echoJob = scheduler.scheduleWithFixedDelay(echoRunnable, 0, ECHO_POLLING_INTERVAL, TimeUnit.SECONDS); } } catch (Exception e) { logger.error("Error occurred while starting online state poller", e); } finally { lock.unlock(); } } public void stop() { try { lock.lock(); communicationHandler.removeResponsePacketListener(this); if (echoJob != null && !echoJob.isCancelled()) { echoJob.cancel(true); echoJob = null; } } catch (Exception e) { logger.error("Error occurred while stopping online state poller", e); } finally { lock.unlock(); } } @Override public void handleResponsePacket(Packet packet) { lastSeen = LocalDateTime.now(); unansweredEchoPackets = 0; } }
package net.yeputons.ofeed; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.UpdateBuilder; import com.vk.sdk.VKAccessToken; import com.vk.sdk.VKCallback; import com.vk.sdk.VKSdk; import com.vk.sdk.api.*; import com.vk.sdk.api.methods.VKApiFeed; import com.vk.sdk.api.model.*; import net.yeputons.ofeed.db.*; import net.yeputons.ofeed.web.*; import net.yeputons.ofeed.web.dmanager.ThreadPoolResourceDownloader; import java.net.URI; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; public class MainActivity extends Activity implements VKCallback<VKAccessToken> { private static final String TAG = "ofeed"; private Menu optionsMenu; private FeedListViewAdapter adapter; private int loadStep = 50; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); adapter = new FeedListViewAdapter(this); ListView listFeed = (ListView) findViewById(R.id.listFeed); listFeed.setAdapter(adapter); listFeed.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { VKApiFeedItem feedItem = adapter.getItem(position).feedItem; if (feedItem != null) { Intent intent = new Intent(MainActivity.this, PostActivity.class); intent.putExtra(PostActivity.EXTRA_POST, feedItem); startActivity(intent); } } }); if (VKAccessToken.currentToken() == null) { logout(null); login(null); } else { onResult(VKAccessToken.currentToken()); } } @Override protected void onDestroy() { optionsMenu = null; adapter = null; super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!VKSdk.onActivityResult(requestCode, resultCode, data, this)) { super.onActivityResult(requestCode, resultCode, data); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); optionsMenu = menu; updateMenuStatus(); return true; } public void login(MenuItem item) { VKSdk.login(this, "friends", "wall"); } public void loadBeginning(MenuItem item) { new VKApiFeed().get(VKParameters.from(VKApiConst.COUNT, loadStep, VKApiFeed.FILTERS, VKApiFeed.FILTERS_POST)).executeWithListener(feedGetListener); } public void loadFrom(final String startFrom) { new VKApiFeed().get(VKParameters.from(VKApiConst.COUNT, loadStep, VKApiFeed.FILTERS, VKApiFeed.FILTERS_POST, VKApiFeed.START_FROM, startFrom)).executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { feedGetListener.onComplete(response); UpdateBuilder<CachedFeedItem, String> update = DbHelper.get().getCachedFeedItemDao().updateBuilder(); try { update.where().eq(CachedFeedItem.NEXT_PAGE_TO_LOAD, startFrom); update.updateColumnValue(CachedFeedItem.NEXT_PAGE_TO_LOAD, ""); update.update(); DbHelper.get().getCachedFeedItemDao().deleteById(CachedFeedItem.getPageEndId(startFrom)); } catch (SQLException e) { Log.e(TAG, "Unable to remove 'next page' marker from some feed items", e); } adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { feedGetListener.attemptFailed(request, attemptNumber, totalAttempts); adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } @Override public void onError(VKError error) { feedGetListener.onError(error); adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } @Override public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) { feedGetListener.onProgress(progressType, bytesLoaded, bytesTotal); adapter.completePageLoad(startFrom); adapter.notifyDataSetChanged(); } }); } public void loadStep2(MenuItem item) { loadStep = 2; } public void loadStep50(MenuItem item) { loadStep = 50; } public void clearCache(MenuItem item) { DbHelper h = DbHelper.get(); try { h.getCachedFeedItemDao().deleteBuilder().delete(); h.getCachedGroupDao().deleteBuilder().delete(); h.getCachedUserDao().deleteBuilder().delete(); h.getCachedWebResourcesDao().deleteBuilder().delete(); h.getCachedWebPageDao().deleteBuilder().delete(); } catch (SQLException e) { Log.e(TAG, "Unable to clear cache", e); Toast.makeText(this, "Error while clearing cache, it may become inconsistent", Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); } public void logout(MenuItem item) { VKSdk.logout(); clearCache(item); updateMenuStatus(); } private void updateMenuStatus() { if (optionsMenu == null) { return; } boolean isLoggedIn = VKAccessToken.currentToken() != null; optionsMenu.findItem(R.id.menuItemLogin).setEnabled(!isLoggedIn); optionsMenu.findItem(R.id.menuItemLoadBeginning).setEnabled(isLoggedIn); optionsMenu.findItem(R.id.menuItemLogout).setEnabled(isLoggedIn); } private final VKRequest.VKRequestListener feedGetListener = new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { final VKApiFeedPage page = (VKApiFeedPage) response.parsedModel; final Dao<CachedUser, Integer> userDao = DbHelper.get().getCachedUserDao(); final Dao<CachedGroup, Integer> groupDao = DbHelper.get().getCachedGroupDao(); final ArrayList<CachedFeedItem> feed = new ArrayList<CachedFeedItem>(); if (page.items.length == 0) { return; } Set<String> occuredItems = new HashSet<>(); for (VKApiFeedItem item : page.items) { CachedFeedItem item2 = new CachedFeedItem(item); if (occuredItems.contains(item2.id)) { Log.w(TAG, "Received duplicated item in response from VK: " + item2.id); continue; } occuredItems.add(item2.id); feed.add(item2); if (item.post != null && item.post.attachments != null) { for (VKAttachments.VKApiAttachment a : item.post.attachments) { if (a instanceof VKApiLink) { VKApiLink l = (VKApiLink) a; final URI uri = URI.create(l.url); if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { DeepWebPageSaver saver = new DeepWebPageSaver(OfeedApplication.getDownloader()); final WebResource resource = saver.savePage(uri); saver.setDownloadCompleteListener(new DownloadCompleteListener() { @Override public void onDownloadComplete() { CachedWebPage page = new CachedWebPage(); page.uri = uri.toString(); ResourceDownload d = resource.getDownloaded(); if (d == null) { Log.e(TAG, "Oops, unable to deep save web page"); return; } page.localFile = d.getLocalFile().getAbsolutePath(); try { DbHelper.get().getCachedWebPageDao().create(page); adapter.notifyDataSetChanged(); } catch (SQLException e) { Log.e(TAG, "Cannot save deep downloaded page info to db", e); } } }); } } } } } final CachedFeedItem pageEndPlaceholder = new CachedFeedItem(page.items[page.items.length - 1], page.next_from); final Dao<CachedFeedItem, String> itemDao = DbHelper.get().getCachedFeedItemDao(); try { userDao.callBatchTasks(new Callable<Void>() { @Override public Void call() throws Exception { for (VKApiUser u : page.profiles) { userDao.createOrUpdate(new CachedUser(u)); } return null; } }); groupDao.callBatchTasks(new Callable<Void>() { @Override public Void call() throws Exception { for (VKApiCommunity g : page.groups) { groupDao.createOrUpdate(new CachedGroup(g)); } return null; } }); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { for (VKApiUser u : page.profiles) { WebResourcesCache.getDownloadingWebResource(URI.create(u.photo_100)); } for (VKApiCommunity g : page.groups) { WebResourcesCache.getDownloadingWebResource(URI.create(g.photo_100)); } return null; } }.execute(); itemDao.callBatchTasks(new Callable<Void>() { @Override public Void call() throws Exception { boolean pageDoesNotContinue = true; for (int i = 0; i < feed.size(); i++) { CachedFeedItem item = feed.get(i); CachedFeedItem old = itemDao.queryForFirst( itemDao.queryBuilder() .selectColumns("nextPageToLoad") .where().eq("id", item.id).prepare()); if (i + 1 == feed.size()) { if (old != null && old.nextPageToLoad.isEmpty()) { item.nextPageToLoad = ""; pageDoesNotContinue = false; } else { item.nextPageToLoad = page.next_from; } } else { if (old != null && !old.nextPageToLoad.isEmpty()) { itemDao.deleteById(CachedFeedItem.getPageEndId(old.nextPageToLoad)); } item.nextPageToLoad = ""; } itemDao.createOrUpdate(item); } if (pageDoesNotContinue) { itemDao.createOrUpdate(pageEndPlaceholder); } return null; } }); } catch (Exception e) { Log.e(TAG, "Unable to update db with received feed items", e); } adapter.notifyDataSetChanged(); Log.d(TAG, "next_from=" + page.next_from); } @Override public void onError(VKError error) { Toast.makeText(MainActivity.this, "Error: " + error.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) { Toast.makeText(MainActivity.this, String.format("Progress %d/%d", bytesLoaded, bytesTotal), Toast.LENGTH_SHORT).show(); } }; @Override public void onResult(final VKAccessToken res) { updateMenuStatus(); } @Override public void onError(VKError error) { Toast.makeText(this, "Error while logging in: " + error, Toast.LENGTH_LONG).show(); } }
package org.uct.cs.simplify; import org.apache.commons.cli.*; import org.uct.cs.simplify.filebuilder.PHFBuilder; import org.uct.cs.simplify.filebuilder.PHFNode; import org.uct.cs.simplify.filebuilder.RecursiveFilePreparer; import org.uct.cs.simplify.util.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileBuilder { public static final int MAX_DEPTH = 20; private static final int RESCALE_SIZE = 1024; public static String run(File inputFile, File outputFile, boolean keepNodes, boolean swapYZ, int treedepth, IProgressReporter progressReporter) throws IOException, InterruptedException { StatRecorder sr = new StatRecorder(); // use the directory of the outputfile as the default output directory File outputDir = outputFile.getParentFile(); // generate tempfiles in the outputdir TempFileManager.setWorkingDirectory(outputDir.toPath()); // delete all tempfiles afterwards TempFileManager.setDeleteOnExit(!keepNodes); // create scaled and recentered version of input File scaledFile = TempFileManager.provide("rescaled", ".ply"); ScaleAndRecenter.run(inputFile, scaledFile, RESCALE_SIZE, swapYZ); // build tree PHFNode tree = RecursiveFilePreparer.prepare(new PHFNode(scaledFile), treedepth, progressReporter); // compile into output file String jsonHeader = PHFBuilder.compile(tree, outputFile); Outputter.info3f("Processing complete. Final file: %s%n", outputFile); sr.close(); //sr.dump(new File(outputDir, "memdump")); return jsonHeader; } public static void main(String[] args) throws IOException { CommandLine cmd = getCommandLine(args); try (StatRecorder ignored = new StatRecorder()) { File inputFile = new File(cmd.getOptionValue("input")); File outputFile = new File(cmd.getOptionValue("output")); File outputDir = outputFile.getParentFile(); String jsonHeader = run( inputFile, outputFile, cmd.hasOption("keeptemp"), cmd.hasOption("swapyz"), Integer.parseInt(cmd.getOptionValue("treedepth")), new StdOutProgressReporter() ); if (cmd.hasOption("dumpjson")) { File headerFile = new File(outputDir, Useful.getFilenameWithoutExt(inputFile.getName()) + ".json"); try (FileWriter fw = new FileWriter(headerFile)) { fw.write(jsonHeader); } } TempFileManager.clear(); } catch (InterruptedException | IllegalArgumentException e) { e.printStackTrace(); } } private static CommandLine getCommandLine(String[] args) { CommandLineParser clp = new BasicParser(); Options options = new Options(); Option inputFile = new Option("i", "input", true, "path to first PLY file"); inputFile.setRequired(true); options.addOption(inputFile); Option outputFile = new Option("o", "output", true, "path to output directory"); outputFile.setRequired(true); options.addOption(outputFile); Option treedepth = new Option("d", "treedepth", true, "Dump the JSON header into separate file"); treedepth.setRequired(true); treedepth.setType(Number.class); options.addOption(treedepth); Option keepTempFiles = new Option( "k", "keeptemp", false, "keep any temporary files generated during phf compilation" ); options.addOption(keepTempFiles); Option swapYZ = new Option("s", "swapyz", false, "Rotate model 90 around X. (convert coordinate frame)"); options.addOption(swapYZ); Option dumpJSON = new Option("j", "dumpjson", false, "Dump the JSON header into separate file"); options.addOption(dumpJSON); CommandLine cmd; try { cmd = clp.parse(options, args); long treedepthv = (Long) cmd.getParsedOptionValue("treedepth"); if (treedepthv < 2 || treedepthv > MAX_DEPTH) throw new ParseException("treedepth must be > 1 and < 21"); return cmd; } catch (ParseException e) { Outputter.errorf("%s : %s%n%n", e.getClass().getName(), e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("filebuilder --input <path> --output <path>", options); System.exit(1); return null; } } }
package org.openbmap.activity; import java.io.File; import java.io.FilenameFilter; import org.openbmap.Preferences; import org.openbmap.R; import android.app.DownloadManager; import android.app.DownloadManager.Query; import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.provider.Settings; import android.util.Log; import android.widget.Toast; /** * Preferences activity. */ public class SettingsActivity extends PreferenceActivity { private static final String TAG = SettingsActivity.class.getSimpleName(); private EditTextPreference mDataDirPref; private DownloadManager dm; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); Query query = new Query(); query.setFilterById(downloadId); Cursor c = dm.query(query); if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { // we're not checking download id here, that is done in handleDownloads String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); handleDownloads(uriString); } } } } }; @Override protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); mDataDirPref = initDataDir(); registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); initWifiCatalogDownload(); initActiveWifiCatalog(mDataDirPref.getText()); initMapDownload(); initActiveMap(mDataDirPref.getText()); initGpsSystem(); initGpsLogInterval(); } @Override protected final void onDestroy() { try { Log.i(TAG, "Unregistering broadcast receivers"); unregisterReceiver(receiver); } catch (IllegalArgumentException e) { return; } super.onDestroy(); } /** * Initializes gps system preference. * OnPreferenceClick system gps settings are displayed. */ private void initGpsSystem() { Preference pref = findPreference(org.openbmap.Preferences.KEY_GPS_OSSETTINGS); pref.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); return true; } }); } /** * Initializes gps logging interval. */ private void initGpsLogInterval() { // Update GPS logging interval summary to the current value Preference pref = findPreference(org.openbmap.Preferences.KEY_GPS_LOGGING_INTERVAL); pref.setSummary( PreferenceManager.getDefaultSharedPreferences(this).getString(org.openbmap.Preferences.KEY_GPS_LOGGING_INTERVAL, org.openbmap.Preferences.VAL_GPS_LOGGING_INTERVAL) + " " + getResources().getString(R.string.prefs_gps_logging_interval_seconds) + ". " + getResources().getString(R.string.prefs_gps_logging_interval_summary)); pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { // Set summary with the interval and "seconds" preference.setSummary(newValue + " " + getResources().getString(R.string.prefs_gps_logging_interval_seconds) + ". " + getResources().getString(R.string.prefs_gps_logging_interval_summary)); return true; } }); } /** * Initializes data directory preference. * @return EditTextPreference with data directory. */ private EditTextPreference initDataDir() { // External storage directory EditTextPreference pref = (EditTextPreference) findPreference(org.openbmap.Preferences.KEY_DATA_DIR); pref.setSummary(PreferenceManager.getDefaultSharedPreferences(this).getString(org.openbmap.Preferences.KEY_DATA_DIR, org.openbmap.Preferences.VAL_DATA_DIR)); pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { String pathName = ""; // Ensure there is always a leading slash if (!((String) newValue).startsWith(File.separator)) { pathName = File.separator + (String) newValue; } else { pathName = (String) newValue; } // try to create directory File folder = new File(Environment.getExternalStorageDirectory() + pathName); boolean success = true; if (!folder.exists()) { success = folder.mkdirs(); } if (!success) { Toast.makeText(getBaseContext(), R.string.error_create_directory_failed + pathName, Toast.LENGTH_LONG).show(); return false; } // Set summary with the directory value preference.setSummary((String) pathName); // Re-populate available maps initActiveMap((String) pathName); return true; } }); return pref; } /** * Populates the active map list preference. * @param rootDir Root folder for MAPS_SUBDIR */ private void initActiveMap(final String rootDir) { String[] entries; String[] values; Log.d(TAG, "Scanning for map files"); // Check for presence of maps directory File mapsDir = new File(Environment.getExternalStorageDirectory(), rootDir + File.separator + org.openbmap.Preferences.MAPS_SUBDIR + File.separator); // List each map file if (mapsDir.exists() && mapsDir.canRead()) { String[] mapFiles = mapsDir.list(new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.endsWith(org.openbmap.Preferences.MAP_FILE_EXTENSION); } }); // Create array of values for each map file + one for not selected entries = new String[mapFiles.length + 1]; values = new String[mapFiles.length + 1]; // Create default / none entry entries[0] = getResources().getString(R.string.prefs_map_none); values[0] = org.openbmap.Preferences.VAL_MAP_NONE; for (int i = 0; i < mapFiles.length; i++) { entries[i + 1] = mapFiles[i].substring(0, mapFiles[i].length() - org.openbmap.Preferences.MAP_FILE_EXTENSION.length()); values[i + 1] = mapFiles[i]; } } else { // No map found, populate values with just the default entry. entries = new String[] {getResources().getString(R.string.prefs_map_none)}; values = new String[] {org.openbmap.Preferences.VAL_MAP_NONE}; } ListPreference lf = (ListPreference) findPreference(org.openbmap.Preferences.KEY_MAP_FILE); lf.setEntries(entries); lf.setEntryValues(values); } /** * Populates the download list with links to mapsforge downloads. * @param rootDir Root folder for MAPS_SUBDIR */ private void initMapDownload() { String[] entries; String[] values; // No map found, populate values with just the default entry. entries = getResources().getStringArray(R.array.listDisplayWord); values = getResources().getStringArray(R.array.listReturnValue); ListPreference lf = (ListPreference) findPreference(org.openbmap.Preferences.KEY_DOWNLOAD_MAP); lf.setEntries(entries); lf.setEntryValues(values); lf.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(final Preference preference, final Object newValue) { // try to create directory File folder = new File(Environment.getExternalStorageDirectory().getPath() + PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(Preferences.KEY_DATA_DIR, Preferences.VAL_DATA_DIR) + Preferences.MAPS_SUBDIR + File.separator); boolean folderAccessible = false; if (folder.exists() && folder.canWrite()) { folderAccessible = true; } if (!folder.exists()) { folderAccessible = folder.mkdirs(); } if (folderAccessible) { final String filename = newValue.toString().substring(newValue.toString().lastIndexOf('/') + 1); Request request = new Request(Uri.parse(newValue.toString())); request.setDestinationUri(Uri.fromFile(new File( folder.getAbsolutePath() + File.separator + filename))); long mapDownloadId = dm.enqueue(request); } else { Toast.makeText(preference.getContext(), R.string.error_save_file_failed, Toast.LENGTH_SHORT).show(); } return false; } }); } /** * Initializes wifi catalog source preference */ private void initWifiCatalogDownload() { Preference pref = findPreference(org.openbmap.Preferences.KEY_DOWNLOAD_WIFI_CATALOG); pref.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { // try to create directory File folder = new File(Environment.getExternalStorageDirectory().getPath() + PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(Preferences.KEY_DATA_DIR, Preferences.VAL_DATA_DIR) + Preferences.WIFI_CATALOG_SUBDIR + File.separator); boolean folderAccessible = false; if (folder.exists() && folder.canWrite()) { folderAccessible = true; } if (!folder.exists()) { folderAccessible = folder.mkdirs(); } if (folderAccessible) { Request request = new Request( Uri.parse(Preferences.WIFI_CATALOG_DOWNLOAD_URL)); request.setDestinationUri(Uri.fromFile(new File( folder.getAbsolutePath() + File.separator + Preferences.WIFI_CATALOG_FILE))); long catalogDownloadId = dm.enqueue(request); } else { Toast.makeText(preference.getContext(), R.string.error_save_file_failed, Toast.LENGTH_SHORT).show(); } return true; } }); } /** * Populates the wifi catalog database list preference. * @param rootDir Root folder for WIFI_CATALOG_SUBDIR */ private void initActiveWifiCatalog(final String rootDir) { String[] entries; String[] values; // Check for presence of database directory File dbDir = new File(Environment.getExternalStorageDirectory(), rootDir + File.separator + org.openbmap.Preferences.WIFI_CATALOG_SUBDIR + File.separator); if (dbDir.exists() && dbDir.canRead()) { // List each map file String[] dbFiles = dbDir.list(new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.endsWith( org.openbmap.Preferences.WIFI_CATALOG_FILE_EXTENSION); } }); // Create array of values for each map file + one for not selected entries = new String[dbFiles.length + 1]; values = new String[dbFiles.length + 1]; // Create default / none entry entries[0] = getResources().getString(R.string.prefs_map_none); values[0] = org.openbmap.Preferences.VAL_WIFI_CATALOG_NONE; for (int i = 0; i < dbFiles.length; i++) { entries[i + 1] = dbFiles[i].substring(0, dbFiles[i].length() - org.openbmap.Preferences.WIFI_CATALOG_FILE_EXTENSION.length()); values[i + 1] = dbFiles[i]; } } else { // No wifi catalog found, populate values with just the default entry. entries = new String[] {getResources().getString(R.string.prefs_map_none)}; values = new String[] {org.openbmap.Preferences.VAL_WIFI_CATALOG_NONE}; } ListPreference lf = (ListPreference) findPreference(org.openbmap.Preferences.KEY_WIFI_CATALOG); lf.setEntries(entries); lf.setEntryValues(values); } /** * Selects downloaded file either as wifi catalog / active map (based on file extension). * @param file */ public final void handleDownloads(final String file) { initActiveMap(mDataDirPref.getText()); initActiveWifiCatalog(mDataDirPref.getText()); // get current file extension String[] filenameArray = file.split("\\."); String extension = "." + filenameArray[filenameArray.length - 1]; if (extension.equals(org.openbmap.Preferences.MAP_FILE_EXTENSION)) { // handling map files activateMap(file); } else if (extension.equals(org.openbmap.Preferences.WIFI_CATALOG_FILE_EXTENSION)) { // handling wifi catalog files activateCatalog(file); } } /** * Changes catalog preference item to given filename. * Helper method to activate map after successful download * @param absoluteFile absolute filename (including path) */ private void activateCatalog(final String absoluteFile) { ListPreference lf = (ListPreference) findPreference(org.openbmap.Preferences.KEY_WIFI_CATALOG); // get filename String[] filenameArray = absoluteFile.split("\\/"); String file = filenameArray[filenameArray.length - 1]; CharSequence[] values = lf.getEntryValues(); for (int i = 0; i < values.length; i++) { if (file.equals(values[i].toString())) { lf.setValueIndex(i); } } } /** * Changes map preference item to given filename. * Helper method to activate map after successful download * @param absoluteFile absolute filename (including path) */ private void activateMap(final String absoluteFile) { ListPreference lf = (ListPreference) findPreference(org.openbmap.Preferences.KEY_MAP_FILE); // get filename String[] filenameArray = absoluteFile.split("\\/"); String file = filenameArray[filenameArray.length - 1]; CharSequence[] values = lf.getEntryValues(); for (int i = 0; i < values.length; i++) { if (file.equals(values[i].toString())) { lf.setValueIndex(i); } } } }
package org.nuxeo.ecm.platform.ec.notification; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.mail.MessagingException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mvel2.PropertyAccessException; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DataModel; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoGroup; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.core.api.blobholder.BlobHolder; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventBundle; import org.nuxeo.ecm.core.event.EventContext; import org.nuxeo.ecm.core.event.PostCommitFilteringEventListener; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.ecm.platform.ec.notification.email.EmailHelper; import org.nuxeo.ecm.platform.ec.notification.service.NotificationService; import org.nuxeo.ecm.platform.ec.notification.service.NotificationServiceHelper; import org.nuxeo.ecm.platform.notification.api.Notification; import org.nuxeo.ecm.platform.url.DocumentViewImpl; import org.nuxeo.ecm.platform.url.api.DocumentView; import org.nuxeo.ecm.platform.url.api.DocumentViewCodecManager; import org.nuxeo.ecm.platform.usermanager.UserManager; import org.nuxeo.runtime.api.Framework; public class NotificationEventListener implements PostCommitFilteringEventListener { private static final Log log = LogFactory.getLog(NotificationEventListener.class); private DocumentViewCodecManager docLocator; private UserManager userManager; private EmailHelper emailHelper = new EmailHelper(); private NotificationService notificationService = NotificationServiceHelper.getNotificationService(); @Override public boolean acceptEvent(Event event) { if (notificationService == null) { return false; } return notificationService.getNotificationEventNames().contains(event.getName()); } @Override public void handleEvent(EventBundle events) throws ClientException { if (notificationService == null) { log.error("Unable to get NotificationService, exiting"); return; } boolean processEvents = false; for (String name : notificationService.getNotificationEventNames()) { if (events.containsEventName(name)) { processEvents = true; break; } } if (! processEvents) { return; } for (Event event : events) { Boolean block = (Boolean)event.getContext().getProperty(NotificationConstants.DISABLE_NOTIFICATION_SERVICE); if (block != null && block) { // ignore the event - we are blocked by the caller continue; } List<Notification> notifs = notificationService.getNotificationsForEvents(event.getName()); if (notifs != null && !notifs.isEmpty()) { try { handleNotifications(event, notifs); } catch (Exception e) { log.error("Error during Notification processing for event " + event.getName(), e); } } } } protected void handleNotifications(Event event, List<Notification> notifs) throws Exception { EventContext ctx = event.getContext(); DocumentEventContext docCtx = null; if (ctx instanceof DocumentEventContext) { docCtx = (DocumentEventContext) ctx; } else { log.warn("Can not handle notification on a event that is not bound to a DocumentEventContext"); return; } CoreSession coreSession = event.getContext().getCoreSession(); Map<String, Serializable> properties = event.getContext().getProperties(); Map<Notification, List<String>> targetUsers = new HashMap<Notification, List<String>>(); for (NotificationListenerVeto veto : notificationService.getNotificationVetos()) { if (!veto.accept(event)) { return; } } for(NotificationListenerHook hookListener:notificationService.getListenerHooks()) { hookListener.handleNotifications(event); } gatherConcernedUsersForDocument(coreSession, docCtx.getSourceDocument(), notifs, targetUsers); for (Notification notif : targetUsers.keySet()) { if (!notif.getAutoSubscribed()) { for (String user : targetUsers.get(notif)) { sendNotificationSignalForUser(notif, user, event, docCtx); } } else { Object recipientProperty = properties.get(NotificationConstants.RECIPIENTS_KEY); String[] recipients = null; if (recipientProperty != null) { if (recipientProperty instanceof String[]) { recipients = (String[]) properties.get(NotificationConstants.RECIPIENTS_KEY); } else if (recipientProperty instanceof String ) { recipients = new String[1]; recipients[0] = (String) recipientProperty; } } if (recipients == null) { continue; } Set<String> users = new HashSet<String>(); for (String recipient : recipients) { if (recipient == null) { continue; } if (recipient.contains(NuxeoPrincipal.PREFIX)) { users.add(recipient.replace(NuxeoPrincipal.PREFIX, "")); } else if (recipient.contains(NuxeoGroup.PREFIX)) { List<String> groupMembers = getGroupMembers(recipient.replace( NuxeoGroup.PREFIX, "")); for (String member : groupMembers) { users.add(member); } } else { users.add(recipient); } } for (String user : users) { sendNotificationSignalForUser(notif, user, event, docCtx); } } } } protected UserManager getUserManager() { if (userManager == null) { try { userManager = Framework.getService(UserManager.class); } catch (Exception e) { throw new IllegalStateException( "UserManager service not deployed.", e); } } return userManager; } protected List<String> getGroupMembers(String groupId) throws ClientException { return getUserManager().getUsersInGroupAndSubGroups(groupId); } private void sendNotificationSignalForUser(Notification notification, String subscriptor, Event event, DocumentEventContext ctx) throws ClientException { log.debug("Producing notification message."); Map<String, Serializable> eventInfo = ctx.getProperties(); DocumentModel doc = ctx.getSourceDocument(); String author = ctx.getPrincipal().getName(); Calendar created = (Calendar) ctx.getSourceDocument().getPropertyValue( "dc:created"); eventInfo.put(NotificationConstants.DESTINATION_KEY, subscriptor); eventInfo.put(NotificationConstants.NOTIFICATION_KEY, notification); eventInfo.put(NotificationConstants.DOCUMENT_ID_KEY, doc.getId()); eventInfo.put(NotificationConstants.DATE_TIME_KEY, new Date(event.getTime())); eventInfo.put(NotificationConstants.AUTHOR_KEY, author); eventInfo.put(NotificationConstants.DOCUMENT_VERSION, doc.getVersionLabel()); eventInfo.put(NotificationConstants.DOCUMENT_STATE, doc.getCurrentLifeCycleState()); eventInfo.put(NotificationConstants.DOCUMENT_CREATED, created.getTime()); StringBuilder userUrl = new StringBuilder(); userUrl.append( notificationService.getServerUrlPrefix()).append( "user/").append(ctx.getPrincipal().getName()); eventInfo.put(NotificationConstants.USER_URL_KEY, userUrl.toString()); eventInfo.put(NotificationConstants.DOCUMENT_LOCATION, doc.getPathAsString()); // Main file link for downloading BlobHolder bh = doc.getAdapter(BlobHolder.class); if (bh != null && bh.getBlob() != null) { StringBuilder docMainFile = new StringBuilder(); docMainFile.append( notificationService.getServerUrlPrefix()).append( "nxfile/default/").append(doc.getId()).append( "/blobholder:0/").append(bh.getBlob().getFilename()); eventInfo.put(NotificationConstants.DOCUMENT_MAIN_FILE, docMainFile.toString()); } if (!isDeleteEvent(event.getName())) { DocumentView docView = new DocumentViewImpl(doc); DocumentViewCodecManager docLocator = getDocLocator(); if (docLocator != null) { eventInfo.put( NotificationConstants.DOCUMENT_URL_KEY, getDocLocator().getUrlFromDocumentView( docView, true, notificationService.getServerUrlPrefix())); } else { eventInfo.put(NotificationConstants.DOCUMENT_URL_KEY, ""); } eventInfo.put(NotificationConstants.DOCUMENT_TITLE_KEY, doc.getTitle()); } if (isInterestedInNotification(notification)) { try { sendNotification(event, ctx); if (log.isDebugEnabled()) { log.debug("notification " + notification.getName() + " sent to " + notification.getSubject()); } } catch (ClientException e) { log.error( "An error occurred while trying to send user notification", e); } } } public void sendNotification(Event event, DocumentEventContext ctx) throws ClientException { String eventId = event.getName(); log.debug("Received a message for notification sender with eventId : " + eventId); Map<String, Serializable> eventInfo = ctx.getProperties(); String userDest = (String) eventInfo.get(NotificationConstants.DESTINATION_KEY); NotificationImpl notif = (NotificationImpl) eventInfo.get(NotificationConstants.NOTIFICATION_KEY); // send email NuxeoPrincipal recepient = NotificationServiceHelper.getUsersService().getPrincipal( userDest); if (recepient == null) { log.error("Couldn't find user: " + userDest + " to send her a mail."); return; } // XXX hack, principals have only one model DataModel model = recepient.getModel().getDataModels().values().iterator().next(); String email = (String) model.getData("email"); if (email == null || "".equals(email)) { log.error("No email found for user: " + userDest); return; } String subjectTemplate = notif.getSubjectTemplate(); String mailTemplate = null; // mail template can be dynamically computed from a MVEL expression if (notif.getTemplateExpr() != null) { try { mailTemplate = emailHelper.evaluateMvelExpresssion( notif.getTemplateExpr(), eventInfo); } catch (PropertyAccessException pae) { if (log.isDebugEnabled()) { log.debug("Cannot evaluate mail template expression '" + notif.getTemplateExpr() + "' in that context " + eventInfo, pae); } } catch (Exception e) { log.error(e); } } // if there is no mailTemplate evaluated, use the defined one if (StringUtils.isEmpty(mailTemplate)) { mailTemplate = notif.getTemplate(); } log.debug("email: " + email); log.debug("mail template: " + mailTemplate); log.debug("subject template: " + subjectTemplate); Map<String, Object> mail = new HashMap<String, Object>(); mail.put("mail.to", email); String authorUsername = (String) eventInfo.get(NotificationConstants.AUTHOR_KEY); if (authorUsername != null) { NuxeoPrincipal author = NotificationServiceHelper.getUsersService().getPrincipal( authorUsername); mail.put(NotificationConstants.PRINCIPAL_AUTHOR_KEY, author); } mail.put(NotificationConstants.DOCUMENT_KEY, ctx.getSourceDocument()); String subject = notif.getSubject() == null ? NotificationConstants.NOTIFICATION_KEY : notif.getSubject(); subject = notificationService.getEMailSubjectPrefix() + subject; mail.put("subject", subject); mail.put("template", mailTemplate); mail.put("subjectTemplate", subjectTemplate); // Transferring all data from event to email for (String key : eventInfo.keySet()) { mail.put(key, eventInfo.get(key) == null ? "" : eventInfo.get(key)); log.debug("Mail prop: " + key); } mail.put(NotificationConstants.EVENT_ID_KEY, eventId); try { emailHelper.sendmail(mail); } catch (MessagingException e) { log.warn("Failed to send notification email to '" + email + "': " + e.getClass().getName() + ": " + e.getMessage()); } catch (Exception e) { if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder( "Failed to send email with these properties:\n"); for (String key : mail.keySet()) { sb.append("\t " + key + ": " + mail.get(key) + "\n"); } log.debug(sb.toString()); } throw new ClientException("Failed to send notification email ", e); } } /** * Adds the concerned users to the list of targeted users for these * notifications. */ private void gatherConcernedUsersForDocument(CoreSession coreSession, DocumentModel doc, List<Notification> notifs, Map<Notification, List<String>> targetUsers) throws Exception { if (doc.getPath().segmentCount() > 1) { log.debug("Searching document: " + doc.getName()); getInterstedUsers(doc, notifs, targetUsers); if (doc.getParentRef() != null && coreSession.exists(doc.getParentRef())) { DocumentModel parent = getDocumentParent(coreSession, doc); gatherConcernedUsersForDocument(coreSession, parent, notifs, targetUsers); } } } private DocumentModel getDocumentParent(CoreSession coreSession, DocumentModel doc) throws ClientException { if (doc == null) { return null; } return coreSession.getDocument(doc.getParentRef()); } private void getInterstedUsers(DocumentModel doc, List<Notification> notifs, Map<Notification, List<String>> targetUsers) throws Exception { for (Notification notification : notifs) { if (!notification.getAutoSubscribed()) { List<String> userGroup = notificationService.getSubscribers( notification.getName(), doc.getId()); for (String subscriptor : userGroup) { if (subscriptor != null) { if (isUser(subscriptor)) { storeUserForNotification(notification, subscriptor.substring(5), targetUsers); } else { // it is a group - get all users and send // notifications to them List<String> usersOfGroup = getGroupMembers(subscriptor.substring(6)); if (usersOfGroup != null && !usersOfGroup.isEmpty()) { for (String usr : usersOfGroup) { storeUserForNotification(notification, usr, targetUsers); } } } } } } else { // An automatic notification happens // should be sent to interested users targetUsers.put(notification, new ArrayList<String>()); } } } private static void storeUserForNotification(Notification notification, String user, Map<Notification, List<String>> targetUsers) { List<String> subscribedUsers = targetUsers.get(notification); if (subscribedUsers == null) { targetUsers.put(notification, new ArrayList<String>()); } if (!targetUsers.get(notification).contains(user)) { targetUsers.get(notification).add(user); } } private boolean isDeleteEvent(String eventId) { List<String> deletionEvents = new ArrayList<String>(); deletionEvents.add("aboutToRemove"); deletionEvents.add("documentRemoved"); return deletionEvents.contains(eventId); } private boolean isUser(String subscriptor) { return subscriptor != null && subscriptor.startsWith("user:"); } public boolean isInterestedInNotification(Notification notif) { return notif != null && "email".equals(notif.getChannel()); } public DocumentViewCodecManager getDocLocator() { if (docLocator == null) { try { docLocator = Framework.getService(DocumentViewCodecManager.class); if (docLocator == null) { log.warn("Could not get service for document view manager"); } } catch (Exception e) { log.info("Could not get service for document view manager"); } } return docLocator; } public EmailHelper getEmailHelper() { return emailHelper; } public void setEmailHelper(EmailHelper emailHelper) { this.emailHelper = emailHelper; } }
package org.apache.velocity.io; import java.io.IOException; import java.io.Writer; /** * Implementation of a fast Writer. It was originally taken from JspWriter * and modified to have less syncronization going on. * * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author Anil K. Vijendran * @version $Id: VelocityWriter.java,v 1.8 2003/08/24 17:31:12 dlr Exp $ */ public final class VelocityWriter extends Writer { /** * constant indicating that the Writer is not buffering output */ public static final int NO_BUFFER = 0; /** * constant indicating that the Writer is buffered and is using the * implementation default buffer size */ public static final int DEFAULT_BUFFER = -1; /** * constant indicating that the Writer is buffered and is unbounded; * this is used in BodyContent */ public static final int UNBOUNDED_BUFFER = -2; protected int bufferSize; protected boolean autoFlush; private Writer writer; private char cb[]; private int nextChar; private static int defaultCharBufferSize = 8 * 1024; private boolean flushed = false; /** * Create a buffered character-output stream that uses a default-sized * output buffer. * * @param response A Servlet Response */ public VelocityWriter(Writer writer) { this(writer, defaultCharBufferSize, true); } /** * private constructor. */ private VelocityWriter(int bufferSize, boolean autoFlush) { this.bufferSize = bufferSize; this.autoFlush = autoFlush; } /** * This method returns the size of the buffer used by the JspWriter. * * @return the size of the buffer in bytes, or 0 is unbuffered. */ public int getBufferSize() { return bufferSize; } /** * This method indicates whether the JspWriter is autoFlushing. * * @return if this JspWriter is auto flushing or throwing IOExceptions on * buffer overflow conditions */ public boolean isAutoFlush() { return autoFlush; } public VelocityWriter(Writer writer, int sz, boolean autoFlush) { this(sz, autoFlush); if (sz < 0) throw new IllegalArgumentException("Buffer size <= 0"); this.writer = writer; cb = sz == 0 ? null : new char[sz]; nextChar = 0; } private final void init( Writer writer, int sz, boolean autoFlush ) { this.writer= writer; if( sz > 0 && ( cb == null || sz > cb.length ) ) cb=new char[sz]; nextChar = 0; this.autoFlush=autoFlush; this.bufferSize=sz; } /** * Flush the output buffer to the underlying character stream, without * flushing the stream itself. This method is non-private only so that it * may be invoked by PrintStream. */ private final void flushBuffer() throws IOException { if (bufferSize == 0) return; flushed = true; if (nextChar == 0) return; writer.write(cb, 0, nextChar); nextChar = 0; } /** * Discard the output buffer. */ public final void clear() { nextChar = 0; } private final void bufferOverflow() throws IOException { throw new IOException("overflow"); } /** * Flush the stream. * */ public final void flush() throws IOException { flushBuffer(); if (writer != null) { writer.flush(); } } /** * Close the stream. * */ public final void close() throws IOException { if (writer == null) return; flush(); } /** * @return the number of bytes unused in the buffer */ public final int getRemaining() { return bufferSize - nextChar; } /** * Write a single character. * */ public final void write(int c) throws IOException { if (bufferSize == 0) { writer.write(c); } else { if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); cb[nextChar++] = (char) c; } } /** * Our own little min method, to avoid loading * <code>java.lang.Math</code> if we've run out of file * descriptors and we're trying to print a stack trace. */ private final int min(int a, int b) { return (a < b ? a : b); } /** * Write a portion of an array of characters. * * <p> Ordinarily this method stores characters from the given array into * this stream's buffer, flushing the buffer to the underlying stream as * needed. If the requested length is at least as large as the buffer, * however, then this method will flush the buffer and write the characters * directly to the underlying stream. Thus redundant * <code>DiscardableBufferedWriter</code>s will not copy data unnecessarily. * * @param cbuf A character array * @param off Offset from which to start reading characters * @param len Number of characters to write * */ public final void write(char cbuf[], int off, int len) throws IOException { if (bufferSize == 0) { writer.write(cbuf, off, len); return; } if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); writer.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write an array of characters. This method cannot be inherited from the * Writer class because it must suppress I/O exceptions. */ public final void write(char buf[]) throws IOException { write(buf, 0, buf.length); } /** * Write a portion of a String. * * @param s String to be written * @param off Offset from which to start reading characters * @param len Number of characters to be written * */ public final void write(String s, int off, int len) throws IOException { if (bufferSize == 0) { writer.write(s, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); s.getChars(b, b + d, cb, nextChar); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write a string. This method cannot be inherited from the Writer class * because it must suppress I/O exceptions. */ public final void write(String s) throws IOException { write(s, 0, s.length()); } /** * resets this class so that it can be reused * */ public final void recycle( Writer writer) { this.writer = writer; flushed = false; clear(); } }
package fr.openwide.core.jpa.more.business.task.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.util.Assert; import fr.openwide.core.infinispan.model.ILock; import fr.openwide.core.infinispan.model.IPriorityQueue; import fr.openwide.core.spring.util.SpringBeanUtils; public final class TaskConsumer { private static final String THREAD_NAME_FORMAT = "TaskConsumer-%1$s-%2$s"; @Autowired private ApplicationContext applicationContext; private final TaskQueue queue; private final int threadIdForThisQueue; private ConsumerThread thread; private final ILock lock; private final IPriorityQueue priorityQueue; public TaskConsumer(TaskQueue queue, int threadIdForThisQueue) { this(queue, threadIdForThisQueue, null, null); } public TaskConsumer(TaskQueue queue, int threadIdForThisQueue, ILock lock, IPriorityQueue priorityQueue) { Assert.notNull(queue, "[Assertion failed] - this argument is required; it must not be null"); this.queue = queue; this.threadIdForThisQueue = threadIdForThisQueue; this.lock = lock; this.priorityQueue = priorityQueue; } public TaskQueue getQueue() { return queue; } public void start() { start(0L); } /** * @param startDelay A length of time the consumer thread will wait before its first access to the task queue. */ public synchronized void start(long startDelay) { if (thread == null || !thread.isAlive()) { // synchronized access String id = String.format(THREAD_NAME_FORMAT, queue.getId(), threadIdForThisQueue); if (lock != null) { thread = new ConsumerInfinispanAwareThread( id, startDelay, queue, lock, priorityQueue); } else { thread = new ConsumerThread( id, startDelay, queue ); } SpringBeanUtils.autowireBean(applicationContext, thread); thread.start(); } } public synchronized void stop(long stopTimeout) { if (thread != null) { // synchronized access thread.stop(stopTimeout); thread = null; } } public boolean isWorking() { return thread != null && thread.isWorking(); } }
package org.jdesktop.swingx; import java.awt.AlphaComposite; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Composite; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.LayoutManager; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.Timer; /** * <code>JXCollapsiblePane</code> provides a component which can collapse or * expand its content area with animation and fade in/fade out effects. * It also acts as a standard container for other Swing components. * * <p> * In this example, the <code>JXCollapsiblePane</code> is used to build * a Search pane which can be shown and hidden on demand. * * <pre> * <code> * JXCollapsiblePane cp = new JXCollapsiblePane(); * * // JXCollapsiblePane can be used like any other container * cp.setLayout(new BorderLayout()); * * // the Controls panel with a textfield to filter the tree * JPanel controls = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0)); * controls.add(new JLabel("Search:")); * controls.add(new JTextField(10)); * controls.add(new JButton("Refresh")); * controls.setBorder(new TitledBorder("Filters")); * cp.add("Center", controls); * * JXFrame frame = new JXFrame(); * frame.setLayout(new BorderLayout()); * * // Put the "Controls" first * frame.add("North", cp); * * // Then the tree - we assume the Controls would somehow filter the tree * JScrollPane scroll = new JScrollPane(new JTree()); * frame.add("Center", scroll); * * // Show/hide the "Controls" * JButton toggle = new JButton(cp.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)); * toggle.setText("Show/Hide Search Panel"); * frame.add("South", toggle); * * frame.pack(); * frame.setVisible(true); * </code> * </pre> * * <p> * The <code>JXCollapsiblePane</code> has a default toggle action registered * under the name {@link #TOGGLE_ACTION}. Bind this action to a button and * pressing the button will automatically toggle the pane between expanded * and collapsed states. Additionally, you can define the icons to use through * the {@link #EXPAND_ICON} and {@link #COLLAPSE_ICON} properties on the action. * Example * <pre> * <code> * // get the built-in toggle action * Action toggleAction = collapsible.getActionMap(). * get(JXCollapsiblePane.TOGGLE_ACTION); * * // use the collapse/expand icons from the JTree UI * toggleAction.putValue(JXCollapsiblePane.COLLAPSE_ICON, * UIManager.getIcon("Tree.expandedIcon")); * toggleAction.putValue(JXCollapsiblePane.EXPAND_ICON, * UIManager.getIcon("Tree.collapsedIcon")); * </code> * </pre> * * <p> * Note: <code>JXCollapsiblePane</code> requires its parent container to have a * {@link java.awt.LayoutManager} using {@link #getPreferredSize()} when * calculating its layout (example {@link org.jdesktop.swingx.VerticalLayout}, * {@link java.awt.BorderLayout}). * * @javabean.attribute * name="isContainer" * value="Boolean.TRUE" * rtexpr="true" * * @javabean.attribute * name="containerDelegate" * value="getContentPane" * * @javabean.class * name="JXCollapsiblePane" * shortDescription="A pane which hides its content with an animation." * stopClass="java.awt.Component" * * @author rbair (from the JDNC project) * @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a> */ public class JXCollapsiblePane extends JPanel { /** * Used when generating PropertyChangeEvents for the "animationState" * property. The PropertyChangeEvent will takes the following different values * for {@link PropertyChangeEvent#getNewValue()}: * <ul> * <li><code>reinit</code> every time the animation starts * <li><code>expanded</code> when the animation ends and the pane is expanded * <li><code>collapsed</code> when the animation ends and the pane is collapsed * </ul> */ public final static String ANIMATION_STATE_KEY = "animationState"; /** * JXCollapsible has a built-in toggle action which can be bound to buttons. * Accesses the action through * <code>collapsiblePane.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)</code>. */ public final static String TOGGLE_ACTION = "toggle"; /** * The icon used by the "toggle" action when the JXCollapsiblePane is * expanded, i.e the icon which indicates the pane can be collapsed. */ public final static String COLLAPSE_ICON = "collapseIcon"; /** * The icon used by the "toggle" action when the JXCollapsiblePane is * collapsed, i.e the icon which indicates the pane can be expanded. */ public final static String EXPAND_ICON = "expandIcon"; /** * Indicates whether the component is collapsed or expanded */ private boolean collapsed = false; /** * Timer used for doing the transparency animation (fade-in) */ private Timer animateTimer; private AnimationListener animator; private int currentHeight = -1; private WrapperContainer wrapper; private boolean useAnimation = true; private AnimationParams animationParams; /** * Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane * and a vertical {@link VerticalLayout} with a gap of 2 pixels as layout * manager. */ public JXCollapsiblePane() { this(new BorderLayout(0, 0)); } /** * Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane * and the given LayoutManager */ public JXCollapsiblePane(LayoutManager layout) { super(layout); JPanel panel = new JPanel(); panel.setLayout(new VerticalLayout(2)); setContentPane(panel); animator = new AnimationListener(); setAnimationParams(new AnimationParams(30, 8, 0.01f, 1.0f)); // add an action to automatically toggle the state of the pane getActionMap().put(TOGGLE_ACTION, new ToggleAction()); } /** * Toggles the JXCollapsiblePane state and updates its icon based on the * JXCollapsiblePane "collapsed" status. */ private class ToggleAction extends AbstractAction implements PropertyChangeListener { public ToggleAction() { super(TOGGLE_ACTION); // the action must track the collapsed status of the pane to update its // icon JXCollapsiblePane.this.addPropertyChangeListener("collapsed", this); } @Override public void putValue(String key, Object newValue) { super.putValue(key, newValue); if (EXPAND_ICON.equals(key) || COLLAPSE_ICON.equals(key)) { updateIcon(); } } public void actionPerformed(ActionEvent e) { setCollapsed(!isCollapsed()); } public void propertyChange(PropertyChangeEvent evt) { updateIcon(); } void updateIcon() { if (isCollapsed()) { putValue(SMALL_ICON, getValue(EXPAND_ICON)); } else { putValue(SMALL_ICON, getValue(COLLAPSE_ICON)); } } } public void setContentPane(Container contentPanel) { if (contentPanel == null) { throw new IllegalArgumentException("Content pane can't be null"); } if (wrapper != null) { //these next two lines are as they are because if I try to remove //the "wrapper" component directly, then super.remove(comp) ends up //calling remove(int), which is overridden in this class, leading to //improper behavior. assert super.getComponent(0) == wrapper; super.remove(0); } wrapper = new WrapperContainer(contentPanel); super.addImpl(wrapper, BorderLayout.CENTER, -1); } /** * @return the content pane */ public Container getContentPane() { return wrapper.c; } /** * Overriden to redirect call to the content pane. */ public void setLayout(LayoutManager mgr) { // wrapper can be null when setLayout is called by "super()" constructor if (wrapper != null) { getContentPane().setLayout(mgr); } } /** * Overriden to redirect call to the content pane. */ protected void addImpl(Component comp, Object constraints, int index) { getContentPane().add(comp, constraints, index); } /** * Overriden to redirect call to the content pane */ public void remove(Component comp) { getContentPane().remove(comp); } /** * Overriden to redirect call to the content pane. */ public void remove(int index) { getContentPane().remove(index); } /** * Overriden to redirect call to the content pane. */ public void removeAll() { getContentPane().removeAll(); } /** * If true, enables the animation when pane is collapsed/expanded. If false, * animation is turned off. * * <p> * When animated, the <code>JXCollapsiblePane</code> will progressively * reduce (when collapsing) or enlarge (when expanding) the height of its * content area until it becomes 0 or until it reaches the preferred height of * the components it contains. The transparency of the content area will also * change during the animation. * * <p> * If not animated, the <code>JXCollapsiblePane</code> will simply hide * (collapsing) or show (expanding) its content area. * * @param animated * @javabean.property bound="true" preferred="true" */ public void setAnimated(boolean animated) { if (animated != useAnimation) { useAnimation = animated; firePropertyChange("animated", !useAnimation, useAnimation); } } /** * @return true if the pane is animated, false otherwise * @see #setAnimated(boolean) */ public boolean isAnimated() { return useAnimation; } /** * @return true if the pane is collapsed, false if expanded */ public boolean isCollapsed() { return collapsed; } /** * Expands or collapses this <code>JXCollapsiblePane</code>. * * <p> * If the component is collapsed and <code>val</code> is false, then this * call expands the JXCollapsiblePane, such that the entire JXCollapsiblePane * will be visible. If {@link #isAnimated()} returns true, the expansion will * be accompanied by an animation. * * <p> * However, if the component is expanded and <code>val</code> is true, then * this call collapses the JXCollapsiblePane, such that the entire * JXCollapsiblePane will be invisible. If {@link #isAnimated()} returns true, * the collapse will be accompanied by an animation. * * @see #isAnimated() * @see #setAnimated(boolean) * @javabean.property * bound="true" * preferred="true" */ public void setCollapsed(boolean val) { if (collapsed != val) { collapsed = val; if (isAnimated()) { if (collapsed) { setAnimationParams(new AnimationParams(30, Math.max(8, wrapper .getHeight() / 10), 1.0f, 0.01f)); animator.reinit(wrapper.getHeight(), 0); animateTimer.start(); } else { setAnimationParams(new AnimationParams(30, Math.max(8, getContentPane().getPreferredSize().height / 10), 0.01f, 1.0f)); animator.reinit(wrapper.getHeight(), getContentPane() .getPreferredSize().height); animateTimer.start(); } } else { wrapper.c.setVisible(!collapsed); invalidate(); doLayout(); } repaint(); firePropertyChange("collapsed", !collapsed, collapsed); } } public Dimension getMinimumSize() { return getPreferredSize(); } /** * The critical part of the animation of this <code>JXCollapsiblePane</code> * relies on the calculation of its preferred size. During the animation, its * preferred size (specially its height) will change, when expanding, from 0 * to the preferred size of the content pane, and the reverse when collapsing. * * @return this component preferred size */ public Dimension getPreferredSize() { /* * The preferred size is calculated based on the current position of the * component in its animation sequence. If the Component is expanded, then * the preferred size will be the preferred size of the top component plus * the preferred size of the embedded content container. <p>However, if the * scroll up is in any state of animation, the height component of the * preferred size will be the current height of the component (as contained * in the currentHeight variable) */ Dimension dim; if (!isAnimated()) { if (getContentPane().isVisible()) { dim = getContentPane().getPreferredSize(); } else { dim = super.getPreferredSize(); } } else { dim = new Dimension(getContentPane().getPreferredSize()); if (!getContentPane().isVisible() && currentHeight != -1) { dim.height = currentHeight; } } return dim; } private void setAnimationParams(AnimationParams params) { if (params == null) { throw new IllegalArgumentException( "params can't be null"); } if (animateTimer != null) { animateTimer.stop(); } animationParams = params; animateTimer = new Timer(animationParams.waitTime, animator); animateTimer.setInitialDelay(0); } /** * Tagging interface for containers in a JXCollapsiblePane hierarchy who needs * to be revalidated (invalidate/validate/repaint) when the pane is expanding * or collapsing. Usually validating only the parent of the JXCollapsiblePane * is enough but there might be cases where the parent parent must be * validated. */ public static interface JCollapsiblePaneContainer { Container getValidatingContainer(); } /** * Parameters controlling the animations */ private static class AnimationParams { final int waitTime; final int deltaY; final float alphaStart; final float alphaEnd; /** * @param waitTime * the amount of time in milliseconds to wait between calls to the * animation thread * @param deltaY * the delta in the Y direction to inc/dec the size of the scroll * up by * @param alphaStart * the starting alpha transparency level * @param alphaEnd * the ending alpha transparency level */ public AnimationParams(int waitTime, int deltaY, float alphaStart, float alphaEnd) { this.waitTime = waitTime; this.deltaY = deltaY; this.alphaStart = alphaStart; this.alphaEnd = alphaEnd; } } /** * This class actual provides the animation support for scrolling up/down this * component. This listener is called whenever the animateTimer fires off. It * fires off in response to scroll up/down requests. This listener is * responsible for modifying the size of the content container and causing it * to be repainted. * * @author Richard Bair */ private final class AnimationListener implements ActionListener { /** * Mutex used to ensure that the startHeight/finalHeight are not changed * during a repaint operation. */ private final Object ANIMATION_MUTEX = "Animation Synchronization Mutex"; /** * This is the starting height when animating. If > finalHeight, then the * animation is going to be to scroll up the component. If it is < then * finalHeight, then the animation will scroll down the component. */ private int startHeight = 0; /** * This is the final height that the content container is going to be when * scrolling is finished. */ private int finalHeight = 0; /** * The current alpha setting used during "animation" (fade-in/fade-out) */ private float animateAlpha = 1.0f; public void actionPerformed(ActionEvent e) { /* * Pre-1) If startHeight == finalHeight, then we're done so stop the timer * 1) Calculate whether we're contracting or expanding. 2) Calculate the * delta (which is either positive or negative, depending on the results * of (1)) 3) Calculate the alpha value 4) Resize the ContentContainer 5) * Revalidate/Repaint the content container */ synchronized (ANIMATION_MUTEX) { if (startHeight == finalHeight) { animateTimer.stop(); animateAlpha = animationParams.alphaEnd; // keep the content pane hidden when it is collapsed, other it may // still receive focus. if (finalHeight > 0) { wrapper.showContent(); validate(); JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null, "expanded"); return; } else { JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null, "collapsed"); } } final boolean contracting = startHeight > finalHeight; final int delta_y = contracting?-1 * animationParams.deltaY :animationParams.deltaY; int newHeight = wrapper.getHeight() + delta_y; if (contracting) { if (newHeight < finalHeight) { newHeight = finalHeight; } } else { if (newHeight > finalHeight) { newHeight = finalHeight; } } animateAlpha = (float)newHeight / (float)wrapper.c.getPreferredSize().height; Rectangle bounds = wrapper.getBounds(); int oldHeight = bounds.height; bounds.height = newHeight; wrapper.setBounds(bounds); bounds = getBounds(); bounds.height = (bounds.height - oldHeight) + newHeight; currentHeight = bounds.height; setBounds(bounds); startHeight = newHeight; // it happens the animateAlpha goes over the alphaStart/alphaEnd range // this code ensures it stays in bounds. This behavior is seen when // component such as JTextComponents are used in the container. if (contracting) { // alphaStart > animateAlpha > alphaEnd if (animateAlpha < animationParams.alphaEnd) { animateAlpha = animationParams.alphaEnd; } if (animateAlpha > animationParams.alphaStart) { animateAlpha = animationParams.alphaStart; } } else { // alphaStart < animateAlpha < alphaEnd if (animateAlpha > animationParams.alphaEnd) { animateAlpha = animationParams.alphaEnd; } if (animateAlpha < animationParams.alphaStart) { animateAlpha = animationParams.alphaStart; } } wrapper.alpha = animateAlpha; validate(); } } void validate() { Container parent = SwingUtilities.getAncestorOfClass( JCollapsiblePaneContainer.class, JXCollapsiblePane.this); if (parent != null) { parent = ((JCollapsiblePaneContainer)parent).getValidatingContainer(); } else { parent = getParent(); } if (parent != null) { if (parent instanceof JComponent) { ((JComponent)parent).revalidate(); } else { parent.invalidate(); } parent.doLayout(); parent.repaint(); } } /** * Reinitializes the timer for scrolling up/down the component. This method * is properly synchronized, so you may make this call regardless of whether * the timer is currently executing or not. * * @param startHeight * @param stopHeight */ public void reinit(int startHeight, int stopHeight) { synchronized (ANIMATION_MUTEX) { JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null, "reinit"); this.startHeight = startHeight; this.finalHeight = stopHeight; animateAlpha = animationParams.alphaStart; currentHeight = -1; wrapper.showImage(); } } } private final class WrapperContainer extends JPanel { private BufferedImage img; private Container c; float alpha = 1.0f; public WrapperContainer(Container c) { super(new BorderLayout()); this.c = c; add(c, BorderLayout.CENTER); // we must ensure the container is opaque. It is not opaque it introduces // painting glitches specially on Linux with JDK 1.5 and GTK look and feel. // GTK look and feel calls setOpaque(false) if (c instanceof JComponent && !((JComponent)c).isOpaque()) { ((JComponent)c).setOpaque(true); } } public void showImage() { // render c into the img makeImage(); c.setVisible(false); } public void showContent() { currentHeight = -1; c.setVisible(true); } void makeImage() { // if we have no image or if the image has changed if (getGraphicsConfiguration() != null && getWidth() > 0) { Dimension dim = c.getPreferredSize(); // width and height must be > 0 to be able to create an image if (dim.height > 0) { img = getGraphicsConfiguration().createCompatibleImage(getWidth(), dim.height); c.setSize(getWidth(), dim.height); c.paint(img.getGraphics()); } else { img = null; } } } public void paintComponent(Graphics g) { if (!useAnimation || c.isVisible()) { super.paintComponent(g); } else { // within netbeans, it happens we arrive here and the image has not been // created yet. We ensure it is. if (img == null) { makeImage(); } // and we paint it only if it has been created and only if we have a // valid graphics if (g != null && img != null) { // draw the image with y being height - imageHeight g.drawImage(img, 0, getHeight() - img.getHeight(), null); } } } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D)g; Composite oldComp = g2d.getComposite(); Composite alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha); g2d.setComposite(alphaComp); super.paint(g2d); g2d.setComposite(oldComp); } } }
package com.elfec.cobranza.business_logic; import java.net.ConnectException; import java.sql.SQLException; import org.json.JSONException; import org.json.JSONObject; import android.nfc.FormatException; import com.elfec.cobranza.model.enums.ConnectionParam; import com.elfec.cobranza.model.results.DataAccessResult; import com.elfec.cobranza.remote_data_access.RoleAccessRDA; import com.elfec.cobranza.settings.PreferencesManager; import com.elfec.cobranza.settings.remote_data_access.OracleDatabaseSettings; /** * Se encarga de la lgica de negocio relacionada a roles * @author drodriguez * */ public class RoleAccessManager { /** * Habilita el rol MOVIL_COBRANZA * @param username * @param password * @return resultado del acceso remoto a datos */ public static DataAccessResult<Void> enableMobileCollectionRole(String username, String password) { DataAccessResult<Void> result = new DataAccessResult<Void>(true); String errorWhileEnablingRole = "Error al activar el rol <b>MOVIL_COBRANZA</b>: "; JSONObject settings; try { settings = OracleDatabaseSettings.getJSONConnectionSettings(PreferencesManager.getApplicationContext()); RoleAccessRDA.enableRole(username, password, settings.getString(ConnectionParam.ROLE.toString()), settings.getString(ConnectionParam.PASSWORD.toString())); } catch (JSONException e) { result.addError(new FormatException(errorWhileEnablingRole+"Los parmetros de la configuracin de conexin a la base de datos tienen un formato incorrecto!")); e.printStackTrace(); } catch (ConnectException e) { result.addError(new ConnectException(errorWhileEnablingRole+e.getMessage())); } catch (SQLException e) { result.addError(new SQLException(errorWhileEnablingRole+e.getMessage())); } return result; } }
package com.esotericsoftware.yamlbeans; import com.esotericsoftware.yamlbeans.Beans.Property; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; /** Stores a constructor, parameters names, and property values so construction can be deferred until all property values are * known. * @author <a href="mailto:misc@n4te.com">Nathan Sweet</a> */ class DeferredConstruction { private final Constructor constructor; private final String[] parameterNames; private final ParameterValue[] parameterValues; private final List<PropertyValue> propertyValues = new ArrayList(16); public DeferredConstruction (Constructor constructor, String[] parameterNames) { this.constructor = constructor; this.parameterNames = parameterNames; parameterValues = new ParameterValue[parameterNames.length]; } public Object construct () throws InvocationTargetException { try { Object[] parameters = new Object[parameterValues.length]; int i = 0; boolean missingParameter = false; for (ParameterValue parameter : parameterValues) { if (parameter == null) missingParameter = true; else parameters[i++] = parameter.value; } Object object; if (missingParameter) { try { object = constructor.getDeclaringClass().getConstructor().newInstance(); } catch (Exception ex) { throw new InvocationTargetException(new YamlException("Missing constructor property: " + parameterNames[i])); } } else object = constructor.newInstance(parameters); for (PropertyValue propertyValue : propertyValues) { if (propertyValue.value != null) propertyValue.property.set(object, propertyValue.value); } return object; } catch (Exception ex) { throw new InvocationTargetException(ex, "Error constructing instance of class: " + constructor.getDeclaringClass().getName()); } } public void storeProperty (Property property, Object value) { int index = 0; for (String name : parameterNames) { if (property.getName().equals(name)) { ParameterValue parameterValue = new ParameterValue(); parameterValue.value = value; parameterValues[index] = parameterValue; return; } index++; } PropertyValue propertyValue = new PropertyValue(); propertyValue.property = property; propertyValue.value = value; propertyValues.add(propertyValue); } public boolean hasParameter (String name) { for (String s : parameterNames) if (s.equals(name)) return true; return false; } static class PropertyValue { Property property; Object value; } static class ParameterValue { Object value; } }
package com.jcwhatever.bukkit.generic.commands; import com.jcwhatever.bukkit.generic.commands.arguments.CommandArguments; import com.jcwhatever.bukkit.generic.commands.exceptions.InvalidValueException; import com.jcwhatever.bukkit.generic.internal.Lang; import com.jcwhatever.bukkit.generic.messaging.Messenger; import org.bukkit.command.CommandSender; import org.bukkit.permissions.PermissionDefault; @ICommandInfo( command={"about"}, usage="/{command} about", description="Get information about the plugin.", permissionDefault=PermissionDefault.TRUE, isHelpVisible=false) public class AboutCommand extends AbstractCommand { static final String _PLUGIN_NAME = "{BOLD}{GREEN}{plugin-name} {plugin-version}"; static final String _AUTHOR = "Plugin by {plugin-author}"; static final String _HELP = "{AQUA}For a list of commands, type '/{plugin-command} ?'"; @Override public void execute(CommandSender sender, CommandArguments args) throws InvalidValueException { Messenger.tell(_plugin, sender, " Messenger.tell(_plugin, sender, Lang.get(_plugin, _PLUGIN_NAME)); if (_plugin.getDescription().getAuthors() != null && !_plugin.getDescription().getAuthors().isEmpty()) { Messenger.tell(_plugin, sender, Lang.get(_plugin, _AUTHOR)); } Messenger.tell(_plugin, sender, Lang.get(_plugin, _HELP)); Messenger.tell(_plugin, sender, " } }