answer
stringlengths 17
10.2M
|
|---|
package ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.main;
import java.util.List;
import ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.model.Album;
import ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.dao.AlbumDAO;
import ar.edu.unrc.exa.dc.dose2016.riocuartobandasderock.dao.impl.AlbumDaoImpl;
import spark.Request;
import spark.Response;
public class AlbumController {
protected static AlbumController unique_instance = null;
protected AlbumDAO dao;
public AlbumController(AlbumDaoImpl albumDaoImpl) {
dao = albumDaoImpl;
}
public static AlbumController getInstance() {
if (unique_instance == null)
unique_instance = new AlbumController(new AlbumDaoImpl());
return unique_instance;
}
public List<Album> getAll(Request req, Response res) {
List<Album> albums = dao.getAllAlbums();
int http_status = albums == null ? 404 : 200;
res.status(http_status);
return albums;
}
public Album getById(Request req, Response res) {
Album album = dao.findById(req.params("id"));
int http_status = album == null ? 404 : 200;
res.status(http_status);
return album;
}
public Boolean create(Request req, Response res) {
boolean result = dao.createAlbum(new Album());
int http_status = result ? 201 : 500;
res.status(http_status);
return result;
}
public Boolean update(Request req, Response res) {
boolean result = dao.updateAlbum(dao.findById(req.params("id")));
int http_status = result ? 200 : 500;
res.status(http_status);
return result;
}
public Boolean delete(Request req, Response res) {
boolean result = dao.deleteAlbum(req.params("id"));
int http_status = result ? 200 : 500;
res.status(http_status);
return result;
}
}
|
package com.github.kory33.UpdateNotificationPlugin.github;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.kory33.UpdateNotificationPlugin.PluginRelease;
import com.github.kory33.UpdateNotificationPlugin.versioning.PluginVersion;
import com.github.kory33.UpdateNotificationPlugin.versioning.SemanticPluginVersion;
public class GithubVersionManager {
private final GithubUpdateNotifyPlugin plugin;
public GithubVersionManager(GithubUpdateNotifyPlugin plugin){
this.plugin = plugin;
}
/**
* Get the latest version release.
* @return reference to the latest version release
* @throws IOException
* @throws ClientProtocolException
* @throws JSONException
*/
public PluginRelease getLatestVersionRelease(){
List<PluginRelease> releaseList = null;
try{
releaseList = this.getReleasesList();
} catch (Exception e) {
this.plugin.getLogger().log(Level.WARNING, "Caught exceptions while fetching and parsing data from Github:\n" + e.getMessage());
return null;
}
if (releaseList.isEmpty()) {
return null;
}
return releaseList.get(0);
}
/**
* get the Github release api's url from the plugin
* @return
*/
private String getGHReleaseAPIUrl() {
return "https://api.github.com/repos/" + this.plugin.getGithubRepository() + "/releases";
}
private String getReleaseJSONString() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGetMethod = new HttpGet(this.getGHReleaseAPIUrl());
// Execute the http get method and gain the response from the server
HttpResponse response = httpClient.execute(httpGetMethod);
int responseStatusCode = response.getStatusLine().getStatusCode();
if (responseStatusCode != 200) {
throw new HttpResponseException(
responseStatusCode, "Got unexpected status response. Is the url " + this.getGHReleaseAPIUrl() + " proper?"
);
}
// get and return the response body
HttpEntity responseEntity = response.getEntity();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line);
}
return stringBuilder.toString();
}
/**
* Get the plugin-release's list.
* <p>
* This method involves downloading data from Github.
* @return list of releases
* @throws JSONException
* @throws ClientProtocolException
* @throws IOException
*/
public List<PluginRelease> getReleasesList() throws JSONException, ClientProtocolException, IOException{
JSONArray releaseJsonArray = new JSONArray(this.getReleaseJSONString());
List<PluginRelease> versionList= new ArrayList<>();
for(int i = 0; i < releaseJsonArray.length(); i++) {
JSONObject releaseJson = releaseJsonArray.getJSONObject(i);
try{
PluginVersion releaseVersion = new SemanticPluginVersion(releaseJson.getString("tag_name"));
String releaseHTMLUrl = releaseJson.getString("html_url");
versionList.add(new PluginRelease(releaseVersion, releaseHTMLUrl));
}catch(Exception e){}
}
return versionList;
}
}
|
package com.insightfullogic.honest_profiler.core.collector;
import com.insightfullogic.honest_profiler.core.Monitor;
import com.insightfullogic.honest_profiler.core.parser.LogEventListener;
import com.insightfullogic.honest_profiler.core.parser.Method;
import com.insightfullogic.honest_profiler.core.parser.StackFrame;
import com.insightfullogic.honest_profiler.core.parser.TraceStart;
import com.insightfullogic.honest_profiler.core.sources.LogSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
public class FlameGraphCollector implements LogEventListener
{
private final Map<Long, Method> methods = new HashMap<>();
private final FlameGraph flameGraph = new FlameGraph();
private FlameTrace trace;
private List<Long> lastMethodIds = new ArrayList<>();
private List<Long> currentMethodIds = new ArrayList<>();
private static Method unknownMethod = new Method(-1, "<unknown>", "unknown.Unknown", "unknown");
@Override
public void handle(TraceStart traceStart)
{
addCurrentTrace();
lastMethodIds = currentMethodIds;
currentMethodIds = new ArrayList<>();
}
@Override
public void handle(StackFrame stackFrame)
{
currentMethodIds.add(stackFrame.getMethodId());
}
@Override
public void handle(Method newMethod)
{
methods.put(newMethod.getMethodId(), newMethod);
}
@Override
public void endOfLog()
{
addCurrentTrace();
}
public FlameGraph collect()
{
return flameGraph;
}
public static FlameGraph readFlamegraph(LogSource source) throws Exception
{
FlameGraphCollector collector = new FlameGraphCollector();
Monitor.consumeFile(source, collector);
return collector.collect();
}
private void addCurrentTrace()
{
if (currentMethodIds == null || currentMethodIds.size() == 0)
return;
if (lastMethodIds.equals(currentMethodIds))
{
trace.incrementWeight();
return;
}
List<Method> methods = currentMethodIds
.stream()
.map(method -> this.methods.getOrDefault(method, unknownMethod))
.collect(toList());
trace = new FlameTrace(methods, 1);
flameGraph.onNewTrace(trace);
}
}
|
/**
* An implementation of the traveling salesman problem in Java using dynamic programming to improve
* the time complexity from O(n!) to O(n^2 * 2^n).
*
* <p>Time Complexity: O(n^2 * 2^n) Space Complexity: O(n * 2^n)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.graphtheory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TspDynamicProgrammingIterative {
private final int N, start;
private final double[][] distance;
private List<Integer> tour = new ArrayList<>();
private double minTourCost = Double.POSITIVE_INFINITY;
private boolean ranSolver = false;
public TspDynamicProgrammingIterative(double[][] distance) {
this(0, distance);
}
public TspDynamicProgrammingIterative(int start, double[][] distance) {
N = distance.length;
if (N <= 2) throw new IllegalStateException("N <= 2 not yet supported.");
if (N != distance[0].length) throw new IllegalStateException("Matrix must be square (n x n)");
if (start < 0 || start >= N) throw new IllegalArgumentException("Invalid start node.");
if (N > 32)
throw new IllegalArgumentException(
"Matrix too large! A matrix that size for the DP TSP problem with a time complexity of"
+ "O(n^2*2^n) requires way too much computation for any modern home computer to handle");
this.start = start;
this.distance = distance;
}
// Returns the optimal tour for the traveling salesman problem.
public List<Integer> getTour() {
if (!ranSolver) solve();
return tour;
}
// Returns the minimal tour cost.
public double getTourCost() {
if (!ranSolver) solve();
return minTourCost;
}
// Solves the traveling salesman problem and caches solution.
public void solve() {
if (ranSolver) return;
final int END_STATE = (1 << N) - 1;
Double[][] memo = new Double[N][1 << N];
// Add all outgoing edges from the starting node to memo table.
for (int end = 0; end < N; end++) {
if (end == start) continue;
memo[end][(1 << start) | (1 << end)] = distance[start][end];
}
for (int r = 3; r <= N; r++) {
for (int subset : combinations(r, N)) {
if (notIn(start, subset)) continue;
for (int next = 0; next < N; next++) {
if (next == start || notIn(next, subset)) continue;
int subsetWithoutNext = subset ^ (1 << next);
double minDist = Double.POSITIVE_INFINITY;
for (int end = 0; end < N; end++) {
if (end == start || end == next || notIn(end, subset)) continue;
double newDistance = memo[end][subsetWithoutNext] + distance[end][next];
if (newDistance < minDist) {
minDist = newDistance;
}
}
memo[next][subset] = minDist;
}
}
}
// Connect tour back to starting node and minimize cost.
for (int i = 0; i < N; i++) {
if (i == start) continue;
double tourCost = memo[i][END_STATE] + distance[i][start];
if (tourCost < minTourCost) {
minTourCost = tourCost;
}
}
int lastIndex = start;
int state = END_STATE;
tour.add(start);
// Reconstruct TSP path from memo table.
for (int i = 1; i < N; i++) {
int bestIndex = -1;
double bestDist = Double.POSITIVE_INFINITY;
for (int j = 0; j < N; j++) {
if (j == start || notIn(j, state)) continue;
double newDist = memo[j][state] + distance[j][lastIndex];
if (newDist < bestDist) {
bestIndex = j;
bestDist = newDist;
}
}
tour.add(bestIndex);
state = state ^ (1 << bestIndex);
lastIndex = bestIndex;
}
tour.add(start);
Collections.reverse(tour);
ranSolver = true;
}
private static boolean notIn(int elem, int subset) {
return ((1 << elem) & subset) == 0;
}
// This method generates all bit sets of size n where r bits
// are set to one. The result is returned as a list of integer masks.
public static List<Integer> combinations(int r, int n) {
List<Integer> subsets = new ArrayList<>();
combinations(0, 0, r, n, subsets);
return subsets;
}
// To find all the combinations of size r we need to recurse until we have
// selected r elements (aka r = 0), otherwise if r != 0 then we still need to select
// an element which is found after the position of our last selected element
private static void combinations(int set, int at, int r, int n, List<Integer> subsets) {
// Return early if there are more elements left to select than what is available.
int elementsLeftToPick = n - at;
if (elementsLeftToPick < r) return;
// We selected 'r' elements so we found a valid subset!
if (r == 0) {
subsets.add(set);
} else {
for (int i = at; i < n; i++) {
// Try including this element
set ^= (1 << i);
combinations(set, i + 1, r - 1, n, subsets);
// Backtrack and try the instance where we did not include this element
set ^= (1 << i);
}
}
}
public static void main(String[] args) {
// Create adjacency matrix
int n = 6;
double[][] distanceMatrix = new double[n][n];
for (double[] row : distanceMatrix) java.util.Arrays.fill(row, 10000);
distanceMatrix[5][0] = 10;
distanceMatrix[1][5] = 12;
distanceMatrix[4][1] = 2;
distanceMatrix[2][4] = 4;
distanceMatrix[3][2] = 6;
distanceMatrix[0][3] = 8;
int startNode = 0;
TspDynamicProgrammingIterative solver =
new TspDynamicProgrammingIterative(startNode, distanceMatrix);
// Prints: [0, 3, 2, 4, 1, 5, 0]
System.out.println("Tour: " + solver.getTour());
// Print: 42.0
System.out.println("Tour cost: " + solver.getTourCost());
}
}
|
package edu.utah.ece.async.sboldesigner.sbol.editor.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import org.synbiohub.frontend.SynBioHubException;
import org.synbiohub.frontend.SynBioHubFrontend;
import edu.utah.ece.async.sboldesigner.sbol.editor.SBOLEditorPreferences;
import edu.utah.ece.async.sboldesigner.swing.FormBuilder;
import edu.utah.ece.async.sboldesigner.versioning.PersonInfo;
public class RegistryLoginDialog extends JDialog implements ActionListener {
private String backendUrl;
private String uriPrefix;
private Component parent;
private SynBioHubFrontend frontend = null;
private final JButton loginButton = new JButton("Login");
private final JButton cancelButton = new JButton("Cancel");
private final JTextField username = new JTextField("");
private final JPasswordField password = new JPasswordField("");
public RegistryLoginDialog(Component parent, String backendUrl, String uriPrefix) {
super(JOptionPane.getFrameForComponent(parent), "Login to " + backendUrl, true);
this.backendUrl = backendUrl;
this.uriPrefix = uriPrefix;
this.parent = parent;
PersonInfo userInfo = SBOLEditorPreferences.INSTANCE.getUserInfo();
String email = userInfo == null || userInfo.getEmail() == null ? null : userInfo.getEmail().getLocalName();
username.setText(email);
password.setEchoChar('*');
cancelButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
cancelButton.addActionListener(this);
loginButton.addActionListener(this);
getRootPane().setDefaultButton(loginButton);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
buttonPane.add(Box.createHorizontalStrut(100));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(cancelButton);
buttonPane.add(loginButton);
FormBuilder builder = new FormBuilder();
builder.add("Username", username);
builder.add("Password", password);
JPanel mainPanel = builder.build();
mainPanel.setAlignmentX(LEFT_ALIGNMENT);
JLabel infoLabel = new JLabel(
"Login to SynBioHub account. This enables you to upload parts and access your private constructs.");
Container contentPane = getContentPane();
contentPane.add(infoLabel, BorderLayout.PAGE_START);
contentPane.add(mainPanel, BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.PAGE_END);
((JComponent) contentPane).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
public SynBioHubFrontend getSynBioHubFrontend() {
return frontend;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cancelButton) {
setVisible(false);
return;
}
if (e.getSource() == loginButton) {
frontend = new SynBioHubFrontend(backendUrl, uriPrefix);
try {
frontend.login(username.getText(), new String(password.getPassword()));
JOptionPane.showMessageDialog(parent, "Login successful!");
} catch (SynBioHubException e1) {
MessageDialog.showMessage(parent, "Login failed", Arrays.asList(e1.getMessage().split("\"|,")));
frontend = null;
e1.printStackTrace();
}
setVisible(false);
return;
}
}
}
|
package net.earthcomputer.easyeditors.gui.command.slot;
import com.google.common.base.Predicate;
import net.earthcomputer.easyeditors.api.util.Patterns;
import net.earthcomputer.easyeditors.gui.command.CommandSyntaxException;
/**
* A text field which has an integer value
*
* @author Earthcomputer
*
*/
public class CommandSlotIntTextField extends CommandSlotTextField {
private int minValue;
private int maxValue;
public CommandSlotIntTextField(int minWidth, int maxWidth) {
this(minWidth, maxWidth, Integer.MIN_VALUE);
}
public CommandSlotIntTextField(int minWidth, int maxWidth, int minValue) {
this(minWidth, maxWidth, minValue, Integer.MAX_VALUE);
}
public CommandSlotIntTextField(int minWidth, int maxWidth, int minValue, int maxValue) {
super(minWidth, maxWidth);
setContentFilter(new Predicate<String>() {
@Override
public boolean apply(String input) {
if (!Patterns.partialInteger.matcher(input).matches())
return false;
else if (CommandSlotIntTextField.this.minValue >= 0 && input.startsWith("-"))
return false;
else if (CommandSlotIntTextField.this.maxValue < 0 && input.startsWith("+"))
return false;
else
return true;
}
});
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public int readFromArgs(String[] args, int index) throws CommandSyntaxException {
if (index >= args.length)
throw new CommandSyntaxException();
int i;
try {
i = Integer.parseInt(args[index]);
} catch (NumberFormatException e) {
throw new CommandSyntaxException();
}
if (i < minValue || i > maxValue)
throw new CommandSyntaxException();
setText(args[index]);
return 1;
}
/**
*
* @return Whether the value inside this text field is a valid integer
*/
public boolean isValid() {
int i;
try {
i = Integer.parseInt(getText());
} catch (NumberFormatException e) {
return false;
}
return i >= minValue && i <= maxValue;
}
/**
*
* @return The value of this text field, as an integer
*/
public int getIntValue() {
return !isValid() ? (minValue > 0 ? minValue : (maxValue < 0 ? maxValue : 0)) : Integer.parseInt(getText());
}
}
|
package org.broadinstitute.hellbender.utils.runtime;
import com.google.common.io.Files;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.broadinstitute.hellbender.exceptions.GATKException;
import org.broadinstitute.hellbender.utils.Utils;
import java.io.*;
import java.util.Random;
import java.util.concurrent.*;
import java.util.function.Function;
/**
* Facade to Runtime.exec() and java.lang.Process. Handles running an interactive, keep-alive process and returns
* stdout and stderr as strings. Creates separate threads for reading stdout and stderr.
*/
public final class StreamingProcessController extends ProcessControllerBase<CapturedStreamOutputSnapshot> {
private static final Logger logger = LogManager.getLogger(StreamingProcessController.class);
private final ProcessSettings settings;
private final String promptForSynchronization;
private File fifoTempDir = null;
private File fifoFile = null;
// Timeout used when retrieving output from the remote process to prevent the GATK main tool thread from
// excessive blocking. {@link #isOutputAvailable} can be used to to check for output before making a
// blocking call in order to avoid exceeding timeouts.
// NOTE: The StreamingProcessController unit tests include tests that deliberately trigger this timeout to
// ensure that it works correctly. Those tests rely on testNG timeouts to prevent the test suite from hanging
// in the event that this timeout mechanism fails. The testNG timeout values used must be greater than the
// timeout used here to ensure the testNG timeout isn't triggered prematurely, which will cause the test to fail.
private static final int TIME_OUT_MILLIS = 30000;
//Timeout used when terminating the remote process
private static final int REMOTE_PROCESS_TERMINATION_TIMEOUT_SECONDS = 20;
// keep an optional journal of all IPC; disabled/no-op by default
private ProcessJournal processJournal = new ProcessJournal();
private OutputStream processStdinStream; // stream to which we send remote commands
/**
* @param settings Settings to be used.
*/
public StreamingProcessController(final ProcessSettings settings) {
this(settings, null);
}
/**
* Create a controller using the specified settings.
*
* @param settings Settings to be run.
* @param promptForSynchronization Prompt to be used as a synchronization point/boundary for retrieving process
* output. Blocking calls that retrieve data will block until a prompt-terminated
* block is available.
*/
public StreamingProcessController(final ProcessSettings settings, final String promptForSynchronization) {
this(settings, promptForSynchronization, false);
}
/**
* Create a controller using the specified settings.
*
* @param settings Settings to be run.
* @param promptForSynchronization Prompt to be used as a synchronization point/boundary for blocking calls that
* retrieve process output.
* @param enableJournaling Turn on process I/O journaling. This records all inter-process communication to a file.
* Journaling incurs a performance penalty, and should be used for debugging purposes only.
*/
public StreamingProcessController(
final ProcessSettings settings,
final String promptForSynchronization,
final boolean enableJournaling) {
Utils.nonNull(settings, "Process settings are required");
this.settings = settings;
this.promptForSynchronization = promptForSynchronization;
if (enableJournaling) {
processJournal.enable(settings.getCommandString());
}
}
/**
* Starts the remote process running based on the setting specified in the constructor.
*
* @return true if the process has been successfully started
*/
public boolean start() {
if (process != null) {
throw new IllegalStateException("This controller is already running a process");
}
process = launchProcess(settings);
startListeners();
processStdinStream = getProcess().getOutputStream();
return process.isAlive();
}
/**
* Write some input to the remote process, without waiting for output.
*
* @param line data to be written to the remote process
*/
public void writeProcessInput(final String line) {
try {
// Its possible that we already have completed futures from output from a previous command that
// weren't consumed before we found the prompt at the last synchronization point. If so, drop them
// before we issue a new command (since retaining them could confound synchronization on output from
// this command), and warn.
if (stdErrFuture != null && stdErrFuture.isDone()) {
processJournal.writeLogMessage("Dropping stale stderr output: " + stdErrFuture.get().getBufferString());
stdErrFuture = null;
}
if (stdOutFuture != null && stdOutFuture.isDone()) {
processJournal.writeLogMessage("Dropping stale stdout output: " + stdOutFuture.get().getBufferString());
stdOutFuture = null;
}
} catch (InterruptedException e) {
throw new GATKException(String.format("Interrupted retrieving stale future: " + line, e));
} catch (ExecutionException e) {
throw new GATKException(String.format("Execution exception retrieving stale future: " + line, e));
}
startListeners();
try {
// write to the output stream that is the process' input
processStdinStream.write(line.getBytes());
processStdinStream.flush();
processJournal.writeOutbound(line);
} catch (IOException e) {
throw new GATKException(String.format("Error writing (%s) to stdin on command", line), e);
}
}
/**
* Non-blocking call to see if output is available. It is always safe to retrieve output immediately
* after this returns true.
*
* @return true if output is currently available, and output can safely be retrieved without blocking
*/
public boolean isOutputAvailable() {
return (stdOutFuture != null && stdOutFuture.isDone()) || (stdErrFuture != null && stdErrFuture.isDone());
}
/**
* Blocking call to retrieve output from the remote process by prompt synchronization. This call collects
* data from the remote process until it receives a prompt on either the stdout or stderr stream, or
* the timeout is reached.
*
* Use isOutputAvailable to ensure the the thread will not block.
*
* @return ProcessOutput containing a prompt terminated string in either std or stderr
* @throws TimeoutException if the timeout is exceeded an no output is available
*/
public ProcessOutput getProcessOutputByPrompt() throws TimeoutException {
if (promptForSynchronization == null) {
throw new IllegalStateException("A prompt must be specified in order to use prompt-synchronized I/O");
}
return getOutputSynchronizedBy(promptForSynchronization);
}
/**
* Blocking call to retrieve output from the remote process by line. This call collects
* data from the remote process until it receives a terminated line on either the stdout or stderr stream, or
* the timeout is reached.
*
* @return ProcessOutput containing a newline terminated string in either std or stderr
* @throws TimeoutException if the timeout is exceeded an no output is available
*/
public ProcessOutput getProcessOutputByLine() throws TimeoutException {
return getOutputSynchronizedBy("\n");
}
/**
* Accumulate output from the target process until either a timeout is reached (no output for timeout duration),
* or output containing the {@code #synchronizationString} is detected.
*
* @param synchronizationString string to synchronize on
* @return ProcessOutput containing a {@code synchronizationString} terminated string in either std or stderr
* @throws TimeoutException
*/
private ProcessOutput getOutputSynchronizedBy(final String synchronizationString) throws TimeoutException {
boolean gotPrompt = false;
try (final ByteArrayOutputStream stdOutAccumulator = new ByteArrayOutputStream(CapturedStreamOutput.STREAM_BLOCK_TRANSFER_SIZE);
final ByteArrayOutputStream stdErrAccumulator = new ByteArrayOutputStream(CapturedStreamOutput.STREAM_BLOCK_TRANSFER_SIZE))
{
while (!gotPrompt) {
final ProcessOutput processOutput = getProcessOutput();
gotPrompt = scanForSynchronizationPoint(processOutput, synchronizationString);
final StreamOutput stdOut = processOutput.getStdout();
if (stdOut != null) {
stdOutAccumulator.write(stdOut.getBufferBytes());
}
final StreamOutput stderr = processOutput.getStderr();
if (stderr != null) {
stdErrAccumulator.write(stderr.getBufferBytes());
}
}
final byte[] stdOutOutput = stdOutAccumulator.toByteArray();
final byte[] stdErrOutput = stdErrAccumulator.toByteArray();
return new ProcessOutput(0,
stdOutOutput.length != 0 ?
new ByteArrayBackedStreamOutput(stdOutOutput) :
null,
stdErrOutput.length != 0 ?
new ByteArrayBackedStreamOutput(stdErrOutput) :
null);
} catch (final IOException e) {
throw new GATKException("Failure writing to process accumulator stream", e);
}
}
/**
* Attempt to retrieve any output from a (possibly) completed future that is immediately available without
* blocking or waiting for the future to complete.
* @param streamOutputFuture Future from which to retrieve output
* @return {@link StreamOutput} if the future is complete, or null otherwise
*/
private StreamOutput getOutputOptimistic(final Future<CapturedStreamOutputSnapshot> streamOutputFuture) {
StreamOutput ret = null;
if (streamOutputFuture != null) {
try {
if (streamOutputFuture.isDone()) {
ret = streamOutputFuture.get();
}
} catch (InterruptedException e) {
throw new GATKException("InterruptedException attempting to retrieve output from remote process", e);
} catch (ExecutionException e) {
throw new GATKException("ExecutionException attempting to retrieve output from remote process", e);
}
}
return ret;
}
/**
* Wait for *any* output from the process (to stdout or stderr), by draining the stream(s) until no more
* output is available. Uses a timeout to prevent the calling thread from hanging. Use isOutputAvailable
* for non-blocking check.
*/
private ProcessOutput getProcessOutput() throws TimeoutException {
StreamOutput stdout = null;
StreamOutput stderr = null;
boolean gotStdErrTimeout = false;
// We need to ensure that we get output from either stdout, or stderr, or both when available, but we don't
// want to block waiting for output that may never materialize on a second stream if we have already have
// output in hand from the other one. So, we optimistically return whatever we can get within the timeout
// period. Failure to do so would kill performance by ensuring that this ALWAYS blocks until timeout whenever
// output is only written to one stream but not the other, which is a common case. So optimistically return
// as soon as we get anything from either stream within the timeout, and let the caller decide whether to
// make another call to this method to get more output in order to reach a synchronization point.
// TODO: Its possible this could be done using an ExecutorCompletionService:
// ExecutorService can wait on multiple futures, but it either returns a single completed Future (invokeAny)
// for the first stream that completes (cancelling the others and thus dropping that output), or waits for
// all to complete (invokeAll), which always blocks and times out if there is only output on one stream.
// First, if either stream is immediately available, return whatever we have without blocking.
stderr = getOutputOptimistic(stdErrFuture);
if (stderr != null) {
stdErrFuture = null;
}
stdout = getOutputOptimistic(stdOutFuture);
if (stdout != null) {
stdOutFuture = null;
}
if (stderr == null && stdout == null) {
try {
if (stdErrFuture != null) {
// neither stderr nor stdout is done, so start our timeout on stderr, then fall through for stdout
stderr = stdErrFuture.get(TIME_OUT_MILLIS, TimeUnit.MILLISECONDS);
stdErrFuture = null;
}
} catch (TimeoutException e) {
gotStdErrTimeout = true;
if (!stdOutFuture.isDone()) { // we exceeded the stderr timeout and there is no stdout
throw e;
}
} catch (InterruptedException e) {
throw new GATKException("InterruptedException out", e);
} catch (ExecutionException e) {
throw new GATKException("ExecutionException out", e);
}
// look for stdout
try {
if (gotStdErrTimeout) {
// we already exceeded our timeout on stderr, so we don't want to timeout again. If we can get stdout
// immediately, take it, otherwise throw.
stdout = getOutputOptimistic(stdOutFuture);
if (stdout != null) {
stdOutFuture = null;
} else { // stderr timed out, and no stdout to read
throw new TimeoutException("No stdout or stderr was available. The timeout period was exceeded.");
}
} else {
// We didn't timeout on stderr, try to get stdout. If its not immediately ready, use a timeout
// and wait for it.
if (stdOutFuture != null) {
if (stderr == null) {
// no stderr timeout; no stderr, and stdout isn't done, so use our timeout on stdout
stdout = stdOutFuture.get(TIME_OUT_MILLIS, TimeUnit.MILLISECONDS);
} else {
// stderr didn't timeout, stdout isn't ready, but we already have stderr output, so fall
// through and just return that it
}
} else {
throw new TimeoutException("No stdout or stderr was available. The timeout period was exceeded.");
}
}
} catch (TimeoutException e) {
// we didn't get any stderr, but thats ok since we got stdout
} catch (InterruptedException e) {
throw new GATKException("InterruptedException retrieving stderr", e);
} catch (ExecutionException e) {
throw new GATKException("ExecutionException retrieving stderr", e);
}
}
//log the output, and restart the listeners for next time
processJournal.writeInbound(stdout, stderr);
startListeners();
return new ProcessOutput(0, stdout, stderr);
}
/**
* Create a temporary FIFO suitable for sending output to the remote process. The FIFO is only valid for the
* lifetime of the controller; the FIFO is destroyed when the controller is destroyed.
*
* @return a FIFO File
*/
public File createFIFO() {
if (fifoTempDir != null || fifoFile != null) {
throw new IllegalArgumentException("Only one FIFO per controller is supported");
}
fifoTempDir = Files.createTempDir();
final String fifoTempFileName = String.format("%s/%s", fifoTempDir.getAbsolutePath(), "gatkStreamingController.fifo");
// create the FIFO by executing mkfifo via another ProcessController
final ProcessSettings mkFIFOSettings = new ProcessSettings(new String[]{"mkfifo", fifoTempFileName});
mkFIFOSettings.getStdoutSettings().setBufferSize(-1);
mkFIFOSettings.setRedirectErrorStream(true);
final ProcessController mkFIFOController = new ProcessController();
final ProcessOutput result = mkFIFOController.exec(mkFIFOSettings);
final int exitValue = result.getExitValue();
fifoFile = new File(fifoTempFileName);
if (exitValue != 0) {
throw new GATKException(String.format(
"Failure creating FIFO named (%s). Got exit code (%d) stderr (%s) and stdout (%s)",
fifoTempFileName,
exitValue,
result.getStderr() == null ? "" : result.getStderr().getBufferString(),
result.getStdout() == null ? "" : result.getStdout().getBufferString()));
} else if (!fifoFile.exists()) {
throw new GATKException(String.format("FIFO (%s) created but doesn't exist", fifoTempFileName));
} else if (!fifoFile.canWrite()) {
throw new GATKException(String.format("FIFO (%s) created isn't writable", fifoTempFileName));
}
return fifoFile;
}
/**
* Return a {@link AsynchronousStreamWriterService} to be used to write to a stream on a background thread.
* @param outputStream stream to which items should be written.
* @param itemSerializer
* @param <T> Type of items to be written to the stream.
* @return {@link AsynchronousStreamWriterService}
*/
public <T> AsynchronousStreamWriterService<T> getAsynchronousStreamWriterService(
final OutputStream outputStream,
final Function<T, ByteArrayOutputStream> itemSerializer) {
Utils.nonNull(outputStream);
Utils.nonNull(itemSerializer);
return new AsynchronousStreamWriterService<>(executorService, outputStream, itemSerializer);
}
/**
* Close the FIFO; called on controller termination
*/
private void closeFIFO() {
if (fifoFile != null) {
fifoFile.delete();
fifoTempDir.delete();
}
}
/**
* Return true if either stdout or stderr ends with a synchronization string
*/
private boolean scanForSynchronizationPoint(final ProcessOutput processOutput, final String synchronizationString) {
final StreamOutput stdOut = processOutput.getStdout();
if (stdOut != null) {
final String output = stdOut.getBufferString();
if (output != null && output.endsWith(synchronizationString)){
return true;
}
}
final StreamOutput stdErr = processOutput.getStderr();
if (stdErr != null) {
final String output = stdErr.getBufferString();
if (output != null && output.endsWith(synchronizationString)) {
return true;
}
}
return false;
}
/**
* Submit a task to start listening for output
*/
private void startListeners() {
// Submit runnable task to start capturing.
if (stdOutFuture == null) {
stdOutFuture = executorService.submit(
new OutputCapture(
new CapturedStreamOutputSnapshot(settings.getStdoutSettings(), process.getInputStream(), System.out),
ProcessStream.STDOUT,
this.getClass().getSimpleName(),
controllerId));
}
if (!settings.isRedirectErrorStream() && stdErrFuture == null) {
// don't waste a callable on stderr if its just going to be redirected to stdout
stdErrFuture = executorService.submit(
new OutputCapture(
new CapturedStreamOutputSnapshot(settings.getStderrSettings(), process.getErrorStream(), System.err),
ProcessStream.STDERR,
this.getClass().getSimpleName(),
controllerId));
}
}
/**
* Stops the process from running and tries to ensure the process is cleaned up properly.
* NOTE: sub-processes started by process may be zombied with their parents set to pid 1.
* NOTE: capture threads may block on read.
*/
@Override
protected void tryCleanShutdown() {
if (stdErrFuture != null && !stdErrFuture.isDone()) {
boolean isCancelled = stdErrFuture.cancel(true);
if (!isCancelled) {
logger.error("Failure cancelling stderr task");
}
}
if (stdOutFuture != null && !stdOutFuture.isDone()) {
boolean isCancelled = stdOutFuture.cancel(true);
if (!isCancelled) {
logger.error("Failure cancelling stdout task");
}
}
if (process != null) {
// terminate the app by closing the process' INPUT stream
IOUtils.closeQuietly(process.getOutputStream());
}
}
/**
* Close the input stream, close the FIFO, and wait for the remote process to terminate
* destroying it if necessary.
*/
public void terminate() {
closeFIFO();
tryCleanShutdown();
boolean exited = false;
try {
exited = process.waitFor(REMOTE_PROCESS_TERMINATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
processJournal.close();
if (!exited) {
// we timed out waiting for the process to exit; it may be in a blocking call, so just force
// it to shutdown
process.destroy();
process.waitFor(REMOTE_PROCESS_TERMINATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
logger.error(String.format("Interrupt exception waiting for process (%s) to terminate", settings.getCommandString()));
}
if (process.isAlive()) {
throw new GATKException("Failure terminating remote process");
}
}
// Stream output class used to aggregate output pulled fom the process stream while waiting for
// a synchronization point.
private class ByteArrayBackedStreamOutput extends StreamOutput {
final byte[] aggregateOutput;
public ByteArrayBackedStreamOutput(final byte[] aggregateOutput) {
this.aggregateOutput = aggregateOutput;
}
@Override
public byte[] getBufferBytes() {
return aggregateOutput;
}
@Override
public boolean isBufferTruncated() {
return false;
}
};
/**
* Keep a journal of all inter-process communication. Can incur significant runtime overhead, and should
* be used for debugging only.
*/
private class ProcessJournal {
private File journalingFile = null;
private FileWriter journalingFileWriter;
public void enable(final String commandString) {
final String journalingFileName = String.format("gatkStreamingProcessJournal-%d.txt", new Random().nextInt());
journalingFile = new File(journalingFileName);
try {
journalingFileWriter = new FileWriter(journalingFile);
journalingFileWriter.write("Initial process command line: ");
journalingFileWriter.write(settings.getCommandString() + "\n\n");
} catch (IOException e) {
throw new GATKException(String.format("Error creating streaming process journaling file %s for command \"%s\"",
commandString,
journalingFile.getAbsolutePath()), e);
}
logger.info(String.format("Enabling streaming process journaling file %s", journalingFileName));
}
/**
* Record outbound data being written to a remote process.
* @param line line being written
*/
public void writeOutbound(final String line) {
try {
if (journalingFileWriter != null) {
journalingFileWriter.write("Sending: [");
journalingFileWriter.write(line);
journalingFileWriter.write("]\n\n");
journalingFileWriter.flush();
}
} catch (IOException e) {
throw new GATKException("Error writing to output to process journal", e);
}
}
/**
* Record inbound data being received from a remote process.
* @param stdout Data receieved from stdout.
* @param stderr Data receieved from stderr.
*/
public void writeInbound(final StreamOutput stdout, final StreamOutput stderr) {
if (journalingFileWriter != null) {
try {
if (stdout != null) {
journalingFileWriter.write("Received from stdout: [");
journalingFileWriter.write(stdout.getBufferString());
journalingFileWriter.write("]\n");
}
if (stderr != null) {
journalingFileWriter.write("Received from stderr: [");
journalingFileWriter.write(stderr.getBufferString());
journalingFileWriter.write("]\n");
}
journalingFileWriter.write("\n");
journalingFileWriter.flush();
} catch (IOException e) {
throw new GATKException(String.format("Error writing to journaling file %s", journalingFile.getAbsolutePath()), e);
}
}
}
/**
* Write an advisory log message to the journal.
* @param message Message to be written to the journal.
*/
public void writeLogMessage(final String message) {
if (journalingFileWriter != null) {
try {
journalingFileWriter.write(message);
journalingFileWriter.flush();
} catch (IOException e) {
throw new GATKException(String.format("Error writing to journaling file %s", journalingFile.getAbsolutePath()), e);
}
}
}
/**
* Close the journal file writer.
*/
public void close() {
try {
if (journalingFileWriter != null) {
writeLogMessage("Shutting down journal normally");
journalingFileWriter.flush();
journalingFileWriter.close();
}
} catch (IOException e) {
throw new GATKException(String.format("Error closing streaming process journaling file %s", journalingFile.getAbsolutePath()), e);
}
}
}
}
|
package org.jbehave.scenario.finegrained.junit.monitoring;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.embedder.Embedder;
import org.jbehave.core.embedder.StoryRunner;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.model.Story;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
public class JUnitReportingRunner extends Runner {
private List<Description> storyDescriptions;
private Embedder configuredEmbedder;
private List<String> storyPaths;
private JUnitStories junitStories;
private Configuration configuration;
private int numberOfTestCases;
private Description rootDescription;
@SuppressWarnings("unchecked")
public JUnitReportingRunner(Class<? extends JUnitStories> testClass) throws Throwable {
junitStories = testClass.newInstance();
configuredEmbedder = junitStories.configuredEmbedder();
configuration = configuredEmbedder.configuration();
Method method;
try {
method = testClass.getDeclaredMethod("storyPaths", (Class[]) null);
} catch (NoSuchMethodException e) {
method = testClass.getMethod("storyPaths", (Class[]) null);
}
method.setAccessible(true);
storyPaths = ((List<String>) method.invoke(junitStories, (Object[]) null));
storyDescriptions = buildDescriptionFromStories();
}
@Override
public Description getDescription() {
rootDescription = Description.createSuiteDescription(junitStories.getClass());
rootDescription.getChildren().addAll(storyDescriptions);
return rootDescription;
}
@Override
public int testCount() {
return numberOfTestCases;
}
@Override
public void run(RunNotifier notifier) {
JUnitScenarioReporter reporter = new JUnitScenarioReporter(notifier, numberOfTestCases, rootDescription);
StoryReporterBuilder reporterBuilder = new StoryReporterBuilder().withReporters(reporter);
Configuration junitReportingConfiguration = junitStories.configuration().useStoryReporterBuilder(reporterBuilder);
configuredEmbedder.useConfiguration(junitReportingConfiguration);
try {
configuredEmbedder.runStoriesAsPaths(storyPaths);
} catch (Throwable e) {
throw new RuntimeException(e);
} finally {
configuredEmbedder.generateCrossReference();
}
}
private List<Description> buildDescriptionFromStories() {
JUnitDescriptionGenerator gen = new JUnitDescriptionGenerator(junitStories.stepsFactory().createCandidateSteps());
StoryRunner storyRunner = new StoryRunner();
List<Description> storyDescriptions = new ArrayList<Description>();
storyDescriptions.add(Description.createTestDescription(Object.class, "BeforeStories"));
numberOfTestCases++;
for (String storyPath : storyPaths) {
Story parseStory = storyRunner.storyOfPath(configuration, storyPath);
Description descr = gen.createDescriptionFrom(parseStory);
storyDescriptions.add(descr);
}
storyDescriptions.add(Description.createTestDescription(Object.class, "AfterStories"));
numberOfTestCases++;
numberOfTestCases += gen.getTestCases();
return storyDescriptions;
}
}
|
package org.mtransit.parser.ca_sorel_varennes_citsv_bus;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.mt.data.MTrip;
public class SorelVarennesCITSVBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-sorel-varennes-citsv-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new SorelVarennesCITSVBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating CITSV bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating CITSV bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
if (!Utils.isDigitsOnly(gRoute.getRouteId())) {
return Long.parseLong(gRoute.getRouteShortName());
}
return super.getRouteId(gRoute);
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.SAINT.matcher(routeLongName).replaceAll(CleanUtils.SAINT_REPLACEMENT);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR = "77A22E";
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
private static final Pattern DIRECTION = Pattern.compile("(direction )", Pattern.CASE_INSENSITIVE);
private static final String DIRECTION_REPLACEMENT = "";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = DIRECTION.matcher(tripHeadsign).replaceAll(DIRECTION_REPLACEMENT);
tripHeadsign = CleanUtils.cleanStreetTypesFRCA(tripHeadsign);
return CleanUtils.cleanLabelFR(tripHeadsign);
}
private static final Pattern START_WITH_FACE_A = Pattern.compile("^(face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE_AU = Pattern.compile("^(face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE = Pattern.compile("^(face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_FACE_A = Pattern.compile("( face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE_AU = Pattern.compile("( face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE = Pattern.compile("( face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern[] START_WITH_FACES = new Pattern[] { START_WITH_FACE_A, START_WITH_FACE_AU, START_WITH_FACE };
private static final Pattern[] SPACE_FACES = new Pattern[] { SPACE_FACE_A, SPACE_WITH_FACE_AU, SPACE_WITH_FACE };
@Override
public String cleanStopName(String gStopName) {
gStopName = Utils.replaceAll(gStopName, START_WITH_FACES, CleanUtils.SPACE);
gStopName = Utils.replaceAll(gStopName, SPACE_FACES, CleanUtils.SPACE);
gStopName = CleanUtils.cleanStreetTypesFRCA(gStopName);
return CleanUtils.cleanLabelFR(gStopName);
}
private static final String ZERO = "0";
@Override
public String getStopCode(GStop gStop) {
if (ZERO.equals(gStop.getStopCode())) {
return null;
}
return super.getStopCode(gStop);
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
@Override
public int getStopId(GStop gStop) {
String stopCode = getStopCode(gStop);
if (stopCode != null && stopCode.length() > 0) {
return Integer.valueOf(stopCode); // using stop code as stop ID
}
// generating integer stop ID
Matcher matcher = DIGITS.matcher(gStop.getStopId());
matcher.find();
int digits = Integer.parseInt(matcher.group());
int stopId;
if (gStop.getStopId().startsWith("BOU")) {
stopId = 100000;
} else if (gStop.getStopId().startsWith("LON")) {
stopId = 200000;
} else if (gStop.getStopId().startsWith("VAR")) {
stopId = 300000;
} else if (gStop.getStopId().startsWith("SAM")) {
stopId = 400000;
} else {
System.out.println("Stop doesn't have an ID (start with)! " + gStop);
System.exit(-1);
stopId = -1;
}
if (gStop.getStopId().endsWith("A")) {
stopId += 1000;
} else if (gStop.getStopId().endsWith("B")) {
stopId += 2000;
} else if (gStop.getStopId().endsWith("C")) {
stopId += 3000;
} else if (gStop.getStopId().endsWith("D")) {
stopId += 4000;
} else {
System.out.println("Stop doesn't have an ID (end with)! " + gStop);
System.exit(-1);
}
return stopId + digits;
}
}
|
package com.damick.dropwizard.metrics.cloudwatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsync;
import com.amazonaws.services.cloudwatch.model.MetricDatum;
import com.amazonaws.services.cloudwatch.model.PutMetricDataRequest;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.jackson.DiscoverableSubtypeResolver;
import io.dropwizard.jackson.Jackson;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.spi.valuehandling.ValidatedValueUnwrapper;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.validation.Validation;
import javax.validation.Validator;
import java.io.File;
import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CloudWatchReporterFactoryTest {
@Test
public void isDiscoverable() throws Exception {
assertThat(new DiscoverableSubtypeResolver().getDiscoveredSubtypes())
.contains(CloudWatchReporterFactory.class);
}
@Test
public void verifyConfigurable() throws Exception {
ObjectMapper mapper = Jackson.newObjectMapper();
// dropwizard 0.9.1 changed the validation wiring a bit..
Class<ValidatedValueUnwrapper> optValidatorClazz = (Class<ValidatedValueUnwrapper>) Class
.forName("io.dropwizard.validation.valuehandling.OptionalValidatedValueUnwrapper");
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
if (optValidatorClazz != null) {
validator = Validation.byProvider(HibernateValidator.class).configure()
.addValidatedValueHandler(optValidatorClazz.newInstance())
.buildValidatorFactory().getValidator();
}
ConfigurationFactory<CloudWatchReporterFactory> configFactory =
new ConfigurationFactory<>(CloudWatchReporterFactory.class,
validator, mapper, "dw");
CloudWatchReporterFactory f = configFactory.build(new File(Resources.getResource("cw.yml").getFile()));
assertEquals("[env=default]", f.getGlobalDimensions().toString());
assertEquals("us-east-1", f.getAwsRegion());
assertEquals("a.b", f.getNamespace());
assertEquals("XXXXX", f.getAwsSecretKey());
assertEquals("11111", f.getAwsAccessKeyId());
assertEquals("p.neustar.biz", f.getAwsClientConfiguration().getProxyHost());
assertNull(f.getAwsClientConfiguration().getProxyUsername());
}
@Test
public void verifyDefaults() throws Exception {
CloudWatchReporterFactory factory = new CloudWatchReporterFactory();
assertFalse(factory.region().getName().isEmpty());
assertFalse(factory.machineId().isEmpty());
factory.setAwsRegion("ap-southeast-2");
factory.setMachineDimension("10.0.0.1");
assertEquals("ap-southeast-2", factory.region().getName());
assertEquals("10.0.0.1", factory.machineId());
}
@Test
public void verifySendingToCloudWatch() throws Exception {
CloudWatchReporterFactory factory = new CloudWatchReporterFactory();
MetricRegistry registry = new MetricRegistry();
Counter counter = registry.counter(MetricRegistry.name(this.getClass(), "test machine=123*"));
AmazonCloudWatchAsync mockClient = mock(AmazonCloudWatchAsync.class);
final Future<Void> mockFuture = mock(Future.class);
when(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class))).thenReturn(mockFuture);
when(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class))).thenAnswer(new Answer<Future>() {
@Override
public Future answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
if (args.length > 0 && args[0] != null) {
PutMetricDataRequest req = (PutMetricDataRequest) args[0];
assertEquals(req.getNamespace(), "myspace");
for (MetricDatum datum : req.getMetricData()) {
System.out.println(datum.toString());
assertTrue(datum.toString().contains("env"));
}
}
return mockFuture;
}
});
factory.setClient(mockClient);
factory.setAwsAccessKeyId("fakeKey");
factory.setAwsSecretKey("fakeSecret");
factory.setNamespace("myspace");
factory.setGlobalDimensions(Lists.newArrayList("env=dev"));
ScheduledReporter reporter = factory.build(registry);
for (int i = 0; i < 200; i++) {
counter.inc();
}
reporter.report();
verify(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class)), times(1));
}
@Test
public void verifyDefaultProviderChainIsUsed() throws Exception {
System.setProperty("aws.accessKeyId", "fake");
System.setProperty("aws.secretKey", "fake");
try {
CloudWatchReporterFactory factory = new CloudWatchReporterFactory();
MetricRegistry registry = new MetricRegistry();
Counter counter = registry.counter(MetricRegistry.name(this.getClass(), "test machine=123*"));
counter.inc();
factory.build(registry).report();
// expecting a 403
} finally {
System.clearProperty("aws.accessKeyId");
System.clearProperty("aws.secretKey");
}
}
}
|
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.ValueOut;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
import static org.junit.Assert.assertEquals;
public class RollCycleMultiThreadStressTest {
private static final Logger LOG = LoggerFactory.getLogger(RollCycleMultiThreadStressTest.class);
private static final long SLEEP_PER_WRITE_NANOS = 50_000;
private static final int RUN_TIME_MILLIS = 120_400;
@Ignore("long running")
@Test
public void stress() throws Exception {
final File path = DirectoryUtils.tempDir("rollCycleStress");
LOG.warn("using path {}", path);
final int numWriters = 1;
final int numThreads = Runtime.getRuntime().availableProcessors() * 2;
final ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
final AtomicInteger wrote = new AtomicInteger();
final int[] read = new int[numThreads - numWriters];
final AtomicBoolean[] finished = new AtomicBoolean[numThreads];
final String[] errors = new String[numThreads];
final long endTime = System.currentTimeMillis() + RUN_TIME_MILLIS;
for (int threadId = 0; threadId < numThreads; threadId++) {
final int finalThreadId = threadId;
finished[finalThreadId] = new AtomicBoolean();
executorService.submit(() -> {
// create a queue per thread
try (final ChronicleQueue queue = SingleChronicleQueueBuilder.binary(path)
.testBlockSize()
.rollCycle(RollCycles.TEST_SECONDLY)
.build()) {
if (finalThreadId < numWriters) {
final ExcerptAppender appender = queue.acquireAppender();
while (System.currentTimeMillis() < endTime) {
try (DocumentContext writingDocument = appender.writingDocument()) {
ValueOut valueOut = writingDocument.wire().getValueOut();
valueOut.int32(wrote.getAndIncrement());
LockSupport.parkNanos(SLEEP_PER_WRITE_NANOS);
}
}
} else {
final ExcerptTailer tailer = queue.createTailer();
while (System.currentTimeMillis() < endTime + 500) {
try (DocumentContext rd = tailer.readingDocument()) {
if (rd.isPresent()) {
int v = rd.wire().getValueIn().int32();
assertEquals(read[finalThreadId - numWriters], v);
read[finalThreadId - numWriters]++;
}
//LockSupport.parkNanos(SLEEP_PER_WRITE_NANOS / 2);
}
}
}
} catch (Throwable t) {
LOG.error("Error " + t.getMessage());
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
errors[finalThreadId] = Thread.currentThread().getName() + ": " + sw.toString();
}
finished[finalThreadId].set(true);
});
}
executorService.shutdown();
boolean ok = executorService.awaitTermination(RUN_TIME_MILLIS + 1000, TimeUnit.MILLISECONDS);
if (!ok) {
LOG.error("shutdown now");
executorService.shutdownNow();
}
Thread.sleep(100);
System.out.println("read: "+ Arrays.toString(read));
if (Arrays.stream(read).anyMatch(readValue -> readValue < wrote.get()))
Assert.fail("Not all readers read all values " + wrote.get() + " vs " + Arrays.toString(read));
if (Arrays.stream(finished).anyMatch(atomicBoolean -> ! atomicBoolean.get()))
Assert.fail("Thread did not finish " + Arrays.toString(finished));
Arrays.stream(errors).filter(Objects::nonNull).forEach(System.out::println);
assertEquals(0, Arrays.stream(errors).filter(Objects::nonNull).count());
}
}
|
package org.ambraproject.rhino.rest.controller;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.ambraproject.rhino.AbstractRhinoTest;
import org.ambraproject.rhino.config.RuntimeConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@ContextConfiguration(classes = ConfigurationReadControllerTest.class)
@Configuration
@WebAppConfiguration
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class ConfigurationReadControllerTest extends AbstractRhinoTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockModelViewController;
private RuntimeConfiguration mockRuntimeConfiguration;
/**
* Initialize test data fixtures.
*
* @throws MalformedURLException if improper URL
*/
@BeforeMethod(alwaysRun = true)
public void init() {
mockRuntimeConfiguration = applicationContext.getBean(RuntimeConfiguration.class);
mockModelViewController = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* Test failed request to read API Configurations.
*
* @throws Exception if API request fails
*/
@Test
public void testReadUserApiConfigShouldFail() throws Exception {
mockModelViewController.perform(get("/config/userApi/")).andExpect(status().isNotFound());
mockModelViewController.perform(get("/config/userApi")).andExpect(status().isNotFound());
verify(mockRuntimeConfiguration, times(0)).getNedConfiguration();
}
}
|
package org.motechproject.nms.testing.it.imi;
import org.apache.commons.codec.binary.Hex;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.nms.imi.service.SettingsService;
import org.motechproject.nms.imi.service.TargetFileService;
import org.motechproject.nms.imi.service.contract.TargetFileNotification;
import org.motechproject.nms.kilkari.domain.CallRetry;
import org.motechproject.nms.kilkari.domain.CallStage;
import org.motechproject.nms.kilkari.domain.DeactivationReason;
import org.motechproject.nms.kilkari.domain.Subscriber;
import org.motechproject.nms.kilkari.domain.Subscription;
import org.motechproject.nms.kilkari.domain.SubscriptionOrigin;
import org.motechproject.nms.kilkari.domain.SubscriptionPack;
import org.motechproject.nms.kilkari.repository.CallRetryDataService;
import org.motechproject.nms.kilkari.repository.SubscriberDataService;
import org.motechproject.nms.kilkari.repository.SubscriptionDataService;
import org.motechproject.nms.kilkari.repository.SubscriptionPackDataService;
import org.motechproject.nms.kilkari.service.SubscriberService;
import org.motechproject.nms.kilkari.service.SubscriptionService;
import org.motechproject.nms.props.domain.DayOfTheWeek;
import org.motechproject.nms.region.domain.Circle;
import org.motechproject.nms.region.domain.Language;
import org.motechproject.nms.region.repository.CircleDataService;
import org.motechproject.nms.region.repository.DistrictDataService;
import org.motechproject.nms.region.repository.LanguageDataService;
import org.motechproject.nms.region.repository.StateDataService;
import org.motechproject.nms.testing.it.utils.RegionHelper;
import org.motechproject.nms.testing.it.utils.SubscriptionHelper;
import org.motechproject.nms.testing.service.TestingService;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;
import javax.inject.Inject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class TargetFileServiceBundleIT extends BasePaxIT {
private static final String LOCAL_OBD_DIR = "imi.local_obd_dir";
private static final String REMOTE_OBD_DIR = "imi.remote_obd_dir";
private String localObdDirBackup;
private String remoteObdDirBackup;
@Inject
TargetFileService targetFileService;
@Inject
SubscriptionService subscriptionService;
@Inject
SubscriptionDataService subscriptionDataService;
@Inject
SubscriberDataService subscriberDataService;
@Inject
SubscriptionPackDataService subscriptionPackDataService;
@Inject
CallRetryDataService callRetryDataService;
@Inject
LanguageDataService languageDataService;
@Inject
private CircleDataService circleDataService;
@Inject
private StateDataService stateDataService;
@Inject
private DistrictDataService districtDataService;
@Inject
private SubscriberService subscriberService;
@Inject
SettingsService settingsService;
@Inject
TestingService testingService;
Circle dehliCircle;
Circle karnatakaCircle;
Language hindi;
Language kannada;
SubscriptionPack childPack;
SubscriptionPack pregnancyPack;
private String setupTestDir(String property, String dir) {
String backup = settingsService.getSettingsFacade().getProperty(property);
File directory = new File(System.getProperty("user.home"), dir);
directory.mkdirs();
settingsService.getSettingsFacade().setProperty(property, directory.getAbsolutePath());
return backup;
}
@Before
public void before() {
testingService.clearDatabase();
localObdDirBackup = setupTestDir(LOCAL_OBD_DIR, "obd-local-dir-it");
remoteObdDirBackup = setupTestDir(REMOTE_OBD_DIR, "obd-remote-dir-it");
RegionHelper rh = new RegionHelper(languageDataService, circleDataService, stateDataService,
districtDataService);
SubscriptionHelper sh = new SubscriptionHelper(subscriptionService,
subscriberDataService, subscriptionPackDataService, languageDataService, circleDataService,
stateDataService, districtDataService);
childPack = sh.childPack();
pregnancyPack = sh.pregnancyPack();
dehliCircle = rh.delhiCircle();
karnatakaCircle = rh.karnatakaCircle();
hindi = rh.hindiLanguage();
kannada = rh.kannadaLanguage();
}
@After
public void restoreSettings() {
settingsService.getSettingsFacade().setProperty(REMOTE_OBD_DIR, remoteObdDirBackup);
settingsService.getSettingsFacade().setProperty(LOCAL_OBD_DIR, localObdDirBackup);
}
@Test
public void testTargetFileGeneration() throws NoSuchAlgorithmException, IOException {
Subscriber subscriber1 = new Subscriber(1111111111L, hindi, dehliCircle);
subscriber1.setLastMenstrualPeriod(DateTime.now().minusDays(90)); // startDate will be today
subscriberDataService.create(subscriber1);
subscriptionService.createSubscription(1111111111L, hindi, pregnancyPack, SubscriptionOrigin.MCTS_IMPORT);
// Should not be picked up because it's been deactivated
Subscriber subscriber2 = new Subscriber(2222222222L, kannada, karnatakaCircle);
subscriber2.setLastMenstrualPeriod(DateTime.now().minusDays(90)); // startDate will be today
subscriberDataService.create(subscriber2);
Subscription subscription2 = subscriptionService.createSubscription(2222222222L, kannada, pregnancyPack,
SubscriptionOrigin.MCTS_IMPORT);
subscriptionService.deactivateSubscription(subscription2, DeactivationReason.CHILD_DEATH);
//Should not be picked up because it's not for today
Subscriber subscriber3 = new Subscriber(6666666666L, kannada, karnatakaCircle);
subscriber3.setDateOfBirth(DateTime.now().plusDays(1)); // startDate is DOB + 1 for child packs,
// so setting the DOB tomorrow this should be picked up
// the day after tomorrow
subscriberDataService.create(subscriber3);
subscriptionService.createSubscription(6666666666L, kannada, childPack, SubscriptionOrigin.IVR);
// Should not be picked up because it's not for today
callRetryDataService.create(new CallRetry("11111111-1111-1111-1111-111111111111", 3333333333L,
DayOfTheWeek.today().nextDay(), CallStage.RETRY_1, "w1_m1.wav", "w1_1", hindi.getCode(),
dehliCircle.getName(), SubscriptionOrigin.IVR));
TargetFileNotification tfn = targetFileService.generateTargetFile();
assertNotNull(tfn);
// Should not pickup subscription2 because its status is not ACTIVE
// Should not pickup subscription3 because it's for tomorrow
// Should not pickup call retry record because it's for tomorrow also
assertEquals(1, (int) tfn.getRecordCount());
//read the file to get checksum & record count
File targetDir = new File(settingsService.getSettingsFacade().getProperty("imi.local_obd_dir"));
File targetFile = new File(targetDir, tfn.getFileName());
MessageDigest md = MessageDigest.getInstance("MD5");
int recordCount = 0;
try (InputStream is = Files.newInputStream(targetFile.toPath());
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
DigestInputStream dis = new DigestInputStream(is, md);
while ((reader.readLine()) != null) {
recordCount++;
}
}
String md5Checksum = new String(Hex.encodeHex(md.digest()));
assertEquals((int)tfn.getRecordCount(), recordCount);
assertEquals(tfn.getChecksum(), md5Checksum);
}
@Test
public void testServicePresent() {
assertTrue(targetFileService != null);
}
// un-ignore to create a large sample OBD file
@Ignore
public void createLargeFile() {
SubscriptionHelper sh = new SubscriptionHelper(subscriptionService, subscriberDataService,
subscriptionPackDataService, languageDataService, circleDataService, stateDataService,
districtDataService);
for (int i=0 ; i<1000 ; i++) {
sh.mksub(SubscriptionOrigin.MCTS_IMPORT, DateTime.now());
}
for (int i=0 ; i<1000 ; i++) {
int randomWeek = (int) (Math.random() * sh.childPack().getWeeks());
Subscription sub = sh.mksub(
SubscriptionOrigin.MCTS_IMPORT,
DateTime.now().minusDays(7 * randomWeek - 1)
);
callRetryDataService.create(new CallRetry(
sub.getSubscriptionId(),
sub.getSubscriber().getCallingNumber(),
DayOfTheWeek.today(),
CallStage.RETRY_1,
sh.getContentMessageFile(sub, randomWeek),
sh.getWeekId(sub, randomWeek),
sh.getLanguageCode(sub),
sh.getCircle(sub),
SubscriptionOrigin.MCTS_IMPORT
));
}
TargetFileNotification tfn = targetFileService.generateTargetFile();
assertNotNull(tfn);
getLogger().debug("Generated {}", tfn.getFileName());
}
// To check that target file should contain correct weekID according to LMP of the subscriber.
@Test
public void verifyFT151() throws NoSuchAlgorithmException, IOException {
Subscriber subscriber1 = new Subscriber(1111111111L, hindi, dehliCircle);
subscriber1.setLastMenstrualPeriod(DateTime.now().minusDays(125)); // weekId will be W6_1
subscriberDataService.create(subscriber1);
Subscription subscription = subscriptionService.createSubscription(1111111111L, hindi, pregnancyPack, SubscriptionOrigin.MCTS_IMPORT);
subscription.setNeedsWelcomeMessage(false);
subscriptionDataService.update(subscription);
List<String> contents = new ArrayList<>();
String line;
TargetFileNotification tfn = targetFileService.generateTargetFile();
File targetDir = new File(settingsService.getSettingsFacade().getProperty("imi.local_obd_dir"));
File targetFile = new File(targetDir, tfn.getFileName());
MessageDigest md = MessageDigest.getInstance("MD5");
int recordCount = 0;
try (InputStream is = Files.newInputStream(targetFile.toPath());
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
DigestInputStream dis = new DigestInputStream(is, md);
while ((line = reader.readLine()) != null) {
recordCount++;
contents.add(line.split(",")[7]); //column 8 is for weekId
}
}
String md5Checksum = new String(Hex.encodeHex(md.digest()));
assertEquals((int)tfn.getRecordCount(), recordCount);
assertEquals(tfn.getChecksum(), md5Checksum);
assertTrue("w6_1".equals(contents.get(0)));
assertEquals(1, recordCount);
}
// To check that target file should contain correct weekID according to DOB of the subscriber.
@Test
public void verifyFT152() throws NoSuchAlgorithmException, IOException {
Subscriber subscriber1 = new Subscriber(1111111111L, hindi, dehliCircle);
subscriber1.setDateOfBirth(DateTime.now().minusDays(28)); // weekId will be W5_1
subscriberDataService.create(subscriber1);
Subscription subscription = subscriptionService.createSubscription(1111111111L, hindi, childPack, SubscriptionOrigin.MCTS_IMPORT);
subscription.setNeedsWelcomeMessage(false);
subscriptionDataService.update(subscription);
List<String> contents = new ArrayList<>();
String line;
TargetFileNotification tfn = targetFileService.generateTargetFile();
File targetDir = new File(settingsService.getSettingsFacade().getProperty("imi.local_obd_dir"));
File targetFile = new File(targetDir, tfn.getFileName());
MessageDigest md = MessageDigest.getInstance("MD5");
int recordCount = 0;
try (InputStream is = Files.newInputStream(targetFile.toPath());
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
DigestInputStream dis = new DigestInputStream(is, md);
while ((line = reader.readLine()) != null) {
recordCount++;
contents.add(line.split(",")[7]); //column 8 is for weekId
}
}
String md5Checksum = new String(Hex.encodeHex(md.digest()));
assertEquals((int)tfn.getRecordCount(), recordCount);
assertEquals(tfn.getChecksum(), md5Checksum);
assertTrue("w5_1".equals(contents.get(0)));
//update the date of birth of the subscriber
Subscriber subscriber2 = subscriberDataService.findByCallingNumber(1111111111L);
subscriber2.setDateOfBirth(DateTime.now().minusDays(21)); // weekId will be W4_1
subscriberService.update(subscriber2);
// again generate the target file to check correct weekId is picked after DOB is changed.
tfn = targetFileService.generateTargetFile();
contents.clear();
targetFile = new File(targetDir, tfn.getFileName());
recordCount = 0;
try (InputStream is = Files.newInputStream(targetFile.toPath());
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
DigestInputStream dis = new DigestInputStream(is, md);
while ((line = reader.readLine()) != null) {
recordCount++;
contents.add(line.split(",")[7]); //column 8 is for weekId
}
}
md5Checksum = new String(Hex.encodeHex(md.digest()));
assertEquals((int)tfn.getRecordCount(), recordCount);
assertEquals(tfn.getChecksum(), md5Checksum);
assertTrue("w4_1".equals(contents.get(0)));
assertEquals(1, recordCount);
}
//todo: test success notification is sent to the IVR system
}
|
package io.spine.server.integration;
import io.spine.server.integration.given.IntProjectRepository;
import io.spine.server.integration.given.RepositoryThrowingExceptionOnClose;
import io.spine.server.integration.given.IntReportRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.spine.server.integration.AcknowledgementsVerifier.acked;
import static io.spine.server.integration.EmittedEventsVerifier.emitted;
import static io.spine.server.integration.given.BlackBoxBoundedContextTestEnv.addTask;
import static io.spine.server.integration.given.BlackBoxBoundedContextTestEnv.createProject;
import static io.spine.server.integration.given.BlackBoxBoundedContextTestEnv.createReport;
import static io.spine.server.integration.given.BlackBoxBoundedContextTestEnv.newProjectId;
import static io.spine.server.integration.given.BlackBoxBoundedContextTestEnv.taskAdded;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Mykhailo Drachuk
*/
@DisplayName("Black Box Bounded Context should")
class BlackBoxBoundedContextTest {
private BlackBoxBoundedContext project;
@BeforeEach
void setUp() {
project = BlackBoxBoundedContext.with(new IntProjectRepository());
}
@AfterEach
void tearDown() {
project.close();
}
@SuppressWarnings("ReturnValueIgnored")
@Test
@DisplayName("receive and handle a single commands")
void receivesACommand() {
project.receivesCommand(createProject())
.verifiesThat(acked(1).withoutErrorsOrRejections())
.verifiesThat(emitted(1, IntProjectCreated.class));
}
@SuppressWarnings("ReturnValueIgnored")
@Test
@DisplayName("receive and handle multiple commands")
void receivesCommands() {
ProjectId projectId = newProjectId();
project.receivesCommand(createProject(projectId))
.receivesCommands(addTask(projectId), addTask(projectId), addTask(projectId))
.verifiesThat(acked(4).withoutErrorsOrRejections())
.verifiesThat(emitted(4))
.verifiesThat(emitted(1, IntProjectCreated.class))
.verifiesThat(emitted(3, IntTaskAdded.class));
}
@SuppressWarnings("ReturnValueIgnored")
@Test
@DisplayName("receive and react on single event")
void receivesEvent() {
ProjectId projectId = newProjectId();
project.andWith(new IntReportRepository())
.receivesCommand(createReport(projectId))
.receivesEvent(taskAdded(projectId))
.verifiesThat(acked(2).withoutErrorsOrRejections())
.verifiesThat(emitted(3))
.verifiesThat(emitted(1, IntReportCreated.class))
.verifiesThat(emitted(1, IntTaskAddedToReport.class));
}
@SuppressWarnings("ReturnValueIgnored")
@Test
@DisplayName("receive and react on multiple events")
void receivesEvents() {
ProjectId projectId = newProjectId();
project.andWith(new IntReportRepository())
.receivesCommand(createReport(projectId))
.receivesEvents(taskAdded(projectId), taskAdded(projectId), taskAdded(projectId))
.verifiesThat(acked(4).withoutErrorsOrRejections())
.verifiesThat(emitted(7))
.verifiesThat(emitted(1, IntReportCreated.class))
.verifiesThat(emitted(3, IntTaskAddedToReport.class));
}
@Test
@DisplayName("throw Illegal State Exception on Bounded Context close error")
void throwIllegalStateExceptionOnClose() {
assertThrows(IllegalStateException.class, () ->
BlackBoxBoundedContext
.with(new RepositoryThrowingExceptionOnClose() {
@Override
protected void throwException() {
throw new RuntimeException("Expected error");
}
})
.close());
}
}
|
package to.etc.domui.component2.controlfactory;
import to.etc.domui.component.input.DateInput;
import to.etc.domui.component.input.DateInput2;
import to.etc.domui.component.meta.PropertyMetaModel;
import to.etc.domui.dom.html.IControl;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Date;
public class ControlCreatorDate implements IControlCreator {
/**
* Accept java.util.Date class <i>only</i>.
*/
@Override
public <T> int accepts(PropertyMetaModel<T> pmm, Class< ? extends IControl<T>> controlClass) {
if(controlClass != null && !controlClass.isAssignableFrom(DateInput.class))
return -1;
Class< ? > iclz = pmm.getActualType();
if(Date.class.isAssignableFrom(iclz)) {
return 2;
}
return 0;
}
@Override
public <T, C extends IControl<T>> C createControl(@Nonnull PropertyMetaModel<T> pmm, @Nullable Class<C> controlClass) {
return (C) DateInput2.createDateInput((PropertyMetaModel<Date>) pmm, true);
}
}
|
package io.spine.tools.gradle.compiler;
import com.google.common.annotations.VisibleForTesting;
import io.spine.tools.gradle.SpinePlugin;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.DependencySet;
import org.gradle.api.artifacts.ResolvedConfiguration;
import org.gradle.api.initialization.dsl.ScriptHandler;
import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency;
import org.gradle.api.invocation.Gradle;
import org.gradle.api.plugins.PluginContainer;
import org.gradle.api.tasks.TaskCollection;
import org.gradle.api.tasks.TaskContainer;
import org.gradle.api.tasks.compile.CompileOptions;
import org.gradle.api.tasks.compile.JavaCompile;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static io.spine.tools.gradle.ConfigurationName.CLASSPATH;
import static io.spine.tools.gradle.compiler.SpineCheckerExtension.getUseValidatingBuilder;
public class SpineCheckerPlugin extends SpinePlugin {
private static final String ERROR_PRONE_PLUGIN_ID = "net.ltgt.errorprone";
private static final String EXTENSION_NAME = "spineChecker";
@VisibleForTesting
static final String PREPROCESSOR_CONFIG_NAME = "annotationProcessor";
@VisibleForTesting
static final String SPINE_TOOLS_GROUP = "io.spine.tools";
@VisibleForTesting
static final String SPINE_CHECKER_MODULE = "spine-checker";
@VisibleForTesting
static final String MODEL_COMPILER_PLUGIN_NAME = "spine-model-compiler";
static String extensionName() {
return EXTENSION_NAME;
}
@Override
public void apply(Project project) {
project.getExtensions()
.create(extensionName(), SpineCheckerExtension.class);
Configuration preprocessorConfig = setupPreprocessorConfig(project);
boolean addedSuccessfully = addSpineCheckerDependency(preprocessorConfig, project);
if (addedSuccessfully) {
addConfigureSeverityAction(project);
}
}
private Configuration setupPreprocessorConfig(Project project) {
ConfigurationContainer configurations = project.getConfigurations();
Configuration preprocessorConfig = configurations.findByName(PREPROCESSOR_CONFIG_NAME);
if (preprocessorConfig == null) {
preprocessorConfig = configurations.create(PREPROCESSOR_CONFIG_NAME);
addConfigurePreprocessorAction(preprocessorConfig, project);
}
return preprocessorConfig;
}
private boolean addSpineCheckerDependency(Configuration configuration, Project project) {
Optional<String> versionToUse = acquireModelCompilerVersion(project);
if (!versionToUse.isPresent()) {
log().debug("Can't acquire model compiler version for the project {}", project.getName());
return false;
}
String version = versionToUse.get();
boolean isResolvable = isSpineCheckerVersionResolvable(version, configuration);
if (isResolvable) {
dependOnSpineChecker(version, configuration);
}
return isResolvable;
}
private void addConfigureSeverityAction(Project project) {
Action<Gradle> configureCheckSeverity = configureSeverityAction(project);
Gradle gradle = project.getGradle();
gradle.projectsEvaluated(configureCheckSeverity);
}
private void addConfigurePreprocessorAction(Configuration preprocessorConfig, Project project) {
Action<Gradle> configurePreprocessor =
configurePreprocessorAction(preprocessorConfig, project);
Gradle gradle = project.getGradle();
gradle.projectsEvaluated(configurePreprocessor);
}
private Optional<String> acquireModelCompilerVersion(Project project) {
log().debug("Acquiring 'spine-model-compiler' dependency version for the project {}",
project.getName());
ScriptHandler buildscript = project.getRootProject()
.getBuildscript();
ConfigurationContainer configurations = buildscript.getConfigurations();
Configuration classpath = configurations.findByName(CLASSPATH.getValue());
if (classpath == null) {
return Optional.empty();
}
DependencySet classpathDependencies = classpath.getDependencies();
Optional<String> version = Optional.empty();
for (Dependency dependency : classpathDependencies) {
if (MODEL_COMPILER_PLUGIN_NAME.equals(dependency.getName())) {
String dependencyVersion = dependency.getVersion();
version = Optional.ofNullable(dependencyVersion);
}
}
return version;
}
@VisibleForTesting
protected boolean isSpineCheckerVersionResolvable(String version, Configuration configuration) {
Configuration configCopy = configuration.copy();
dependOnSpineChecker(version, configCopy);
ResolvedConfiguration resolved = configCopy.getResolvedConfiguration();
boolean isResolvable = !resolved.hasError();
return isResolvable;
}
private void dependOnSpineChecker(String dependencyVersion, Configuration configuration) {
log().debug("Adding dependency on {}:{}:{} to the {} configuration",
SPINE_TOOLS_GROUP, SPINE_CHECKER_MODULE, dependencyVersion,
PREPROCESSOR_CONFIG_NAME);
DependencySet dependencies = configuration.getDependencies();
Dependency dependency = new DefaultExternalModuleDependency(
SPINE_TOOLS_GROUP, SPINE_CHECKER_MODULE, dependencyVersion);
dependencies.add(dependency);
}
private Action<Gradle>
configurePreprocessorAction(Configuration preprocessorConfig, Project project) {
return gradle -> configurePreprocessor(preprocessorConfig, project);
}
@SuppressWarnings("TypeMayBeWeakened") // More specific type expresses the method intent better.
private void configurePreprocessor(Configuration preprocessorConfig, Project project) {
log().debug("Adding the {} configuration to all 'JavaCompile' tasks.",
PREPROCESSOR_CONFIG_NAME);
addArgsToJavaCompile(project, "-processorpath", preprocessorConfig.getAsPath());
}
private Action<Gradle> configureSeverityAction(Project project) {
return gradle -> configureCheckSeverity(project);
}
private void configureCheckSeverity(Project project) {
if (!hasErrorPronePlugin(project)) {
log().debug("Cannot configure Spine checks severity as Error Prone plugin is not " +
"applied to the project {}.", project.getName());
return;
}
Severity defaultSeverity = Extension.getSpineCheckerSeverity(project);
setUseValidatingBuilderSeverity(project, defaultSeverity);
}
@SuppressWarnings("ConstantConditions") // Checking nullable argument for null.
private void
setUseValidatingBuilderSeverity(Project project, @Nullable Severity defaultSeverity) {
Severity severity = getUseValidatingBuilder(project);
if (severity == null) {
if (defaultSeverity == null) {
return;
} else {
severity = defaultSeverity;
}
}
log().debug("Setting UseValidatingBuilder checker severity to {} for the project {}",
severity.name(), project.getName());
String severityArg = "-Xep:UseValidatingBuilder:" + severity.name();
addArgsToJavaCompile(project, severityArg);
}
private static void addArgsToJavaCompile(Project project, String... args) {
TaskContainer tasks = project.getTasks();
TaskCollection<JavaCompile> javaCompileTasks = tasks.withType(JavaCompile.class);
for (JavaCompile task : javaCompileTasks) {
CompileOptions taskOptions = task.getOptions();
List<String> compilerArgs = taskOptions.getCompilerArgs();
compilerArgs.addAll(Arrays.asList(args));
}
}
@VisibleForTesting
protected boolean hasErrorPronePlugin(Project project) {
PluginContainer appliedPlugins = project.getPlugins();
boolean hasPlugin = appliedPlugins.hasPlugin(ERROR_PRONE_PLUGIN_ID);
return hasPlugin;
}
}
|
package org.cipres.treebase.domain.nexus.nexml;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.cipres.treebase.Constants;
import org.cipres.treebase.TreebaseUtil;
import org.cipres.treebase.domain.matrix.CharSet;
import org.cipres.treebase.domain.matrix.CharacterMatrix;
import org.cipres.treebase.domain.matrix.ColumnRange;
import org.cipres.treebase.domain.matrix.ContinuousMatrix;
import org.cipres.treebase.domain.matrix.ContinuousMatrixElement;
import org.cipres.treebase.domain.matrix.DiscreteCharState;
import org.cipres.treebase.domain.matrix.DiscreteMatrix;
import org.cipres.treebase.domain.matrix.DiscreteMatrixElement;
import org.cipres.treebase.domain.matrix.Matrix;
import org.cipres.treebase.domain.matrix.MatrixColumn;
import org.cipres.treebase.domain.matrix.MatrixDataType;
import org.cipres.treebase.domain.matrix.MatrixElement;
import org.cipres.treebase.domain.matrix.MatrixRow;
import org.cipres.treebase.domain.matrix.PhyloChar;
import org.cipres.treebase.domain.matrix.RowSegment;
import org.cipres.treebase.domain.matrix.StandardMatrix;
import org.cipres.treebase.domain.matrix.StateSet;
import org.cipres.treebase.domain.study.Study;
import org.cipres.treebase.domain.taxon.SpecimenLabel;
import org.cipres.treebase.domain.taxon.TaxonLabelHome;
import org.nexml.model.Annotatable;
import org.nexml.model.Annotation;
import org.nexml.model.CategoricalMatrix;
import org.nexml.model.CharacterState;
import org.nexml.model.CharacterStateSet;
import org.nexml.model.Document;
import org.nexml.model.MatrixCell;
import org.nexml.model.MolecularMatrix;
import org.nexml.model.OTUs;
import org.nexml.model.OTU;
import org.nexml.model.Subset;
import org.nexml.model.UncertainCharacterState;
public class NexmlMatrixWriter extends NexmlObjectConverter {
private static final int MAX_GRANULAR_NCHAR = 0;
private static final int MAX_GRANULAR_NTAX = 0;
/**
*
* @param study
* @param taxonLabelHome
*/
public NexmlMatrixWriter(Study study,TaxonLabelHome taxonLabelHome,Document document) {
super(study,taxonLabelHome,document);
}
/**
* This is the method that is called by the NexmlDocumentWriter when turning
* a study or data set into a NeXML document
* @param tbMatrix
* @param xmlOTUs
* @return
* XXX doesn't handle the following data types:
* public static final String MATRIX_DATATYPE_NUCLEOTIDE = "Nucleotide";
* public static final String MATRIX_DATATYPE_DISTANCE = "Distance";
* public static final String MATRIX_DATATYPE_MIXED = "Mixed";
*/
public org.nexml.model.Matrix<?> fromTreeBaseToXml(CharacterMatrix tbMatrix,OTUs xmlOTUs) {
// here we decide what subtype of character matrix to instantiate
org.nexml.model.Matrix<?> xmlMatrix = createMatrix(tbMatrix, xmlOTUs);
// here we create column/character sets
createCharacterSets(tbMatrix, xmlMatrix);
return xmlMatrix;
}
/**
*
* @param tbMatrix
* @param xmlOTUs
* @return
*/
private org.nexml.model.Matrix<?> createMatrix(CharacterMatrix tbMatrix, OTUs xmlOTUs) {
// here we decide what (super-)type to instantiate: discrete or continuous
if ( tbMatrix instanceof DiscreteMatrix ) {
org.nexml.model.Matrix<CharacterState> xmlDiscreteMatrix = null;
// 'standard' data is treated separately because we don't have an alphabet for it
if ( tbMatrix.getDataType().getDescription().equals(MatrixDataType.MATRIX_DATATYPE_STANDARD) ) {
// standard categorical
xmlDiscreteMatrix = createStandardNexmlMatrix((StandardMatrix) tbMatrix,xmlOTUs);
}
else {
// molecular
xmlDiscreteMatrix = createMolecularNexmlMatrix((DiscreteMatrix) tbMatrix,xmlOTUs);
}
populateDiscreteNexmlMatrix(xmlDiscreteMatrix,(DiscreteMatrix)tbMatrix);
return xmlDiscreteMatrix;
}
else if ( tbMatrix instanceof ContinuousMatrix ) {
// continuous
org.nexml.model.ContinuousMatrix xmlContinuousMatrix = createContinuousNexmlMatrix((ContinuousMatrix) tbMatrix,xmlOTUs);
populateContinuousNexmlMatrix(xmlContinuousMatrix,(ContinuousMatrix)tbMatrix);
return xmlContinuousMatrix;
}
return null;
}
/**
* Creates and populates characters (i.e. columns) with their annotations,
* and state sets, with their annotations. For standard data (including
* those matrices that are actually mostly molecular) we flatten the
* (fictional, but modeled) stateset mapping of all state symbols, plus
* missing ('?') and gap ('-').
*
* @param tbMatrix
* @return an xml matrix with empty rows
*/
private CategoricalMatrix createStandardNexmlMatrix(StandardMatrix tbMatrix,OTUs xmlOTUs) {
if ( null == xmlOTUs ) {
xmlOTUs = getOTUsById(tbMatrix.getTaxa().getId());
}
CategoricalMatrix xmlMatrix = getDocument().createCategoricalMatrix(xmlOTUs);
copyMatrixAttributes(tbMatrix,xmlMatrix);
// first flatten the two-dimensional list into a map, we will always only create a single state set
List<List<DiscreteCharState>> tbStateLabels = tbMatrix.getStateLabels();
Map<Character,DiscreteCharState> stateForSymbol = new HashMap<Character,DiscreteCharState>();
CharacterStateSet xmlStateSet = xmlMatrix.createCharacterStateSet();
for ( int i = 0; i < tbStateLabels.size(); i++ ) {
for ( int j = 0; j < tbStateLabels.get(i).size(); j++ ) {
Character symbol = tbStateLabels.get(i).get(j).getSymbol();
DiscreteCharState state = tbStateLabels.get(i).get(j);
stateForSymbol.put(symbol, state);
}
}
// then create the single state set out of the map, assigning all non-missing characters to missing
Set<CharacterState> xmlMissingStates = new HashSet<CharacterState>();
for ( Character symbol : stateForSymbol.keySet() ) {
char sym = symbol.charValue();
if ( sym != '-' && sym != '?' ) {
String symString = symbol.toString();
CharacterState xmlState = xmlStateSet.createCharacterState(symString);
xmlMissingStates.add(xmlState);
DiscreteCharState tbState = stateForSymbol.get(symbol);
xmlState.setLabel(symString);
attachTreeBaseID((Annotatable)xmlState,tbState,DiscreteCharState.class);
}
}
// the missing symbol ("?") includes all others, including gap ("-")
UncertainCharacterState gap = xmlStateSet.createUncertainCharacterState("-", new HashSet<CharacterState>());
gap.setLabel("-");
xmlMissingStates.add(gap);
UncertainCharacterState missing = xmlStateSet.createUncertainCharacterState("?", xmlMissingStates);
missing.setLabel("?");
// then create the XML characters, assigning them all the same state set
List<MatrixColumn> tbColumns = tbMatrix.getColumnsReadOnly();
for ( int i = 0; i < tbColumns.size(); i++ ) {
MatrixColumn tbColumn = tbColumns.get(i);
org.nexml.model.Character xmlCharacter = xmlMatrix.createCharacter(xmlStateSet);
copyCharacterAttributes(tbColumn, xmlCharacter);
}
return xmlMatrix;
}
/**
* Creates and populates characters (i.e. columns) with their annotations,
* and state sets, with their annotations
*
* @param tbMatrix
* @return an xml matrix with empty rows
*/
private MolecularMatrix createMolecularNexmlMatrix(DiscreteMatrix tbMatrix,OTUs xmlOTUs) {
if ( null == xmlOTUs ) {
xmlOTUs = getOTUsById(tbMatrix.getTaxa().getId());
}
String tbDataType = tbMatrix.getDataType().getDescription();
MolecularMatrix xmlMatrix = null;
CharacterStateSet xmlStateSet = null;
// create the matrix and constant (IUPAC) state set
if ( tbDataType.equals(MatrixDataType.MATRIX_DATATYPE_DNA) ) {
xmlMatrix = getDocument().createMolecularMatrix(xmlOTUs, MolecularMatrix.DNA);
xmlStateSet = ((MolecularMatrix)xmlMatrix).getDNACharacterStateSet();
}
else if ( tbDataType.equals(MatrixDataType.MATRIX_DATATYPE_RNA) ) {
xmlMatrix = getDocument().createMolecularMatrix(xmlOTUs, MolecularMatrix.RNA);
xmlStateSet = ((MolecularMatrix)xmlMatrix).getRNACharacterStateSet();
}
else if ( tbDataType.equals(MatrixDataType.MATRIX_DATATYPE_PROTEIN) ) {
xmlMatrix = getDocument().createMolecularMatrix(xmlOTUs, MolecularMatrix.Protein);
xmlStateSet = ((MolecularMatrix)xmlMatrix).getProteinCharacterStateSet();
}
copyMatrixAttributes(tbMatrix,xmlMatrix);
// lookup the equivalent state in tb and attach identifiers
for(StateSet tbStateSet : tbMatrix.getStateSets() ) {
for (DiscreteCharState tbState : tbStateSet.getStates() ) {
String tbSymbol = tbState.getSymbol().toString().toUpperCase();
CharacterState xmlState = xmlStateSet.lookupCharacterStateBySymbol(tbSymbol);
if ( null == xmlState ) {
xmlState = xmlStateSet.createCharacterState(tbSymbol);
}
attachTreeBaseID((Annotatable)xmlState,tbState,DiscreteCharState.class);
}
}
// create columns and attach identifiers
for ( MatrixColumn tbColumn : tbMatrix.getColumnsReadOnly() ) {
org.nexml.model.Character xmlCharacter = xmlMatrix.createCharacter(xmlStateSet);
copyCharacterAttributes(tbColumn, xmlCharacter);
}
return xmlMatrix;
}
/**
* Creates and populates characters (i.e. columns) with their annotations,
* and state sets, with their annotations
*
* @param tbMatrix
* @return an xml matrix with empty rows
*/
private org.nexml.model.ContinuousMatrix createContinuousNexmlMatrix(ContinuousMatrix tbMatrix,OTUs xmlOTUs) {
if ( null == xmlOTUs ) {
xmlOTUs = getOTUsById(tbMatrix.getTaxa().getId());
}
org.nexml.model.ContinuousMatrix xmlMatrix = getDocument().createContinuousMatrix(xmlOTUs);
copyMatrixAttributes(tbMatrix,xmlMatrix);
for ( MatrixColumn tbColumn : tbMatrix.getColumnsReadOnly() ) {
org.nexml.model.Character xmlCharacter = xmlMatrix.createCharacter();
copyCharacterAttributes(tbColumn, xmlCharacter);
//coerce the tbMatrix into a character matrix to get its character sets
CharacterMatrix tbCharacterMatrix = (CharacterMatrix)tbMatrix;
Set<CharSet> tbCharSets = tbCharacterMatrix.getCharSets();
for ( CharSet tbCharSet : tbCharSets ) {
Collection<ColumnRange> tbColumnRanges = tbCharSet.getColumns(tbCharacterMatrix);
for ( ColumnRange tbColumnRange : tbColumnRanges ) {
// these are the beginning and end of the range
int tbStart = tbColumnRange.getStartColIndex();
int tbStop = tbColumnRange.getEndColIndex();
// increment from beginning to end. This number is probably either null, for a
// contiguous range, or perhaps 3 for codon positions
int tbInc = 1;
// create the equivalent nexml character set
Subset nexSubset = xmlMatrix.createSubset(tbCharSet.getLabel());
// assign character objects to the subset. Here we get the full list
List<org.nexml.model.Character> nexCharacters = xmlMatrix.getCharacters();
// now we iterate over the coordinates and assign the nexml characters to the set
for ( int i = tbStart; i <= tbStop; i += tbInc ) {
nexSubset.addThing(nexCharacters.get(i));
}
}
}
}
return xmlMatrix;
}
/**
*
* @param tbMatrix
* @param xmlMatrix
*/
private void createCharacterSets(CharacterMatrix tbMatrix, org.nexml.model.Matrix<?> xmlMatrix) {
// here we copy the character sets for all matrix types
Set<CharSet> tbCharSets = tbMatrix.getCharSets();
for ( CharSet tbCharSet : tbCharSets ) {
Collection<ColumnRange> tbColumnRanges = tbCharSet.getColumns(tbMatrix);
for ( ColumnRange tbColumnRange : tbColumnRanges ) {
// these are the beginning and end of the range
int tbStart = tbColumnRange.getStartColIndex();
int tbStop = tbColumnRange.getEndColIndex();
// increment from beginning to end. This number is probably either null, for a
// contiguous range, or perhaps 3 for codon positions
int tbInc = 1;
// need to do this to prevent nullpointerexceptions
Integer tbRepeatInterval = tbColumnRange.getRepeatInterval();
if ( null != tbRepeatInterval ) {
tbInc = tbRepeatInterval;
}
// create the equivalent nexml character set
Subset xmlSubset = xmlMatrix.createSubset(tbCharSet.getLabel());
// assign character objects to the subset. Here we get the full list
List<org.nexml.model.Character> xmlCharacters = xmlMatrix.getCharacters();
// now we iterate over the coordinates and assign the nexml characters to the set
for ( int i = tbStart; i <= tbStop; i += tbInc ) {
xmlSubset.addThing(xmlCharacters.get(i));
}
}
}
}
/**
*
* @param xmlMatrix
* @param tbMatrix
* @param xmlOTUs
* @param stateSet
*/
private void populateDiscreteNexmlMatrix(org.nexml.model.Matrix<CharacterState> xmlMatrix, DiscreteMatrix tbMatrix) {
OTUs xmlOTUs = xmlMatrix.getOTUs();
List<org.nexml.model.Character> xmlCharacters = xmlMatrix.getCharacters();
// iterates over all matrix rows, i.e. ntax times
for ( MatrixRow tbRow : tbMatrix.getRowsReadOnly() ) {
Set<RowSegment> tbSegments = tbRow.getSegmentsReadOnly();
OTU xmlOTU = getOTUById(xmlOTUs, tbRow.getTaxonLabel().getId());
if ( xmlCharacters.size() <= MAX_GRANULAR_NCHAR && xmlOTUs.getAllOTUs().size() <= MAX_GRANULAR_NTAX ) {
populateDiscreteVerboseNexmlMatrix(xmlMatrix,tbMatrix,xmlCharacters,tbRow,tbSegments,xmlOTU);
}
else {
String seq = tbRow.getNormalizedSymbolString();
// In NeXML, 'standard' data needs to be space-separated
if ( tbMatrix.getDataType().getDescription().equals(MatrixDataType.MATRIX_DATATYPE_STANDARD) ) {
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < seq.length(); i++ ) {
sb.append(seq.charAt(i));
if ( i < seq.length() - 1 ) {
sb.append(' ');
}
}
}
xmlMatrix.setSeq(seq,xmlOTU);
// this often only happens once, when the row has only 1 segment
for ( RowSegment tbSegment : tbSegments ) {
org.nexml.model.MatrixRow<CharacterState> xmlRow = xmlMatrix.getRowObject(xmlOTU);
Annotation xmlSegment = xmlRow.addAnnotationValue("tb:rowSegment", Constants.TBTermsURI, new String());
xmlSegment.addAnnotationValue("tb:startIndex", Constants.TBTermsURI, tbSegment.getStartIndex());
xmlSegment.addAnnotationValue("tb:endIndex", Constants.TBTermsURI, tbSegment.getEndIndex());
copyDarwinCoreAnnotations(tbSegment, xmlSegment);
}
}
}
}
/**
* XXX this never executes, we always make compact matrices - RAV 5/2/2012
* @param xmlMatrix
* @param tbMatrix
* @param xmlCharacterList
* @param tbRow
* @param tbSegments
* @param xmlOTU
*/
private void populateDiscreteVerboseNexmlMatrix(
org.nexml.model.Matrix<CharacterState> xmlMatrix,
DiscreteMatrix tbMatrix,
List<org.nexml.model.Character> xmlCharacterList,MatrixRow tbRow,
Set<RowSegment> tbSegments, OTU xmlOTU) {
// iterates over all characters, i.e. nchar times
int charIndex = 0;
String seq = tbRow.getSymbolString();
for ( MatrixColumn tbColumn : ((CharacterMatrix)tbMatrix).getColumns() ) {
org.nexml.model.Character xmlCharacter = xmlCharacterList.get(charIndex);
MatrixCell<CharacterState> xmlCell = xmlMatrix.getCell(xmlOTU, xmlCharacter);
String value = "" + seq.charAt(charIndex);
CharacterState xmlState = xmlMatrix.parseSymbol(value);
xmlCell.setValue(xmlState);
attachTreeBaseID ((Annotatable) xmlCell, tbColumn , DiscreteMatrixElement.class);
for ( RowSegment tbSegment : tbSegments ) {
if ( tbSegment.getStartIndex() <= charIndex && charIndex <= tbSegment.getEndIndex() ) {
copyDarwinCoreAnnotations(tbSegment, (Annotatable)xmlCell);
}
}
charIndex++;
}
}
/**
*
* @param xmlMatrix
* @param tbMatrix
*/
private void populateContinuousNexmlMatrix(org.nexml.model.ContinuousMatrix xmlMatrix,
ContinuousMatrix tbMatrix) {
List<org.nexml.model.Character> characterList = xmlMatrix.getCharacters();
OTUs xmlOTUs = xmlMatrix.getOTUs();
for ( MatrixRow tbRow : tbMatrix.getRowsReadOnly() ) {
List<MatrixElement> elements = tbRow.getElements();
OTU xmlOTU = getOTUById(xmlOTUs, tbRow.getTaxonLabel().getId());
if ( characterList.size() <= MAX_GRANULAR_NCHAR && xmlOTUs.getAllOTUs().size() <= MAX_GRANULAR_NTAX ) {
for ( int elementIndex = 0; elementIndex < tbMatrix.getnChar(); elementIndex++ ) {
ContinuousMatrixElement tbCell = (ContinuousMatrixElement)elements.get(elementIndex);
MatrixCell<Double> xmlCell = xmlMatrix.getCell(xmlOTU, characterList.get(elementIndex));
xmlCell.setValue(tbCell.getValue());
attachTreeBaseID((Annotatable)xmlCell,tbCell,DiscreteMatrixElement.class);
}
}
else {
String seq = tbRow.buildElementAsString();
xmlMatrix.setSeq(seq,xmlOTU);
}
Set<RowSegment> tbSegments = tbRow.getSegmentsReadOnly();
for ( RowSegment tbSegment : tbSegments ) {
org.nexml.model.MatrixRow<Double> xmlRow = xmlMatrix.getRowObject(xmlOTU);
Annotation xmlSegment = xmlRow.addAnnotationValue("tb:rowSegment", Constants.TBTermsURI, new String());
xmlSegment.addAnnotationValue("tb:startIndex", Constants.TBTermsURI, tbSegment.getStartIndex());
xmlSegment.addAnnotationValue("tb:endIndex", Constants.TBTermsURI, tbSegment.getEndIndex());
copyDarwinCoreAnnotations(tbSegment,xmlSegment);
}
}
}
/**
*
* @param tbSegment
* @param xmlAnnotatable
*/
private void copyDarwinCoreAnnotations(RowSegment tbSegment, Annotatable xmlAnnotatable) {
SpecimenLabel tbSpec = tbSegment.getSpecimenLabel();
Map<String,String> predicateToObjectMap = new HashMap<String,String>();
predicateToObjectMap.put("DwC:institutionCode", tbSpec.getInstAcronym());
predicateToObjectMap.put("DwC:collectionCode", tbSpec.getCollectionCode());
predicateToObjectMap.put("DwC:catalogNumber", tbSpec.getCatalogNumber());
predicateToObjectMap.put("DwC:associatedSequences", tbSpec.getGenBankAccession());
predicateToObjectMap.put("DwC:otherCatalogNumbers", tbSpec.getOtherAccession());
predicateToObjectMap.put("DwC:eventDate", tbSpec.getSampleDateString());
predicateToObjectMap.put("DwC:scientificName", tbSegment.getSpecimenTaxonLabelAsString());
predicateToObjectMap.put("DwC:recordedBy", tbSpec.getCollector());
predicateToObjectMap.put("DwC:country", tbSpec.getCountry());
predicateToObjectMap.put("DwC:locality", tbSpec.getLocality());
predicateToObjectMap.put("DwC:stateProvince", tbSpec.getState());
predicateToObjectMap.put("DwC:datasetName", tbSegment.getTitle());
predicateToObjectMap.put("DwC:occurenceRemarks", tbSpec.getNotes());
for ( String predicate : predicateToObjectMap.keySet() ) {
String objectString = predicateToObjectMap.get(predicate);
if ( ! TreebaseUtil.isEmpty(objectString) ) {
xmlAnnotatable.addAnnotationValue(predicate, Constants.DwCURI, objectString);
}
}
//output geographic latitude in decimal degrees using geodeticDatum spatial reference system
Double latitude = tbSpec.getLatitude();
if ( null != latitude ) {
xmlAnnotatable.addAnnotationValue("DwC:decimalLatitude", Constants.DwCURI, latitude);
}
//output geographic longitude in decimal degrees using geodeticDatum spatial reference system
Double longitude = tbSpec.getLongitude();
if ( null != longitude ) {
xmlAnnotatable.addAnnotationValue("DwC:decimalLongitude", Constants.DwCURI, longitude);
}
//there are two different Darwin Core terms for elevation depending on elevation value
//outputs geographic elevation of sample
Double elevation = tbSpec.getElevation();
if ( null != elevation ) {
if ( elevation >= 0) {
//above local surface in meters
xmlAnnotatable.addAnnotationValue("DwC:verbatimElevation", Constants.DwCURI, elevation);
}
else {
//below local surface in meters
xmlAnnotatable.addAnnotationValue("DwC:verbatimDepth", Constants.DwCURI, elevation);
}
}
}
/**
*
* @param tbColumn
* @param xmlCharacter
*/
private void copyCharacterAttributes(MatrixColumn tbColumn,org.nexml.model.Character xmlCharacter) {
PhyloChar tbCharacter = tbColumn.getCharacter();
if ( null != tbCharacter.getDescription() ) {
xmlCharacter.setLabel(tbCharacter.getLabel());
}
attachTreeBaseID((Annotatable)xmlCharacter,tbColumn,MatrixColumn.class);
}
/**
*
* @param tbMatrix
* @param xmlMatrix
*/
private void copyMatrixAttributes(CharacterMatrix tbMatrix,org.nexml.model.Matrix<?> xmlMatrix) {
// attach matrix identifiers
attachTreeBaseID((Annotatable)xmlMatrix, tbMatrix,Matrix.class);
String tb1MatrixID = tbMatrix.getTB1MatrixID();
if ( null != tb1MatrixID ) {
((Annotatable)xmlMatrix).addAnnotationValue("tb:identifier.matrix.tb1", Constants.TBTermsURI, tb1MatrixID);
}
xmlMatrix.addAnnotationValue("skos:historyNote", Constants.SKOSURI, "Mapped from TreeBASE schema using "+this.toString()+" $Rev$");
xmlMatrix.setBaseURI(mMatrixBaseURI);
xmlMatrix.setLabel(tbMatrix.getLabel());
}
}
|
package de.danielnaber.languagetool.tagging.pl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import de.danielnaber.languagetool.AnalyzedTokenReadings;
import de.danielnaber.languagetool.tokenizers.WordTokenizer;
import junit.framework.TestCase;
public class PolishTaggerTest extends TestCase {
private PolishTagger tagger;
private WordTokenizer tokenizer;
public void setUp() {
tagger = new PolishTagger();
tokenizer = new WordTokenizer();
}
public void testTagger() throws IOException {
myAssert("To jest duży dom.", "To/conj jest/verb:fin:sg:ter:imperf duży/adj:sg:nom.acc:m+adj:sg:nom:m dom/subst:sg:nom.acc:m3+subst:sg:nom:m");
myAssert("Krowa pasie się na pastwisku.", "Krowa/subst:sg:nom:f pasie/subst:pl:nom.voc:m1+subst:sg:loc.voc:m+subst:sg:loc.voc:m3 się/qub na/prep:loc pastwisku/subst:sg:dat:m+subst:sg:dat:n+subst:sg:loc.voc:m+subst:sg:loc:n");
myAssert("blablabla","blablabla/null");
}
private void myAssert(String input, String expected) throws IOException {
List tokens = tokenizer.tokenize(input);
List noWhitespaceTokens = new ArrayList();
// whitespace confuses tagger, so give it the tokens but no whitespace tokens:
for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
String token = (String) iterator.next();
if (isWord(token)) {
noWhitespaceTokens.add(token);
}
}
List output = tagger.tag(noWhitespaceTokens);
StringBuffer outputStr = new StringBuffer();
for (Iterator iter = output.iterator(); iter.hasNext();) {
AnalyzedTokenReadings token = (AnalyzedTokenReadings) iter.next();
//FIXME: check for multiple readings
outputStr.append(token.getAnalyzedToken(0));
if (iter.hasNext())
outputStr.append(" ");
}
assertEquals(expected, outputStr.toString());
}
private boolean isWord(String token) {
for (int i = 0; i < token.length(); i++) {
char c = token.charAt(i);
if (Character.isLetter(c) || Character.isDigit(c))
return true;
}
return false;
}
}
|
package gr.ntua.vision.monitoring.rules;
import gr.ntua.vision.monitoring.events.Event;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AggregationPerContainerRule implements AggregationRule {
private static final String TOPIC = "SLA";
private static final String DICT = "!dict";
private final String aggregationField;
private final String newField;
private final String operation;
private static final Logger log = LoggerFactory.getLogger(AggregationPerContainerRule.class);
private static final String SPECIAL_FIELD = "transaction-duration";
private static final long MIN = 60 * 1000;
public class ContainerRep {
public final String tenant;
public final String name;
public ContainerRep(String tenant, String name) {
this.tenant = tenant;
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ContainerRep other = (ContainerRep) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (tenant == null) {
if (other.tenant != null)
return false;
} else if (!tenant.equals(other.tenant))
return false;
return true;
}
private AggregationPerContainerRule getOuterType() {
return AggregationPerContainerRule.this;
}
}
/**
* @param aggregationField
* @param resultField
*/
public AggregationPerContainerRule(final String operation, String aggregationField, final String resultField) {
this.operation = operation;
this.aggregationField = aggregationField;
this.newField = resultField;
}
/**
* @param eventList
*/
private void aggregateContainerSize(final Map<ContainerRep, Long> containersSize, List<? extends Event> eventList) {
for (final Event e : eventList)
try {
final String tenant = (String) e.get("tenant");
final String name = (String) e.get("container");
final Long size = getValue(e, aggregationField);
final ContainerRep c = new ContainerRep(tenant, name);
if (size == null) {
log.trace("event with no appropriate field '{}'; skipping", aggregationField);
continue;
}
if (containersSize.containsKey(c)) {
final long oldSize = containersSize.get(c);
containersSize.put(c, oldSize + size);
} else {
containersSize.put(c, size);
}
} catch (Throwable x) {
x.printStackTrace();
log.error("continuing aggregation", x);
}
}
private static Long getValue(final Event e, final String field) {
final Object val = e.get(field);
if (val == null)
return null;
try {
return (Long) val;
} catch (ClassCastException x) {
log.trace("expecting field '{}' of type {} ...", field, Long.class);
log.trace("but got value {} of type {}", val, val.getClass());
log.trace("", x);
return Long.valueOf((String) val);
}
}
@SuppressWarnings("unchecked")
@Override
public AggregationResultEvent aggregate(final long aggregationStartTime, List<? extends Event> eventList) {
final Map<ContainerRep, Long> containersSize = new HashMap<ContainerRep, Long>();
aggregateContainerSize(containersSize, eventList);
@SuppressWarnings("rawtypes")
final Map dict = appendNewFields(eventList, aggregationStartTime, containersSize);
return new VismoAggregationResultEvent(dict);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map appendNewFields(List<? extends Event> eventList, final long aggregationStartTime,
final Map<ContainerRep, Long> containersSize) {
final Event lastEvent = eventList.get(eventList.size() - 1);
final Map dict = (Map) lastEvent.get(DICT);
final List<Object> containers = new ArrayList<Object>();
// FIXME: these should be gotten off the timer
dict.put("tStart", aggregationStartTime - MIN); // FIXME: bind this to the timer
dict.put("tEnd", aggregationStartTime);
dict.put(newField, getContainersList(containersSize));
return dict;
}
private List<Object> getContainersList(final Map<ContainerRep, Long> containersSize) {
final List<Object> containers = new ArrayList<Object>();
for (final ContainerRep c : containersSize.keySet()) {
final Map<String, Object> o = new HashMap<String, Object>();
o.put("tenant", c.tenant);
o.put("container", c.name);
o.put("size", containersSize.get(c));
o.put("topic", TOPIC);
containers.add(o);
}
return containers;
}
@Override
public boolean matches(Event e) {
final String op = (String) e.get("operation");
// FIXME: add a field for events coming from vismo_dispatch
return e.get(SPECIAL_FIELD) != null && op.equals(operation);
}
@Override
public boolean hasExpired() {
// TODO????
return true;
}
@Override
public String toString() {
return "#<" + this.getClass().getSimpleName() + "[" + operation + "] on field: " + aggregationField
+ ", with new field '" + newField + "'>";
}
}
|
package org.weasis.dicom.viewer2d;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.swing.JOptionPane;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.weasis.core.api.explorer.ObservableEvent;
import org.weasis.core.api.gui.util.ActionState;
import org.weasis.core.api.gui.util.ActionW;
import org.weasis.core.api.gui.util.ComboItemListener;
import org.weasis.core.api.gui.util.Filter;
import org.weasis.core.api.gui.util.JMVUtils;
import org.weasis.core.api.gui.util.SliderChangeListener;
import org.weasis.core.api.gui.util.SliderCineListener;
import org.weasis.core.api.gui.util.ToggleButtonListener;
import org.weasis.core.api.media.data.MediaElement;
import org.weasis.core.api.media.data.MediaSeries;
import org.weasis.core.api.media.data.SeriesEvent;
import org.weasis.core.api.media.data.TagW;
import org.weasis.core.api.util.StringUtil;
import org.weasis.core.ui.editor.image.ViewCanvas;
import org.weasis.dicom.codec.DcmMediaReader;
import org.weasis.dicom.codec.DicomImageElement;
import org.weasis.dicom.codec.DicomSeries;
import org.weasis.dicom.codec.KOSpecialElement;
import org.weasis.dicom.codec.TagD;
import org.weasis.dicom.codec.macro.HierachicalSOPInstanceReference;
import org.weasis.dicom.codec.macro.KODocumentModule;
import org.weasis.dicom.codec.utils.DicomMediaUtils;
import org.weasis.dicom.explorer.DicomModel;
import org.weasis.dicom.explorer.LoadDicomObjects;
public final class KOManager {
public static List<Object> getKOElementListWithNone(ViewCanvas<DicomImageElement> currentView) {
Collection<KOSpecialElement> koElements =
currentView != null ? DicomModel.getKoSpecialElements(currentView.getSeries()) : null;
int koElementNb = (koElements == null) ? 0 : koElements.size();
List<Object> koElementListWithNone = new ArrayList<>(koElementNb + 1);
koElementListWithNone.add(ActionState.NoneLabel.NONE);
if (koElementNb > 0) {
koElementListWithNone.addAll(koElements);
}
return koElementListWithNone;
}
/**
* Test if current sopInstanceUID is referenced in the selected KEY_OBJECT of the given currentView. If not, search
* if there is a more suitable new KEY_OBJECT element. Ask the user if needed.
*/
public static KOSpecialElement getValidKOSelection(final ViewCanvas<DicomImageElement> view2d) {
KOSpecialElement currentSelectedKO = getCurrentKOSelection(view2d);
DicomImageElement currentImage = view2d.getImage();
KOSpecialElement newKOSelection = null;
Attributes newDicomKO = null;
if (currentSelectedKO == null) {
KOSpecialElement validKOSelection = findValidKOSelection(view2d);
if (validKOSelection != null) {
String message = Messages.getString("KOManager.select_KO_msg"); //$NON-NLS-1$
Object[] options =
{ Messages.getString("KOManager.select_last_ko"), Messages.getString("KOManager.new_ko") }; //$NON-NLS-1$ //$NON-NLS-2$
int response = JOptionPane.showOptionDialog(view2d.getJComponent(), message,
Messages.getString("KOManager.ko_title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (response == 0) {
newKOSelection = validKOSelection;
} else if (response == 1) {
newDicomKO = createNewDicomKeyObject(currentImage, view2d.getJComponent());
} else if (response == JOptionPane.CLOSED_OPTION) {
return null;
}
} else {
newDicomKO = createNewDicomKeyObject(currentImage, view2d.getJComponent());
}
} else {
if (currentSelectedKO.getMediaReader().isEditableDicom()) {
String studyInstanceUID = TagD.getTagValue(currentImage, Tag.StudyInstanceUID, String.class);
if (currentSelectedKO.isEmpty()
|| currentSelectedKO.containsStudyInstanceUIDReference(studyInstanceUID)) {
newKOSelection = currentSelectedKO;
} else {
String message = Messages.getString("KOManager.no_ko_msg"); //$NON-NLS-1$
Object[] options =
{ Messages.getString("KOManager.use_ko"), Messages.getString("KOManager.new_ko") }; //$NON-NLS-1$ //$NON-NLS-2$
int response = JOptionPane.showOptionDialog(view2d.getJComponent(), message,
Messages.getString("KOManager.ko_title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (response == 0) {
newKOSelection = currentSelectedKO;
} else if (response == 1) {
newDicomKO = createNewDicomKeyObject(currentImage, view2d.getJComponent());
} else if (response == JOptionPane.CLOSED_OPTION) {
return null;
}
}
} else {
String message = Messages.getString("KOManager.ko_readonly"); //$NON-NLS-1$
Object[] options =
{ Messages.getString("KOManager.new_ko"), Messages.getString("KOManager.new_ko_from") }; //$NON-NLS-1$ //$NON-NLS-2$
int response = JOptionPane.showOptionDialog(view2d.getJComponent(), message,
Messages.getString("KOManager.ko_title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (response == 0) {
newDicomKO = createNewDicomKeyObject(currentImage, view2d.getJComponent());
} else if (response == 1) {
newDicomKO = createNewDicomKeyObject(currentSelectedKO, view2d.getJComponent());
} else if (response == JOptionPane.CLOSED_OPTION) {
return null;
}
}
}
if (newDicomKO != null) {
// Deactivate filter for new KO
ActionState koFilterAction = view2d.getEventManager().getAction(ActionW.KO_FILTER);
if (koFilterAction instanceof ToggleButtonListener) {
((ToggleButtonListener) koFilterAction).setSelected(false);
}
newKOSelection = loadDicomKeyObject(view2d.getSeries(), newDicomKO);
}
return newKOSelection;
}
public static KOSpecialElement loadDicomKeyObject(MediaSeries<DicomImageElement> dicomSeries,
Attributes newDicomKO) {
DicomModel dicomModel = (DicomModel) dicomSeries.getTagValue(TagW.ExplorerModel);
new LoadDicomObjects(dicomModel, newDicomKO).addSelectionAndnotify(); // must be executed in the EDT
for (KOSpecialElement koElement : DicomModel.getKoSpecialElements(dicomSeries)) {
if (koElement.getMediaReader().getDicomObject().equals(newDicomKO)) {
return koElement;
}
}
return null;
}
public static Attributes createNewDicomKeyObject(MediaElement dicomMediaElement, Component parentComponent) {
if (dicomMediaElement != null && dicomMediaElement.getMediaReader() instanceof DcmMediaReader) {
Attributes dicomSourceAttribute = ((DcmMediaReader) dicomMediaElement.getMediaReader()).getDicomObject();
String message = Messages.getString("KOManager.ko_desc"); //$NON-NLS-1$
String defautDescription = Messages.getString("KOManager.ko_name"); //$NON-NLS-1$
String description =
(String) JOptionPane.showInputDialog(parentComponent, message, Messages.getString("KOManager.ko_title"), //$NON-NLS-1$
JOptionPane.INFORMATION_MESSAGE, null, null, defautDescription);
// description==null means the user canceled the input
if (StringUtil.hasText(description)) {
Attributes ko = DicomMediaUtils.createDicomKeyObject(dicomSourceAttribute, description, null);
if (dicomMediaElement instanceof KOSpecialElement) {
Collection<HierachicalSOPInstanceReference> referencedStudySequence =
new KODocumentModule(dicomSourceAttribute).getCurrentRequestedProcedureEvidences();
new KODocumentModule(ko).setCurrentRequestedProcedureEvidences(referencedStudySequence);
}
return ko;
}
}
return null;
}
/**
* Get an editable Dicom KeyObject Selection suitable to handle current Dicom Image. A valid object should either
* reference the studyInstanceUID of the current Dicom Image or simply be empty ...
*/
public static KOSpecialElement findValidKOSelection(final ViewCanvas<DicomImageElement> view2d) {
MediaSeries<DicomImageElement> dicomSeries = view2d.getSeries();
DicomImageElement currentImage = view2d.getImage();
if (currentImage != null && dicomSeries != null) {
String currentStudyInstanceUID = TagD.getTagValue(currentImage, Tag.StudyInstanceUID, String.class);
Collection<KOSpecialElement> koElementsWithReferencedSeriesInstanceUID =
DicomModel.getKoSpecialElements(dicomSeries);
if (koElementsWithReferencedSeriesInstanceUID != null) {
for (KOSpecialElement koElement : koElementsWithReferencedSeriesInstanceUID) {
if (koElement.getMediaReader().isEditableDicom()) {
if (koElement.containsStudyInstanceUIDReference(currentStudyInstanceUID)) {
return koElement;
}
}
}
for (KOSpecialElement koElement : koElementsWithReferencedSeriesInstanceUID) {
if (koElement.getMediaReader().isEditableDicom()) {
if (koElement.isEmpty()) {
return koElement;
}
}
}
}
}
return null;
}
public static KOSpecialElement getCurrentKOSelection(final ViewCanvas<DicomImageElement> view2d) {
Object actionValue = view2d.getActionValue(ActionW.KO_SELECTION.cmd());
if (actionValue instanceof KOSpecialElement) {
return (KOSpecialElement) actionValue;
}
return null;
}
public static boolean setKeyObjectReference(boolean selectedState, final ViewCanvas<DicomImageElement> view2d) {
KOSpecialElement validKOSelection = getValidKOSelection(view2d);
if (validKOSelection == null) {
return false; // canceled
}
KOSpecialElement currentSelectedKO = KOManager.getCurrentKOSelection(view2d);
if (validKOSelection != currentSelectedKO) {
ActionState koSelection = view2d.getEventManager().getAction(ActionW.KO_SELECTION);
if (koSelection instanceof ComboItemListener) {
((ComboItemListener) koSelection).setSelectedItem(validKOSelection);
}
}
boolean hasKeyObjectReferenceChanged = false;
if (validKOSelection == currentSelectedKO || currentSelectedKO == null) {
// KO Toogle State is changed only if KO Selection remains the same,
// or if there was no previous KO Selection
DicomImageElement currentImage = view2d.getImage();
hasKeyObjectReferenceChanged = validKOSelection.setKeyObjectReference(selectedState, currentImage);
if (hasKeyObjectReferenceChanged) {
DicomModel dicomModel = (DicomModel) view2d.getSeries().getTagValue(TagW.ExplorerModel);
// Fire an event since any view in any View2dContainer may have its KO selected state changed
if (dicomModel != null) {
dicomModel.firePropertyChange(
new ObservableEvent(ObservableEvent.BasicAction.UPDATE, view2d, null, validKOSelection));
}
boolean filter = JMVUtils.getNULLtoFalse(view2d.getActionValue(ActionW.KO_FILTER.cmd()));
if (filter && (view2d.getEventManager().getSelectedViewPane() == view2d)) {
// When unchecking an image, force to call the filter action to resize the views
ActionState koFilterAction = view2d.getEventManager().getAction(ActionW.KO_FILTER);
if (koFilterAction instanceof ToggleButtonListener) {
((ToggleButtonListener) koFilterAction).setSelectedWithoutTriggerAction(false);
((ToggleButtonListener) koFilterAction).setSelected(true);
}
}
}
}
return hasKeyObjectReferenceChanged;
}
public static boolean setKeyObjectReferenceAllSeries(boolean selectedState,
final ViewCanvas<DicomImageElement> view2d) {
KOSpecialElement validKOSelection = getValidKOSelection(view2d);
if (validKOSelection == null) {
return false; // canceled
}
KOSpecialElement currentSelectedKO = KOManager.getCurrentKOSelection(view2d);
if (validKOSelection != currentSelectedKO) {
ActionState koSelection = view2d.getEventManager().getAction(ActionW.KO_SELECTION);
if (koSelection instanceof ComboItemListener) {
((ComboItemListener) koSelection).setSelectedItem(validKOSelection);
}
}
boolean hasKeyObjectReferenceChanged = false;
if (validKOSelection == currentSelectedKO || currentSelectedKO == null) {
// KO Toogle State is changed only if KO Selection remains the same,
// or if there was no previous KO Selection
List<DicomImageElement> dicomImageList = view2d.getSeries().getSortedMedias(null);
hasKeyObjectReferenceChanged = validKOSelection.setKeyObjectReference(selectedState, dicomImageList);
if (hasKeyObjectReferenceChanged) {
DicomModel dicomModel = (DicomModel) view2d.getSeries().getTagValue(TagW.ExplorerModel);
// Fire an event since any view in any View2dContainer may have its KO selected state changed
if (dicomModel != null) {
dicomModel.firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.UPDATE, view2d, null,
new SeriesEvent(SeriesEvent.Action.UPDATE, validKOSelection, "updateAll"))); //$NON-NLS-1$
}
}
}
return hasKeyObjectReferenceChanged;
}
public static void updateKOFilter(ViewCanvas<DicomImageElement> view2D, Object newSelectedKO, Boolean enableFilter,
int imgSelectionIndex) {
updateKOFilter(view2D, newSelectedKO, enableFilter, imgSelectionIndex, true);
}
public static void updateKOFilter(ViewCanvas<DicomImageElement> view2D, Object newSelectedKO, Boolean enableFilter,
int imgSelectionIndex, boolean updateImage) {
if (view2D instanceof View2d) {
boolean tiledMode = imgSelectionIndex >= 0;
boolean koFilter = false;
KOSpecialElement selectedKO = null;
if (newSelectedKO == null) {
Object actionValue = view2D.getActionValue(ActionW.KO_SELECTION.cmd());
if (actionValue instanceof KOSpecialElement) {
selectedKO = (KOSpecialElement) actionValue;
// test if current ko_selection action in view do still exist
Collection<KOSpecialElement> koElements = (view2D != null && view2D.getSeries() != null)
? DicomModel.getKoSpecialElements(view2D.getSeries()) : null;
if (koElements != null && koElements.contains(selectedKO) == false) {
selectedKO = null;
newSelectedKO = ActionState.NoneLabel.NONE;
view2D.setActionsInView(ActionW.KO_SELECTION.cmd(), newSelectedKO);
}
}
} else {
if (newSelectedKO instanceof KOSpecialElement) {
selectedKO = (KOSpecialElement) newSelectedKO;
}
view2D.setActionsInView(ActionW.KO_SELECTION.cmd(), newSelectedKO);
}
if (enableFilter == null) {
koFilter = JMVUtils.getNULLtoFalse(view2D.getActionValue(ActionW.KO_FILTER.cmd()));
} else {
koFilter = enableFilter;
}
if (tiledMode && selectedKO == null) {
// Unselect the filter with the None KO selection
koFilter = false;
}
view2D.setActionsInView(ActionW.KO_FILTER.cmd(), koFilter);
view2D.setActionsInView(ActionW.FILTERED_SERIES.cmd(), null);
if (selectedKO == null || view2D.getSeries() == null || (view2D.getImage() == null && !tiledMode)) {
if (newSelectedKO != null) {
if (updateImage) {
updateImage(view2D, null, view2D.getFrameIndex());
}
// Update the None KO selection
((View2d) view2D).updateKOButtonVisibleState();
}
return;
}
DicomSeries dicomSeries = (DicomSeries) view2D.getSeries();
String seriesInstanceUID = TagD.getTagValue(dicomSeries, Tag.SeriesInstanceUID, String.class);
Filter<DicomImageElement> sopInstanceUIDFilter = null;
if (koFilter && selectedKO.containsSeriesInstanceUIDReference(seriesInstanceUID)) {
sopInstanceUIDFilter = selectedKO.getSOPInstanceUIDFilter();
}
view2D.setActionsInView(ActionW.FILTERED_SERIES.cmd(), sopInstanceUIDFilter);
if (updateImage) {
/*
* The getFrameIndex() returns a valid index for the current image displayed according to the current
* FILTERED_SERIES and the current SortComparator
*/
int newImageIndex = view2D.getFrameIndex();
if (tiledMode) {
newImageIndex = view2D.getTileOffset() + imgSelectionIndex;
}
if (koFilter && newImageIndex < 0) {
if (dicomSeries.size(sopInstanceUIDFilter) > 0 && view2D.getImage() != null) {
double[] val = (double[]) view2D.getImage().getTagValue(TagW.SlicePosition);
if (val != null) {
double location = val[0] + val[1] + val[2];
// Double offset = (Double) view2D.getActionValue(ActionW.STACK_OFFSET.cmd());
// if (offset != null) {
// location += offset;
newImageIndex = dicomSeries.getNearestImageIndex(location, view2D.getTileOffset(),
sopInstanceUIDFilter, view2D.getCurrentSortComparator());
}
} else {
// If there is no more image in KO series filtered then disable the KO_FILTER
sopInstanceUIDFilter = null;
view2D.setActionsInView(ActionW.KO_FILTER.cmd(), false);
view2D.setActionsInView(ActionW.FILTERED_SERIES.cmd(), sopInstanceUIDFilter);
newImageIndex = view2D.getFrameIndex();
}
}
updateImage(view2D, sopInstanceUIDFilter, newImageIndex);
}
((View2d) view2D).updateKOButtonVisibleState();
}
}
private static void updateImage(ViewCanvas<DicomImageElement> view2D,
Filter<DicomImageElement> sopInstanceUIDFilter, int newImageIndex) {
int imgIndex = newImageIndex < 0 ? 0 : newImageIndex;
if (view2D == view2D.getEventManager().getSelectedViewPane()) {
/*
* Update the sliceAction action according to nearest image when the filter hides the image of the previous
* state. And update the action min and max.
*/
ActionState seqAction = view2D.getEventManager().getAction(ActionW.SCROLL_SERIES);
if (seqAction instanceof SliderCineListener) {
SliderChangeListener moveTroughSliceAction = (SliderChangeListener) seqAction;
moveTroughSliceAction.setSliderMinMaxValue(1, view2D.getSeries().size(sopInstanceUIDFilter),
imgIndex + 1);
}
}
DicomImageElement newImage = null;
if (view2D.getSeries() != null) {
newImage = view2D.getSeries().getMedia(imgIndex, sopInstanceUIDFilter, view2D.getCurrentSortComparator());
}
if (newImage != null && !newImage.isImageAvailable()) {
newImage.getImage();
}
((View2d) view2D).setImage(newImage);
}
}
|
package org.webrtc.voiceengine;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.audiofx.AcousticEchoCanceler;
import android.media.audiofx.AudioEffect;
import android.media.audiofx.AudioEffect.Descriptor;
import android.media.AudioManager;
import android.os.Build;
import android.os.Process;
import org.webrtc.Logging;
import java.lang.Thread;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class WebRtcAudioUtils {
private static final String TAG = "WebRtcAudioUtils";
// List of devices where we have seen issues (e.g. bad audio quality) using
// the low latency output mode in combination with OpenSL ES.
// The device name is given by Build.MODEL.
private static final String[] BLACKLISTED_OPEN_SL_ES_MODELS = new String[] {
// This list is currently empty ;-)
};
// List of devices where it has been verified that the built-in effect
// bad and where it makes sense to avoid using it and instead rely on the
// native WebRTC version instead. The device name is given by Build.MODEL.
private static final String[] BLACKLISTED_AEC_MODELS = new String[] {
"D6503", // Sony Xperia Z2 D6503
"ONE A2005", // OnePlus 2
"MotoG3", // Moto G (3rd Generation)
};
private static final String[] BLACKLISTED_AGC_MODELS = new String[] {
"Nexus 10",
"Nexus 9",
};
private static final String[] BLACKLISTED_NS_MODELS = new String[] {
"Nexus 10",
"Nexus 9",
"ONE A2005", // OnePlus 2
};
// Use 16kHz as the default sample rate. A higher sample rate might prevent
// us from supporting communication mode on some older (e.g. ICS) devices.
private static final int DEFAULT_SAMPLE_RATE_HZ = 16000;
private static int defaultSampleRateHz = DEFAULT_SAMPLE_RATE_HZ;
// Set to true if setDefaultSampleRateHz() has been called.
private static boolean isDefaultSampleRateOverridden = false;
// By default, utilize hardware based audio effects when available.
private static boolean useWebRtcBasedAcousticEchoCanceler = false;
private static boolean useWebRtcBasedAutomaticGainControl = false;
private static boolean useWebRtcBasedNoiseSuppressor = false;
// Call these methods if any hardware based effect shall be replaced by a
// software based version provided by the WebRTC stack instead.
public static synchronized void setWebRtcBasedAcousticEchoCanceler(
boolean enable) {
useWebRtcBasedAcousticEchoCanceler = enable;
}
public static synchronized void setWebRtcBasedAutomaticGainControl(
boolean enable) {
useWebRtcBasedAutomaticGainControl = enable;
}
public static synchronized void setWebRtcBasedNoiseSuppressor(
boolean enable) {
useWebRtcBasedNoiseSuppressor = enable;
}
public static synchronized boolean useWebRtcBasedAcousticEchoCanceler() {
if (useWebRtcBasedAcousticEchoCanceler) {
Logging.w(TAG, "Overriding default behavior; now using WebRTC AEC!");
}
return useWebRtcBasedAcousticEchoCanceler;
}
public static synchronized boolean useWebRtcBasedAutomaticGainControl() {
if (useWebRtcBasedAutomaticGainControl) {
Logging.w(TAG, "Overriding default behavior; now using WebRTC AGC!");
}
return useWebRtcBasedAutomaticGainControl;
}
public static synchronized boolean useWebRtcBasedNoiseSuppressor() {
if (useWebRtcBasedNoiseSuppressor) {
Logging.w(TAG, "Overriding default behavior; now using WebRTC NS!");
}
return useWebRtcBasedNoiseSuppressor;
}
// Call this method if the default handling of querying the native sample
// rate shall be overridden. Can be useful on some devices where the
// available Android APIs are known to return invalid results.
public static synchronized void setDefaultSampleRateHz(int sampleRateHz) {
isDefaultSampleRateOverridden = true;
defaultSampleRateHz = sampleRateHz;
}
public static synchronized boolean isDefaultSampleRateOverridden() {
return isDefaultSampleRateOverridden;
}
public static synchronized int getDefaultSampleRateHz() {
return defaultSampleRateHz;
}
public static List<String> getBlackListedModelsForAecUsage() {
return Arrays.asList(WebRtcAudioUtils.BLACKLISTED_AEC_MODELS);
}
public static List<String> getBlackListedModelsForAgcUsage() {
return Arrays.asList(WebRtcAudioUtils.BLACKLISTED_AGC_MODELS);
}
public static List<String> getBlackListedModelsForNsUsage() {
return Arrays.asList(WebRtcAudioUtils.BLACKLISTED_NS_MODELS);
}
public static boolean runningOnGingerBreadOrHigher() {
// November 2010: Android 2.3, API Level 9.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
public static boolean runningOnJellyBeanOrHigher() {
// June 2012: Android 4.1. API Level 16.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
public static boolean runningOnJellyBeanMR1OrHigher() {
// November 2012: Android 4.2. API Level 17.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
}
public static boolean runningOnJellyBeanMR2OrHigher() {
// July 24, 2013: Android 4.3. API Level 18.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
}
public static boolean runningOnLollipopOrHigher() {
// API Level 21.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
// TODO(phoglund): enable when all downstream users use M.
// public static boolean runningOnMOrHigher() {
// API Level 23.
// return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
// Helper method for building a string of thread information.
public static String getThreadInfo() {
return "@[name=" + Thread.currentThread().getName()
+ ", id=" + Thread.currentThread().getId() + "]";
}
// Returns true if we're running on emulator.
public static boolean runningOnEmulator() {
return Build.HARDWARE.equals("goldfish") &&
Build.BRAND.startsWith("generic_");
}
// Returns true if the device is blacklisted for OpenSL ES usage.
public static boolean deviceIsBlacklistedForOpenSLESUsage() {
List<String> blackListedModels =
Arrays.asList(BLACKLISTED_OPEN_SL_ES_MODELS);
return blackListedModels.contains(Build.MODEL);
}
// Information about the current build, taken from system properties.
public static void logDeviceInfo(String tag) {
Logging.d(tag, "Android SDK: " + Build.VERSION.SDK_INT + ", "
+ "Release: " + Build.VERSION.RELEASE + ", "
+ "Brand: " + Build.BRAND + ", "
+ "Device: " + Build.DEVICE + ", "
+ "Id: " + Build.ID + ", "
+ "Hardware: " + Build.HARDWARE + ", "
+ "Manufacturer: " + Build.MANUFACTURER + ", "
+ "Model: " + Build.MODEL + ", "
+ "Product: " + Build.PRODUCT);
}
public static boolean hasPermission(Context context, String permission) {
return context.checkPermission(
permission,
Process.myPid(),
Process.myUid()) == PackageManager.PERMISSION_GRANTED;
}
}
|
package com.nitorcreations.willow.eventhandler;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.nitorcreations.willow.messages.event.EventMessage;
import com.nitorcreations.willow.messages.metrics.MetricConfig;
import com.nitorcreations.willow.sshagentauth.SSHUtil;
/**
* Event poller for receiving events from metrics server via websocket and dispatching them to event handlers.
*
* @author mtommila
*/
public class EventPoller {
private Logger logger = Logger.getLogger(getClass().getName());
private Map<String, List<EventHandler>> eventHandlers;
@Inject
private Gson gson;
@Inject
private ExecutorService executorService;
/**
* Initialize the event poller.
*
* @param eventHandlers The handlers for different event types.
* @param uri The web socket connection URI.
*/
public void initialize(Map<String, List<EventHandler>> eventHandlers, URI uri) {
this.eventHandlers = eventHandlers;
EventListener listener = new EventListener(uri);
executorService.submit(listener);
logger.fine("Started event listener");
}
/**
* Websocket message listener. Dispatches events to the event handlers.
* Autowired to Jetty websocket implementation via annotations.
*
* @author mtommila
*/
@WebSocket
public class EventListener implements Runnable {
private Logger logger = Logger.getLogger(getClass().getName());
private URI uri;
private WebSocketClient client;
private CountDownLatch connectLatch;
private Set<String> messageIds = new HashSet<>();
private EventListener(URI uri) {
this.uri = uri;
}
private synchronized WebSocketClient getClient() {
if (this.client == null) {
this.client = new WebSocketClient();
}
return this.client;
}
private synchronized WebSocketClient createClient() {
this.client = new WebSocketClient();
return this.client;
}
private void connect() throws Exception {
logger.info("Connecting event listener");
WebSocketClient client = createClient();
client.start();
client.setAsyncWriteTimeout(5000);
client.setConnectTimeout(2000);
client.setStopTimeout(5000);
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("Authorization", SSHUtil.getPublicKeyAuthorization(System.getProperty("user.name", "willow")));
Future<Session> future = client.connect(this, uri, request);
logger.info("Connecting to : " + uri);
try {
future.get();
logger.info("Connected to : " + uri);
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed to connect event poller with uri " + uri, e);
if (client.isRunning()) {
client.stop();
client.destroy();
}
throw e;
}
}
@OnWebSocketMessage
public void messageReceived(Session session, String message) {
if (message == null || message.isEmpty()) {
return;
}
EventMessage[] eventMessages = null;
List<EventMessage> uniqueEventMessages = new ArrayList<>();
try {
eventMessages = gson.fromJson(gson.fromJson(message, JsonObject.class).get("data"), EventMessage[].class);
} catch (Exception e) {
logger.log(Level.INFO, "Failure in unmarshalling event data", e);
}
if (eventMessages != null) {
// Loop through all events that happened during the retrieved time window
synchronized (messageIds) {
Set<String> newMessageIds = new HashSet<>();
for (EventMessage eventMessage : eventMessages) {
if (eventMessage != null && eventMessage.eventType != null && eventMessage.getId() != null) {
String id = eventMessage.getId();
newMessageIds.add(id);
// Ignore duplicate messages
if (!messageIds.contains(id)) {
uniqueEventMessages.add(eventMessage);
}
}
}
// Clear the previous message IDs and set the now received message IDs, note the synchronization
messageIds.clear();
messageIds.addAll(newMessageIds);
}
// Loop through configured handlers to handle the non-duplicate message
for (EventMessage eventMessage : uniqueEventMessages) {
List<EventHandler> messageEventHandlers = eventHandlers.get(eventMessage.eventType);
if (messageEventHandlers != null) {
for (EventHandler eventHandler : messageEventHandlers) {
try {
eventHandler.handle(eventMessage);
} catch (Exception e) {
logger.log(Level.INFO, "Failure in handling event data", e);
}
}
}
}
}
}
@OnWebSocketClose
public void handleClose(Session closedSession, int statusCode, String reason) {
logger.log(Level.INFO, "Event listener websocket closed with status " + statusCode + ". Reason: " + reason);
closeClient();
connectLatch.countDown();
}
@OnWebSocketError
public void handleError(Session errorSession, Throwable throwable) {
logger.log(Level.INFO, "Event listener websocket error", throwable);
closeClient();
connectLatch.countDown();
}
@OnWebSocketConnect
public void startPolling(Session session) {
logger.info("Sending poll request for events");
MetricConfig metricConfig = new MetricConfig();
long now = System.currentTimeMillis();
metricConfig.setId("eventhandler");
metricConfig.setMetricKey("/event");
metricConfig.setStart(now - 20000); // For the first chunk, send events from 20s ago
metricConfig.setStop(now); // ... up to the current moment.
metricConfig.setStep(10000); // Then keep sending data every 10 seconds.
metricConfig.setMinSteps(2); // Every time send data for the last 2 * 10 = 20 seconds.
String json = gson.toJson(metricConfig);
logger.info("Sending polling request " + json);
try {
session.getRemote().sendString(json);
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to send event polling request", e);
closeClient();
connectLatch.countDown();
}
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
WebSocketClient client = getClient();
if (!client.isRunning() && !client.isStarting() || client.isFailed()) {
try {
connect();
connectLatch = new CountDownLatch(1);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error setting up websocket connection", e);
}
}
try {
connectLatch.await();
} catch (InterruptedException e) {
}
}
}
private void closeClient() {
try {
WebSocketClient client = getClient();
if (client.isRunning()) {
client.stop();
client.destroy();
}
} catch (Exception e) {
logger.log(Level.INFO, "Error stopping websocket client", e);
}
}
}
}
|
package com.example.alexeyglushkov.wordteacher;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import main.MainApplication;
import model.Card;
import model.Course;
import model.CourseHolder;
public class CourseStackFragment extends StackFragment {
public static final String DEFAULT_TITLE = "Courses";
private MainApplication getMainApplication() {
return MainApplication.instance;
}
public CourseHolder getCourseHolder() {
return getMainApplication().getCourseHolder();
}
private CourseStackFragment.Listener getCourseListener() {
return (CourseStackFragment.Listener)listener;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
showCourseFragment();
} else {
restoreListeners();
}
}
public void updateCourses(ArrayList<Course> courses) {
CourseFragment courseFragment = getCourseFragment();
courseFragment.setCourses(courses);
}
public void updateCards(ArrayList<Card> cards) {
CourseFragment cardsFragment = getCardsFragment();
cardsFragment.setCards(cards);
}
private void showCourseFragment() {
CourseFragment courseFragment = new CourseFragment();
courseFragment.setViewType(CourseFragment.ViewType.Courses);
courseFragment.setListener(getMenuListener());
addFragment(courseFragment, null);
}
public void showCardsFragment(Course course) {
CourseFragment fragment = new CourseFragment();
fragment.setListener(getMenuListener());
fragment.setViewType(CourseFragment.ViewType.Cards);
ArrayList<Course> list = new ArrayList<>();
list.add(course);
fragment.setParentCourse(course);
fragment.setCourses(list);
addFragment(fragment, new TransactionCallback() {
@Override
public void onFinished() {
}
});
}
private void restoreListeners() {
CourseFragment setFragment = getCourseFragment();
if (setFragment != null) {
setFragment.setListener(getMenuListener());
}
CourseFragment cardsFragment = getCardsFragment();
if (cardsFragment != null) {
cardsFragment.setListener(getMenuListener());
}
}
private CourseFragment getCourseFragment() {
List<Fragment> list = getChildFragmentManager().getFragments();
return list != null && list.size() > 0 ? (CourseFragment)list.get(0) : null;
}
private CourseFragment getCardsFragment() {
List<Fragment> list = getChildFragmentManager().getFragments();
return list != null && list.size() > 1 ? (CourseFragment)list.get(1) : null;
}
public void updateCourses() {
CourseFragment courseFragment = getCourseFragment();
if (courseFragment != null) {
ArrayList<Course> courses = getCourseHolder().getCourses();
Collections.sort(courses, new Comparator<Course>() {
@Override
public int compare(Course lhs, Course rhs) {
return rhs.getCreateDate().compareTo(lhs.getCreateDate());
}
});
courseFragment.setCourses(courses);
}
}
public String getTitle() {
String title = null;
if (getBackStackSize() > 0) {
title = getCardsFragment().getParentCourse().getTitle();
} else {
title = DEFAULT_TITLE;
}
return title;
}
private CourseFragmentMenuListener getMenuListener() {
return new CourseFragmentMenuListener(getContext(), getCourseHolder(), new CourseFragmentMenuListener.Listener() {
@Override
public void onCourseDeleteClicked(Course course) {
getCourseFragment().deleteCourse(course);
}
@Override
public void onCardDeleteClicked(Card card) {
getCardsFragment().deleteCard(card);
}
@Override
public void onShowCourseContentClicked(Course course) {
showCardsFragment(course);
}
@Override
public void onCourseClicked(Course course) {
CourseStackFragment.this.getCourseListener().onCourseClicked(course);
}
@Override
public void onLearnReadyWordsClick(Course course) {
CourseStackFragment.this.getCourseListener().onLearnReadyWordsClick(course);
}
@Override
public void onLearnNewWordsClick(Course course) {
CourseStackFragment.this.getCourseListener().onLearnNewWordsClick(course);
}
@Override
public void onCourseDeletionCancelled(Course course) {
updateCourses();
}
@Override
public void onCourseDeleted(Course course) {
updateCourses();
}
@Override
public View getSnackBarViewContainer() {
return getView();
}
});
}
// CourseFragment.Listener
public interface Listener extends StackFragment.Listener {
void onCourseClicked(Course course);
void onLearnReadyWordsClick(Course course);
void onLearnNewWordsClick(Course course);
}
}
|
package com.rehivetech.beeeon.gui.adapter.dashboard;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.rehivetech.beeeon.IconResourceType;
import com.rehivetech.beeeon.R;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.gui.activity.BaseApplicationActivity;
import com.rehivetech.beeeon.gui.adapter.RecyclerViewSelectableAdapter;
import com.rehivetech.beeeon.gui.adapter.dashboard.items.ActualValueItem;
import com.rehivetech.beeeon.gui.adapter.dashboard.items.BaseItem;
import com.rehivetech.beeeon.gui.adapter.dashboard.items.GraphItem;
import com.rehivetech.beeeon.gui.adapter.dashboard.items.OverviewGraphItem;
import com.rehivetech.beeeon.household.device.Module;
import com.rehivetech.beeeon.household.device.ModuleLog;
import com.rehivetech.beeeon.household.device.values.EnumValue;
import com.rehivetech.beeeon.household.gate.Gate;
import com.rehivetech.beeeon.util.ChartHelper;
import com.rehivetech.beeeon.util.TimeHelper;
import com.rehivetech.beeeon.util.UnitsHelper;
import com.rehivetech.beeeon.util.Utils;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DashboardAdapter extends RecyclerViewSelectableAdapter {
private static final String TAG = DashboardAdapter.class.getSimpleName();
private static final String GRAPH_DATE_TIME_FORMAT = "dd.MM. HH:mm";
private static final int VIEW_TYPE_GRAPH = 0;
private static final int VIEW_TYPE_ACT_VALUE = 1;
private static final int VIEW_TYPE_GRAPH_OVERVIEW = 2;
private final TimeHelper mTimeHelper;
private final UnitsHelper mUnitsHelper;
private BaseApplicationActivity mActivity;
private IItemClickListener mItemClickListener;
private List<BaseItem> mItems = new ArrayList<>();
public DashboardAdapter(BaseApplicationActivity activity, IItemClickListener itemClickListener) {
super(activity);
mActivity = activity;
mItemClickListener = itemClickListener;
SharedPreferences prefs = Controller.getInstance(mActivity).getUserSettings();
mTimeHelper = (prefs == null) ? null : new TimeHelper(prefs);
mUnitsHelper = (prefs == null) ? null : new UnitsHelper(prefs, mActivity);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_GRAPH: {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dashboard_item_graph, parent, false);
return new DashboardGraphViewHolder(view);
}
case VIEW_TYPE_ACT_VALUE: {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dashboard_item_act_value, parent, false);
return new ActualValueViewHolder(view);
}
case VIEW_TYPE_GRAPH_OVERVIEW: {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dashboard_item_overview_graph, parent, false);
return new OverviewGraphViewHolder(view);
}
default:
break;
}
return null;
}
@Override
public int getItemViewType(int position) {
BaseItem item = mItems.get(position);
if (item instanceof GraphItem) {
return VIEW_TYPE_GRAPH;
} else if (item instanceof ActualValueItem) {
return VIEW_TYPE_ACT_VALUE;
} else if (item instanceof OverviewGraphItem) {
return VIEW_TYPE_GRAPH_OVERVIEW;
}
return -1;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
BaseItem item = mItems.get(position);
Controller controller = Controller.getInstance(mActivity);
int viewType = holder.getItemViewType();
switch (viewType) {
case VIEW_TYPE_GRAPH:
((DashboardGraphViewHolder) holder).bind(controller, (GraphItem) item, position);
break;
case VIEW_TYPE_ACT_VALUE: {
((ActualValueViewHolder) holder).bind(controller, (ActualValueItem) item, position);
break;
}
case VIEW_TYPE_GRAPH_OVERVIEW: {
((OverviewGraphViewHolder) holder).bind(controller, (OverviewGraphItem) item, position);
break;
}
}
}
@Override
public int getItemCount() {
return mItems.size();
}
public void addItem(BaseItem item) {
mItems.add(item);
notifyItemRangeInserted(0, mItems.size());
}
public void addItem(int position, BaseItem item) {
mItems.add(position, item);
notifyItemInserted(position);
}
public List<BaseItem> getItems() {
return mItems;
}
public void setItems(List<BaseItem> items) {
mItems = items;
}
public BaseItem getItem(int position) {
return mItems.get(position);
}
public void deleteItem(BaseItem item) {
int position = mItems.indexOf(item);
mItems.remove(item);
notifyItemRemoved(position);
}
public abstract class BaseDashboardViewHolder extends SelectableViewHolder {
public final CardView mCardView;
public BaseDashboardViewHolder(View itemView) {
super(itemView);
mCardView = (CardView) itemView;
}
@Override
protected void setSelectedBackground(boolean isSelected) {
if (isSelected) {
mCardView.setCardBackgroundColor(ContextCompat.getColor(mActivity, R.color.gray_material_400));
} else {
mCardView.setCardBackgroundColor(ContextCompat.getColor(mActivity, R.color.white));
}
}
}
public class DashboardGraphViewHolder extends BaseDashboardViewHolder implements View.OnClickListener, View.OnLongClickListener {
public final TextView mGraphName;
public final TextView mLeftAxisUnit;
public final TextView mRightAxisUnit;
public final LineChart mChart;
public final TextView mLastUpdate;
public DashboardGraphViewHolder(View itemView) {
super(itemView);
mGraphName = (TextView) itemView.findViewById(R.id.dashboard_item_graph_name);
mLeftAxisUnit = (TextView) itemView.findViewById(R.id.dashboard_item_graph_left_axis_unit);
mRightAxisUnit = (TextView) itemView.findViewById(R.id.dashboard_item_graph_right_axis_unit);
mChart = (LineChart) itemView.findViewById(R.id.dashboard_item_graph_chart);
mLastUpdate = (TextView) itemView.findViewById(R.id.dashboard_item_graph_last_update_value);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void bind(Controller controller, GraphItem item, int position) {
Gate gate = controller.getGatesModel().getGate(item.getGateId());
Module module = controller.getDevicesModel().getModule(item.getGateId(), item.getAbsoluteModuleIds().get(0));
mGraphName.setText(item.getName());
mLastUpdate.setText(mTimeHelper.formatLastUpdate(module.getDevice().getLastUpdate(), gate));
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
mChart.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mChart.clear();
prepareChart(item);
mChart.setNoDataText(mActivity.getString(R.string.chart_helper_chart_loading));
fillChart(controller, item, gate);
setSelected(isSelected(position));
}
private void prepareChart(GraphItem item) {
ChartHelper.prepareChart(mChart, mActivity, null, null, null, false, false);
ChartHelper.prepareXAxis(mActivity, mChart.getXAxis(), null, XAxis.XAxisPosition.BOTTOM, false);
ChartHelper.prepareYAxis(mActivity, null, mChart.getAxisLeft(), Utils.getGraphColor(mActivity, 0), YAxis.YAxisLabelPosition.OUTSIDE_CHART, false, true, 3);
if (item.getAbsoluteModuleIds().size() > 1) {
ChartHelper.prepareYAxis(mActivity, null, mChart.getAxisRight(), Utils.getGraphColor(mActivity, 1), YAxis.YAxisLabelPosition.OUTSIDE_CHART, false, true, 3);
} else {
mChart.getAxisRight().setEnabled(false);
}
mChart.setOnTouchListener(null);
}
private void fillChart(final Controller controller, final GraphItem item, final Gate gate) {
final DateTimeFormatter dateTimeFormatter = mTimeHelper.getFormatter(GRAPH_DATE_TIME_FORMAT, gate);
YAxis.AxisDependency axisDependency = YAxis.AxisDependency.LEFT;
final List<String> modules = item.getAbsoluteModuleIds();
for (int i = 0; i < modules.size(); i++) {
final LineDataSet dataSet = new LineDataSet(new ArrayList<Entry>(), modules.get(i));
dataSet.setAxisDependency(axisDependency);
ChartHelper.prepareDataSet(mActivity, dataSet, false, true, Utils.getGraphColor(mActivity, i), ContextCompat.getColor(mActivity, R.color.beeeon_accent), false);
ChartHelper.ChartLoadListener chartLoadListener = new ChartHelper.ChartLoadListener() {
@Override
public void onChartLoaded(DataSet dataset, List<String> xValues) {
if (dataset.getYVals().size() > 1) {
LineData lineData = mChart.getLineData() != null ? mChart.getLineData() : new LineData(xValues);
lineData.addDataSet(dataSet);
mChart.setData(lineData);
mLeftAxisUnit.setVisibility(View.VISIBLE);
mLeftAxisUnit.setText(mUnitsHelper.getStringUnit(controller.getDevicesModel().getModule(gate.getId(), modules.get(0)).getValue()));
mLeftAxisUnit.setTextColor(Utils.getGraphColor(mActivity, 0));
if (modules.size() > 1) {
mRightAxisUnit.setVisibility(View.VISIBLE);
mRightAxisUnit.setText(mUnitsHelper.getStringUnit(controller.getDevicesModel().getModule(gate.getId(), modules.get(1)).getValue()));
mRightAxisUnit.setTextColor(Utils.getGraphColor(mActivity, 1));
}
} else {
if (dataset.getAxisDependency() == YAxis.AxisDependency.LEFT) {
mLeftAxisUnit.setVisibility(View.GONE);
mChart.getAxisLeft().setEnabled(false);
} else {
mRightAxisUnit.setVisibility(View.GONE);
mChart.getAxisRight().setEnabled(false);
}
}
mChart.setNoDataText(mActivity.getString(R.string.chart_helper_chart_no_data));
mChart.invalidate();
}
};
Module module = controller.getDevicesModel().getModule(gate.getId(), modules.get(i));
ModuleLog.DataInterval dataInterval = (item.getDataRange() > ChartHelper.RANGE_DAY) ? ModuleLog.DataInterval.HALF_HOUR : ModuleLog.DataInterval.TEN_MINUTES;
ChartHelper.loadChartData(mActivity, controller, dataSet, item.getGateId(), module.getDevice().getId(), module.getId(), item.getDataRange(),
ModuleLog.DataType.AVERAGE, dataInterval, chartLoadListener, dateTimeFormatter);
axisDependency = YAxis.AxisDependency.RIGHT;
}
}
@Override
public void onClick(View v) {
}
@Override
public boolean onLongClick(View v) {
if (mItemClickListener != null && mItemClickListener.onRecyclerViewItemLongClick(getAdapterPosition(), getItemViewType())) {
v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
return false;
}
}
public class ActualValueViewHolder extends BaseDashboardViewHolder implements View.OnClickListener, View.OnLongClickListener {
public final ImageView mIcon;
public final TextView mLabel;
public final TextView mValue;
public final TextView mLastUpdate;
public ActualValueViewHolder(View itemView) {
super(itemView);
mIcon = (ImageView) itemView.findViewById(R.id.dashboard_item_act_value_icon);
mLabel = (TextView) itemView.findViewById(R.id.dashboard_item_act_value_label);
mValue = (TextView) itemView.findViewById(R.id.dashboard_item_act_value_value);
mLastUpdate = (TextView) itemView.findViewById(R.id.dashboard_item_act_value_last_update_value);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void bind(Controller controller, ActualValueItem item, int position) {
Module module = controller.getDevicesModel().getModule(item.getGateId(), item.getAbsoluteModuleId());
SharedPreferences prefs = controller.getUserSettings();
UnitsHelper unitsHelper = new UnitsHelper(prefs, mActivity);
mLabel.setText(item.getName());
mIcon.setImageResource(module.getIconResource(IconResourceType.DARK));
if (module.getValue() instanceof EnumValue) {
mValue.setText(((EnumValue) module.getValue()).getStateStringResource());
} else {
mValue.setText(String.format("%s %s", unitsHelper.getStringValue(module.getValue()), unitsHelper.getStringUnit(module.getValue())));
}
mLastUpdate.setText(mTimeHelper.formatLastUpdate(module.getDevice().getLastUpdate(), controller.getGatesModel().getGate(item.getGateId())));
setSelected(isSelected(position));
}
@Override
public void onClick(View v) {
}
@Override
public boolean onLongClick(View v) {
if (mItemClickListener != null && mItemClickListener.onRecyclerViewItemLongClick(getAdapterPosition(), getItemViewType())) {
v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
return false;
}
}
public class OverviewGraphViewHolder extends BaseDashboardViewHolder implements View.OnClickListener, View.OnLongClickListener {
public final TextView mGraphName;
public final TextView mGraphUnit;
public final BarChart mChart;
public final TextView mLastUpdate;
public OverviewGraphViewHolder(View itemView) {
super(itemView);
mGraphName = (TextView) itemView.findViewById(R.id.dashboard_item_overview_graph_name);
mGraphUnit = (TextView) itemView.findViewById(R.id.dashboard_item_overview_graph_axis_unit);
mChart = (BarChart) itemView.findViewById(R.id.dashboard_item_overview_graph_chart);
mLastUpdate = (TextView) itemView.findViewById(R.id.dashboard_item_overview_graph_last_update_value);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void bind(Controller controller, OverviewGraphItem item, int position) {
Gate gate = controller.getGatesModel().getGate(item.getGateId());
Module module = controller.getDevicesModel().getModule(gate.getId(), item.getAbsoluteModuleId());
mGraphName.setText(item.getName());
mLastUpdate.setText(mTimeHelper.formatLastUpdate(module.getDevice().getLastUpdate(), gate));
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
mChart.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mChart.clear();
prepareChart();
mChart.setNoDataText(mActivity.getString(R.string.chart_helper_chart_loading));
fillChart(controller, item, gate, module);
setSelected(isSelected(position));
}
private void prepareChart() {
ChartHelper.prepareChart(mChart, mActivity, null, null, null, false, false);
XAxis xAxis = mChart.getXAxis();
ChartHelper.prepareXAxis(mActivity, xAxis, null, XAxis.XAxisPosition.BOTTOM, false);
ChartHelper.prepareYAxis(mActivity, null, mChart.getAxisLeft(), Utils.getGraphColor(mActivity, 0), YAxis.YAxisLabelPosition.OUTSIDE_CHART, false, true, 3);
mChart.getAxisRight().setEnabled(false);
mChart.setOnTouchListener(null);
}
private void fillChart(Controller controller, OverviewGraphItem item, Gate gate, final Module module) {
final DateTimeFormatter dateTimeFormatter = mTimeHelper.getFormatter(GRAPH_DATE_TIME_FORMAT, gate);
final BarDataSet dataSet = new BarDataSet(new ArrayList<BarEntry>(), item.getAbsoluteModuleId());
ChartHelper.prepareDataSet(mActivity, dataSet, true, false, Utils.getGraphColor(mActivity, 0), ContextCompat.getColor(mActivity, R.color.beeeon_accent), false);
ChartHelper.ChartLoadListener chartLoadListener = new ChartHelper.ChartLoadListener() {
@Override
public void onChartLoaded(DataSet dataset, List<String> xValues) {
if (dataSet.getYVals().size() > 1) {
BarData barData = mChart.getBarData() != null ? mChart.getBarData() : new BarData(xValues);
barData.addDataSet(dataSet);
mChart.setData(barData);
List<String> xValuesCustom = new ArrayList<>(Arrays.asList(mActivity.getString(R.string.monday),
mActivity.getString(R.string.tuesday),
mActivity.getString(R.string.wednesday),
mActivity.getString(R.string.thursday),
mActivity.getString(R.string.friday),
mActivity.getString(R.string.saturday),
mActivity.getString(R.string.sunday)));
mChart.getXAxis().setValues(xValuesCustom);
mGraphUnit.setText(mUnitsHelper.getStringUnit(module.getValue()));
mGraphUnit.setTextColor(Utils.getGraphColor(mActivity, 0));
}
mChart.setNoDataText(mActivity.getString(R.string.chart_helper_chart_no_data));
mChart.invalidate();
}
};
ModuleLog.DataInterval dataInterval = ModuleLog.DataInterval.DAY;
ChartHelper.loadChartData(mActivity, controller, dataSet, item.getGateId(), module.getDevice().getId(), module.getId(), ChartHelper.RANGE_WEEK,
item.getDataType(), dataInterval, chartLoadListener, dateTimeFormatter);
}
@Override
public void onClick(View v) {
}
@Override
public boolean onLongClick(View v) {
if (mItemClickListener != null && mItemClickListener.onRecyclerViewItemLongClick(getAdapterPosition(), getItemViewType())) {
v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
return false;
}
}
}
|
package com.braintreepayments.cardform.view;
import android.text.Editable;
import android.text.Spanned;
import android.view.View;
import com.braintreepayments.cardform.R;
import com.braintreepayments.cardform.test.TestActivity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.Calendar;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
@RunWith(RobolectricTestRunner.class)
public class ExpirationDateEditTextTest {
private ExpirationDateEditText mView;
@Before
public void setup() {
mView = Robolectric.setupActivity(TestActivity.class)
.findViewById(R.id.bt_card_form_expiration);
}
@Test
public void onDetachedFromWindow_handlesNullDialog() {
mView.onDetachedFromWindow();
}
@Test
public void onFocusChanged_handlesNullDialog() {
mView.onFocusChanged(true, View.FOCUS_DOWN, null);
}
@Test
public void typing_2_through_9_addsPrefix_0() {
for (int i = 2; i <= 9; i++) {
setText(String.valueOf(i));
assertTextIs("0" + i);
}
}
@Test
public void typing_0_or_1_doesntAddPrefix_0() {
setText("0");
assertTextIs("0");
setText("1");
assertTextIs("1");
}
@Test
public void canOnlyTypeNumeric() {
type('-');
assertTextIs("");
type('5', ':', '/', '-', 'h');
assertTextIs("05");
}
@Test
public void typingNumbersWithoutSlashWorks() {
type('1', '2', '1', '8');
assertTextIs("1218");
}
@Test
public void addsSlashForYou() {
setText("1218");
Spanned spanned = mView.getText();
SlashSpan[] appendSlashSpan = spanned.getSpans(0, mView.getText().toString().length(), SlashSpan.class);
assertEquals(1, appendSlashSpan.length);
}
@Test
public void maxLengthIsSix() {
type('1', '2', '2', '0', '0', '1', '5');
assertTextIs("122001");
}
@Test
public void getMonth() {
assertEquals("getMonth() should be \"\" if text is empty", "", mView.getMonth());
setText("1");
assertEquals("", mView.getMonth());
setText("01");
assertEquals("01", mView.getMonth());
setText("0218");
assertEquals("02", mView.getMonth());
setText("032018");
assertEquals("03", mView.getMonth());
}
@Test
public void getYear() {
assertEquals("getYear() should be \"\" if text is empty", "", mView.getYear());
setText("01");
assertEquals("", mView.getYear());
type('1');
assertEquals("getYear() doesn't return unformatted years", "", mView.getYear());
type('8');
assertEquals("18", mView.getYear());
setText("012018");
assertEquals("getYear() will return 4-digit years", "2018", mView.getYear());
}
@Test
public void isValid_returnsFalseForInvalidDate() {
assertFalse(mView.isValid());
}
@Test
public void isValid_returnsTrueForValidDate() {
setText("12" + getCurrent2DigitYear());
assertTrue(mView.isValid());
}
@Test
public void isValid_returnsTrueForInvalidDateWhenOptional() {
mView.setOptional(true);
assertTrue(mView.isValid());
}
@Test
public void getErrorMessage_returnsErrorMessageWhenEmpty() {
assertEquals(RuntimeEnvironment.application.getString(R.string.bt_expiration_required), mView.getErrorMessage());
}
@Test
public void getErrorMessage_returnsErrorMessageWhenNotEmpty() {
type('4');
assertEquals(RuntimeEnvironment.application.getString(R.string.bt_expiration_invalid), mView.getErrorMessage());
}
private ExpirationDateEditTextTest type(char... chars) {
Editable editable = mView.getText();
for (char c : chars) {
editable.append(c);
}
return this;
}
private ExpirationDateEditTextTest type(char c) {
mView.getText().append(c);
return this;
}
private void assertTextIs(String expected) {
assertEquals(expected, mView.getText().toString());
}
/** Clears the field and types the text as if it were new/untouched. */
private void setText(CharSequence seq) {
mView.setText("");
mView.setText(seq);
}
/** Gets the current years last two digits */
private String getCurrent2DigitYear() {
String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
return year.substring(2);
}
}
|
package cz.cvut.valespe.js.interpreter;
import java.lang.Object;
import cz.cvut.valespe.js.interpreter.model.*;
import cz.cvut.valespe.js.parser.JavaScriptParser;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class InterpreterVisitor implements cz.cvut.valespe.js.parser.JavaScriptVisitor {
private Memory memory;
private Scope scope;
private Scope thisScope;
public InterpreterVisitor(Memory memory, Scope scope, Scope thisScope) {
this.memory = memory;
this.scope = scope;
this.thisScope = thisScope;
}
@Override
public Object visitFile(@NotNull JavaScriptParser.FileContext ctx) {
Object result = null;
for (JavaScriptParser.ExpressionContext expressionContext : ctx.expression()) {
result = expressionContext.accept(this);
}
return result;
}
@Override
public Object visitMessageToInstanceExpression(@NotNull JavaScriptParser.MessageToInstanceExpressionContext ctx) {
return ctx.messageToInstance().accept(this);
}
@Override
public Object visitCallMethodOnInstance(@NotNull JavaScriptParser.CallMethodOnInstanceContext ctx) {
final JsObject instance = resolveSymbolToJsObject(ctx.ID(0).accept(this));
final String methodName = resolveSymbolName(ctx.ID(1).accept(this));
final List<Memory.Reference> paramRefs =
ctx.callParams() == null ?
Collections.<Memory.Reference>emptyList() :
(List<Memory.Reference>) ctx.callParams().accept(this);
return instance.invoke(methodName, paramRefs, scope, memory);
}
private JsObject resolveSymbolToJsObject(Object id) {
final String symbol = resolveSymbolName(id);
Memory.Reference instanceRed = scope.get(symbol);
return memory.getJsObject(instanceRed);
}
private String resolveSymbolName(Object nameRef) {
Symbol instanceName = (Symbol) memory.getJsObject((Memory.Reference) nameRef);
return (String) instanceName.value();
}
@Override
public Object visitGetPropertyOnInstance(@NotNull JavaScriptParser.GetPropertyOnInstanceContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID(0).accept(this);
Symbol instanceName = (Symbol) memory.getJsObject(nameRef);
Memory.Reference instanceRed = scope.get((String) instanceName.value());
JsObject instance = memory.getJsObject(instanceRed);
Memory.Reference methodRef = (Memory.Reference) ctx.ID(1).accept(this);
Symbol methodName = (Symbol) memory.getJsObject(methodRef);
return instance.invoke((String) methodName.value(), null, scope, memory);
}
@Override
public Object visitSetPropertyOnInstance(@NotNull JavaScriptParser.SetPropertyOnInstanceContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID(0).accept(this);
Symbol instanceName = (Symbol) memory.getJsObject(nameRef);
Memory.Reference instanceRed = scope.get((String) instanceName.value());
JsObject instance = memory.getJsObject(instanceRed);
Memory.Reference methodRef = (Memory.Reference) ctx.ID(1).accept(this);
Symbol methodName = (Symbol) memory.getJsObject(methodRef);
List<Memory.Reference> paramRefs = Arrays.asList((Memory.Reference) ctx.expression().accept(this));
return instance.invoke((String) methodName.value(), paramRefs, scope, memory);
}
@Override
public Object visitThisExpressionExpression(@NotNull JavaScriptParser.ThisExpressionExpressionContext ctx) {
return ctx.thisExpression().accept(this);
}
@Override
public Object visitThisCallMethod(@NotNull JavaScriptParser.ThisCallMethodContext ctx) {
Memory.Reference methodRef = (Memory.Reference) ctx.ID().accept(this);
Symbol methodName = (Symbol) memory.getJsObject(methodRef);
JsObject method = memory.getJsObject(thisScope.get((String) methodName.value()));
List<Memory.Reference> paramRefs = ctx.callParams() == null ? Collections.emptyList() : (List) ctx.callParams().accept(this);
return method.invoke(paramRefs, thisScope, memory);
}
@Override
public Object visitThisGetterExpression(@NotNull JavaScriptParser.ThisGetterExpressionContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
return thisScope.get((String) memory.getJsObject(nameRef).value());
}
@Override
public Object visitThisSetterExpression(@NotNull JavaScriptParser.ThisSetterExpressionContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
Memory.Reference resultRef = (Memory.Reference) ctx.expression().accept(this);
if (resultRef != null && memory.getJsObject(resultRef).isSymbol())
resultRef = scope.get((String) memory.getJsObject(resultRef).value());
thisScope.define((String) memory.getJsObject(nameRef).value());
thisScope.set((String) memory.getJsObject(nameRef).value(), resultRef);
return null;
}
@Override
public Object visitParenthesesExpression(@NotNull JavaScriptParser.ParenthesesExpressionContext ctx) {
return ctx.expression().accept(this);
}
@Override
public Object visitFunctionCallExpression(@NotNull JavaScriptParser.FunctionCallExpressionContext ctx) {
return ctx.functionCall().accept(this);
}
@Override
public Object visitFunctionCall(@NotNull JavaScriptParser.FunctionCallContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
Memory.Reference funRef = scope.get((String) memory.getJsObject(nameRef).value());
JsFunction function = (JsFunction) memory.getJsObject(funRef);
List<Memory.Reference> paramRefs = ctx.callParams() == null ? Collections.emptyList() : (List) ctx.callParams().accept(this);
return function.invoke(paramRefs, scope, memory);
}
@Override
public Object visitCallParams(@NotNull JavaScriptParser.CallParamsContext ctx) {
List<Memory.Reference> params = new ArrayList<Memory.Reference>();
for (JavaScriptParser.CallParamContext callParamContext : ctx.callParam()) {
params.add((Memory.Reference) callParamContext.accept(this));
}
return params;
}
@Override
public Object visitCallParam(@NotNull JavaScriptParser.CallParamContext ctx) {
if (ctx.ID() != null)
return ctx.ID().accept(this);
else if (ctx.INT() != null)
return ctx.INT().accept(this);
else if (ctx.STRING() != null)
return ctx.STRING().accept(this);
else
return null;
}
@Override
public Object visitCreateInstanceExpression(@NotNull JavaScriptParser.CreateInstanceExpressionContext ctx) {
return ctx.createInstance().accept(this);
}
@Override
public Object visitCreateInstance(@NotNull JavaScriptParser.CreateInstanceContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
Symbol functionName = (Symbol) memory.getJsObject(nameRef);
Memory.Reference constructorRef = scope.get((String) functionName.value());
final JsObject jsObject = memory.getJsObject(constructorRef);
if (jsObject.isJsFunction()) {
JsFunction constructor = (JsFunction) jsObject;
List<Memory.Reference> paramRefs = ctx.callParams() == null ? Collections.emptyList() : (List) ctx.callParams().accept(this);
return constructor.constructInstance(paramRefs, scope, memory);
}
return null;
}
@Override
public Object visitFunctionBody(@NotNull JavaScriptParser.FunctionBodyContext ctx) {
Object returnValue = null;
for (JavaScriptParser.ExpressionContext expressionContext : ctx.expression()) {
returnValue = expressionContext.accept(this);
}
return returnValue;
}
@Override
public Object visitPlusExpression(@NotNull JavaScriptParser.PlusExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "+");
}
@Override
public Object visitMinusExpression(@NotNull JavaScriptParser.MinusExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "-");
}
@Override
public Object visitMulExpression(@NotNull JavaScriptParser.MulExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "*");
}
@Override
public Object visitDivExpression(@NotNull JavaScriptParser.DivExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "/");
}
@Override
public Object visitModExpression(@NotNull JavaScriptParser.ModExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "%");
}
private Object invokeBinaryOperation(Memory.Reference firstRef, Memory.Reference secondRef, String operation) {
JsObject first = memory.getJsObject(firstRef);
JsObject second = memory.getJsObject(secondRef);
if (first.isSymbol())
first = memory.getJsObject(scope.get((String) first.value()));
if (second.isSymbol())
secondRef = scope.get((String) second.value());
return first.invoke(operation, Arrays.asList(secondRef), scope, memory);
}
@Override
public Object visitOrExpression(@NotNull JavaScriptParser.OrExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "||");
}
@Override
public Object visitAndExpression(@NotNull JavaScriptParser.AndExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "&&");
}
@Override
public Object visitEqualsExpression(@NotNull JavaScriptParser.EqualsExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "==");
}
@Override
public Object visitCompareExpression(@NotNull JavaScriptParser.CompareExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, ctx.COMPARE_OPERATORS().getText());
}
@Override
public Object visitNotExpression(@NotNull JavaScriptParser.NotExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression().accept(this);
JsObject first = memory.getJsObject(firstRef);
if (first.isSymbol())
first = memory.getJsObject(scope.get((String) first.value()));
return first.invoke("!", Collections.<Memory.Reference>emptyList(), scope, memory);
}
@Override
public Object visitUnaryMinusExpression(@NotNull JavaScriptParser.UnaryMinusExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression().accept(this);
JsObject first = memory.getJsObject(firstRef);
if (first.isSymbol())
first = memory.getJsObject(scope.get((String) first.value()));
return first.invoke("-", Collections.<Memory.Reference>emptyList(), scope, memory);
}
@Override
public Object visitFalse(@NotNull JavaScriptParser.FalseContext ctx) {
return ctx.FALSE().accept(this);
}
@Override
public Object visitTrue(@NotNull JavaScriptParser.TrueContext ctx) {
return ctx.TRUE().accept(this);
}
@Override
public Object visitAssignmentExpressionExpression(@NotNull JavaScriptParser.AssignmentExpressionExpressionContext ctx) {
ctx.assignmentExpression().accept(this);
return null;
}
@Override
public Object visitVarAssignment(@NotNull JavaScriptParser.VarAssignmentContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
Memory.Reference resultRef = (Memory.Reference) ctx.expression().accept(this);
if (resultRef != null && memory.getJsObject(resultRef).isSymbol())
resultRef = scope.get((String) memory.getJsObject(resultRef).value());
scope.set((String) memory.getJsObject(nameRef).value(), resultRef);
return null;
}
@Override
public Object visitAssignment(@NotNull JavaScriptParser.AssignmentContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
Memory.Reference resultRef = (Memory.Reference) ctx.expression().accept(this);
if (resultRef != null && memory.getJsObject(resultRef).isSymbol())
resultRef = scope.get((String) memory.getJsObject(resultRef).value());
scope.set((String) memory.getJsObject(nameRef).value(), resultRef);
return null;
}
@Override
public Object visitPrototypeAssignmentExpressionExpression(@NotNull JavaScriptParser.PrototypeAssignmentExpressionExpressionContext ctx) {
ctx.prototypeAssignmentExpression().accept(this);
return null;
}
@Override
public Object visitPrototypeAssignment(@NotNull JavaScriptParser.PrototypeAssignmentContext ctx) {
final Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
final Memory.Reference objectRef = scope.get((String) memory.getJsObject(nameRef).value());
final JsObject jsObject = memory.getJsObject(objectRef);
jsObject.setPrototype((Memory.Reference) ctx.expression().accept(this));
return null;
}
@Override
public Object visitAnonymousFunctionExpression(@NotNull JavaScriptParser.AnonymousFunctionExpressionContext ctx) {
return ctx.anonymousFunction().accept(new DefinitionCollectingVisitor(memory, scope));
}
@Override
public Object visitAnonymousFunction(@NotNull JavaScriptParser.AnonymousFunctionContext ctx) {
JsFunction function = new JsFunction(null, getFunctionParams(ctx.functionParameters()), ctx.functionBody(), scope);
return memory.storeJsObject(function);
}
private List getFunctionParams(JavaScriptParser.FunctionParametersContext functionParameters) {
return functionParameters == null ? new ArrayList() : (List) functionParameters.accept(this);
}
@Override
public Object visitFunctionParameters(@NotNull JavaScriptParser.FunctionParametersContext ctx) {
List<Memory.Reference> params = new ArrayList<Memory.Reference>();
if (ctx.functionParameter() != null) {
for (JavaScriptParser.FunctionParameterContext param : ctx.functionParameter()) {
params.add((Memory.Reference) param.accept(this));
}
}
return params;
}
@Override
public Object visitFunctionName(@NotNull JavaScriptParser.FunctionNameContext ctx) {
return ctx.ID().accept(this);
}
@Override
public Object visitFunctionParameter(@NotNull JavaScriptParser.FunctionParameterContext ctx) {
return ctx.ID().accept(this);
}
@Override
public Object visitArray(@NotNull JavaScriptParser.ArrayContext ctx) {
return ctx.createArray().accept(this);
}
@Override
public Object visitArrayAssignmentExpression(@NotNull JavaScriptParser.ArrayAssignmentExpressionContext ctx) {
return ctx.arrayAssignment().accept(this);
}
@Override
public Object visitArrayAccessExpression(@NotNull JavaScriptParser.ArrayAccessExpressionContext ctx) {
return ctx.arrayAccess().accept(this);
}
@Override
public Object visitCreateArray(@NotNull JavaScriptParser.CreateArrayContext ctx) {
List<Memory.Reference> refs = (List) ctx.callParams().accept(this);
List<Memory.Reference> arrayRefs = new ArrayList<Memory.Reference>(refs.size());
for (Memory.Reference ref : refs) {
final JsObject jsObject = memory.getJsObject(ref);
if (jsObject.isSymbol())
arrayRefs.add(scope.get((String) jsObject.value()));
else
arrayRefs.add(ref);
}
return memory.storeJsObject(new JsArray(arrayRefs));
}
@Override
public Object visitArrayAccess(@NotNull JavaScriptParser.ArrayAccessContext ctx) {
Memory.Reference idRef = (Memory.Reference) ctx.ID().accept(this);
JsObject id = memory.getJsObject(idRef);
Memory.Reference arrayRef = scope.get((String) id.value());
JsObject array = memory.getJsObject(arrayRef);
Memory.Reference indexRef = (Memory.Reference) ctx.INT().accept(this);
JsObject index = memory.getJsObject(indexRef);
if (array.isJsArray()) {
return ((JsArray) array).get((Integer) index.value());
}
throw new TypeError(id.value() + " is not array.");
}
@Override
public Object visitArrayAssignment(@NotNull JavaScriptParser.ArrayAssignmentContext ctx) {
Memory.Reference idRef = (Memory.Reference) ctx.ID().accept(this);
JsObject id = memory.getJsObject(idRef);
Memory.Reference arrayRef = scope.get((String) id.value());
JsObject array = memory.getJsObject(arrayRef);
Memory.Reference indexRef = (Memory.Reference) ctx.INT().accept(this);
JsObject index = memory.getJsObject(indexRef);
if (array.isJsArray()) {
((JsArray) array).set((Integer) index.value(), (Memory.Reference) ctx.expression().accept(this));
return null;
}
throw new TypeError(id.value() + " is not array.");
}
@Override
public Object visitInt(@NotNull JavaScriptParser.IntContext ctx) {
return ctx.INT().accept(this);
}
@Override
public Object visitId(@NotNull JavaScriptParser.IdContext ctx) {
return ctx.ID().accept(this);
}
@Override
public Object visitString(@NotNull JavaScriptParser.StringContext ctx) {
return ctx.STRING().accept(this);
}
@Override
public Object visitIfExpression(@NotNull JavaScriptParser.IfExpressionContext ctx) {
return ctx.ifStatement().accept(this);
}
@Override
public Object visitIfStatement(@NotNull JavaScriptParser.IfStatementContext ctx) {
Memory.Reference conditionRef = (Memory.Reference) ctx.expression().accept(this);
JsObject condition = memory.getJsObject(conditionRef);
if (condition.isSymbol())
condition = memory.getJsObject(scope.get((String) condition.value()));
if (!condition.isJsBoolean())
throw new TypeError("Not boolean expression");
if ((Boolean) condition.value()) {
ctx.functionBody(0).accept(this);
} else {
ctx.functionBody(1).accept(this);
}
return null;
}
@Override
public Object visitWhileExpression(@NotNull JavaScriptParser.WhileExpressionContext ctx) {
return ctx.whileStatement().accept(this);
}
@Override
public Object visitWhileStatement(@NotNull JavaScriptParser.WhileStatementContext ctx) {
Memory.Reference conditionRef = (Memory.Reference) ctx.expression().accept(this);
JsObject condition = memory.getJsObject(conditionRef);
if (condition.isSymbol())
condition = memory.getJsObject(scope.get((String) condition.value()));
if (!condition.isJsBoolean())
throw new TypeError("Not boolean expression");
while ((Boolean) condition.value()) {
ctx.functionBody().accept(this);
conditionRef = (Memory.Reference) ctx.expression().accept(this);
condition = memory.getJsObject(conditionRef);
if (condition.isSymbol())
condition = memory.getJsObject(scope.get((String) condition.value()));
}
return null;
}
@Override
public Memory.Reference visitTerminal(@NotNull TerminalNode node) {
JsObject terminal = null;
switch (node.getSymbol().getType()) {
case JavaScriptParser.INT:
terminal = new JsInt(Integer.parseInt(node.getText()));
break;
case JavaScriptParser.ID:
terminal = new Symbol(node.getText());
break;
case JavaScriptParser.STRING:
terminal = new JsString(node.getText().replace("\"", ""));
break;
case JavaScriptParser.TRUE:
terminal = new JsBoolean(Boolean.TRUE);
break;
case JavaScriptParser.FALSE:
terminal = new JsBoolean(Boolean.FALSE);
break;
default: throw new IllegalStateException("Unknown terminal node");
}
return memory.storeJsObject(terminal);
}
@Override
public Object visitVarDeclaration(@NotNull JavaScriptParser.VarDeclarationContext ctx) {
return null;
}
@Override
public Object visitFunctionDeclaration(@NotNull JavaScriptParser.FunctionDeclarationContext ctx) {
return null;
}
@Override
public Object visitErrorNode(@NotNull ErrorNode node) {
return null;
}
@Override
public Object visit(@NotNull ParseTree tree) {
return null;
}
@Override
public Object visitChildren(@NotNull RuleNode node) {
return null;
}
}
|
package cz.cvut.valespe.js.interpreter;
import java.lang.Object;
import cz.cvut.valespe.js.interpreter.model.*;
import cz.cvut.valespe.js.parser.JavaScriptParser;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class InterpreterVisitor implements cz.cvut.valespe.js.parser.JavaScriptVisitor {
private Memory memory;
private Scope scope;
private Scope thisScope;
public InterpreterVisitor(Memory memory, Scope scope, Scope thisScope) {
this.memory = memory;
this.scope = scope;
this.thisScope = thisScope;
}
@Override
public Object visitFile(@NotNull JavaScriptParser.FileContext ctx) {
Object result = null;
for (JavaScriptParser.ExpressionContext expressionContext : ctx.expression()) {
result = expressionContext.accept(this);
}
return result;
}
@Override
public Object visitMessageToInstanceExpression(@NotNull JavaScriptParser.MessageToInstanceExpressionContext ctx) {
return ctx.messageToInstance().accept(this);
}
@Override
public Object visitCallMethodOnInstance(@NotNull JavaScriptParser.CallMethodOnInstanceContext ctx) {
final JsObject instance = resolveSymbolToJsObject(ctx.ID(0).accept(this));
final String methodName = resolveSymbolName(ctx.ID(1).accept(this));
final List<Memory.Reference> paramRefs = ctx.callParams() == null ?
Collections.<Memory.Reference>emptyList() :
(List<Memory.Reference>) ctx.callParams().accept(this);
return instance.invoke(methodName, paramRefs, scope, memory);
}
@Override
public Object visitGetPropertyOnInstance(@NotNull JavaScriptParser.GetPropertyOnInstanceContext ctx) {
JsObject instance = resolveSymbolToJsObject(ctx.ID(0).accept(this));
String methodName = resolveSymbolName(ctx.ID(1).accept(this));
return instance.invoke(methodName, null, scope, memory);
}
@Override
public Object visitSetPropertyOnInstance(@NotNull JavaScriptParser.SetPropertyOnInstanceContext ctx) {
JsObject instance = resolveSymbolToJsObject(ctx.ID(0).accept(this));
String methodName = resolveSymbolName(ctx.ID(1).accept(this));
List<Memory.Reference> paramRefs = Arrays.asList((Memory.Reference) ctx.expression().accept(this));
return instance.invoke(methodName, paramRefs, scope, memory);
}
@Override
public Object visitThisExpressionExpression(@NotNull JavaScriptParser.ThisExpressionExpressionContext ctx) {
return ctx.thisExpression().accept(this);
}
@Override
public Object visitThisCallMethod(@NotNull JavaScriptParser.ThisCallMethodContext ctx) {
JsObject method = resolveSymbolToJsObjectFromThisScope(ctx.ID().accept(this));
List<Memory.Reference> paramRefs = ctx.callParams() == null ?
Collections.<Memory.Reference>emptyList() :
(List<Memory.Reference>) ctx.callParams().accept(this);
return method.invoke(paramRefs, thisScope, memory);
}
@Override
public Object visitThisGetterExpression(@NotNull JavaScriptParser.ThisGetterExpressionContext ctx) {
return thisScope.get(resolveSymbolName(ctx.ID().accept(this)));
}
@Override
public Object visitThisSetterExpression(@NotNull JavaScriptParser.ThisSetterExpressionContext ctx) {
String propertyName = resolveSymbolName(ctx.ID().accept(this));
Memory.Reference resultRef = getReferenceOfJsObject(ctx.expression().accept(this));
thisScope.define(propertyName);
thisScope.set(propertyName, resultRef);
return null;
}
@Override
public Object visitParenthesesExpression(@NotNull JavaScriptParser.ParenthesesExpressionContext ctx) {
return ctx.expression().accept(this);
}
@Override
public Object visitFunctionCallExpression(@NotNull JavaScriptParser.FunctionCallExpressionContext ctx) {
return ctx.functionCall().accept(this);
}
@Override
public Object visitFunctionCall(@NotNull JavaScriptParser.FunctionCallContext ctx) {
JsObject function = resolveSymbolToJsObject(ctx.ID().accept(this));
List<Memory.Reference> paramRefs = ctx.callParams() == null ?
Collections.<Memory.Reference>emptyList() :
(List<Memory.Reference>) ctx.callParams().accept(this);
return function.invoke(paramRefs, scope, memory);
}
@Override
public Object visitCallParams(@NotNull JavaScriptParser.CallParamsContext ctx) {
List<Memory.Reference> params = new ArrayList<Memory.Reference>();
for (JavaScriptParser.CallParamContext callParamContext : ctx.callParam()) {
params.add((Memory.Reference) callParamContext.accept(this));
}
return params;
}
@Override
public Object visitCallParam(@NotNull JavaScriptParser.CallParamContext ctx) {
if (ctx.ID() != null)
return ctx.ID().accept(this);
else if (ctx.INT() != null)
return ctx.INT().accept(this);
else if (ctx.STRING() != null)
return ctx.STRING().accept(this);
else
return null;
}
@Override
public Object visitCreateInstanceExpression(@NotNull JavaScriptParser.CreateInstanceExpressionContext ctx) {
return ctx.createInstance().accept(this);
}
@Override
public Object visitCreateInstance(@NotNull JavaScriptParser.CreateInstanceContext ctx) {
final JsObject jsObject = resolveSymbolToJsObject(ctx.ID().accept(this));
if (jsObject.isJsFunction()) {
JsFunction constructor = (JsFunction) jsObject;
List<Memory.Reference> paramRefs = ctx.callParams() == null ?
Collections.<Memory.Reference>emptyList() :
(List<Memory.Reference>) ctx.callParams().accept(this);
return constructor.constructInstance(paramRefs, scope, memory);
}
throw new TypeError(resolveSymbolName(ctx.ID().accept(this)) + " is not function");
}
@Override
public Object visitFunctionBody(@NotNull JavaScriptParser.FunctionBodyContext ctx) {
Object returnValue = null;
for (JavaScriptParser.ExpressionContext expressionContext : ctx.expression()) {
returnValue = expressionContext.accept(this);
}
return returnValue;
}
@Override
public Object visitPlusExpression(@NotNull JavaScriptParser.PlusExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "+");
}
@Override
public Object visitMinusExpression(@NotNull JavaScriptParser.MinusExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "-");
}
@Override
public Object visitMulExpression(@NotNull JavaScriptParser.MulExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "*");
}
@Override
public Object visitDivExpression(@NotNull JavaScriptParser.DivExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "/");
}
@Override
public Object visitModExpression(@NotNull JavaScriptParser.ModExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "%");
}
private Object invokeBinaryOperation(Memory.Reference firstRef, Memory.Reference secondRef, String operation) {
JsObject first = ensureObject(firstRef);
JsObject second = memory.getJsObject(secondRef);
if (second.isSymbol())
secondRef = scope.get((String) second.value());
return first.invoke(operation, Arrays.asList(secondRef), scope, memory);
}
@Override
public Object visitOrExpression(@NotNull JavaScriptParser.OrExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "||");
}
@Override
public Object visitAndExpression(@NotNull JavaScriptParser.AndExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "&&");
}
@Override
public Object visitEqualsExpression(@NotNull JavaScriptParser.EqualsExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, "==");
}
@Override
public Object visitCompareExpression(@NotNull JavaScriptParser.CompareExpressionContext ctx) {
Memory.Reference firstRef = (Memory.Reference) ctx.expression(0).accept(this);
Memory.Reference secondRef = (Memory.Reference) ctx.expression(1).accept(this);
return invokeBinaryOperation(firstRef, secondRef, ctx.COMPARE_OPERATORS().getText());
}
@Override
public Object visitNotExpression(@NotNull JavaScriptParser.NotExpressionContext ctx) {
JsObject first = ensureObject(ctx.expression().accept(this));
return first.invoke("!", Collections.<Memory.Reference>emptyList(), scope, memory);
}
@Override
public Object visitUnaryMinusExpression(@NotNull JavaScriptParser.UnaryMinusExpressionContext ctx) {
JsObject first = ensureObject(ctx.expression().accept(this));
return first.invoke("-", Collections.<Memory.Reference>emptyList(), scope, memory);
}
@Override
public Object visitFalse(@NotNull JavaScriptParser.FalseContext ctx) {
return ctx.FALSE().accept(this);
}
@Override
public Object visitTrue(@NotNull JavaScriptParser.TrueContext ctx) {
return ctx.TRUE().accept(this);
}
@Override
public Object visitAssignmentExpressionExpression(@NotNull JavaScriptParser.AssignmentExpressionExpressionContext ctx) {
ctx.assignmentExpression().accept(this);
return null;
}
@Override
public Object visitVarAssignment(@NotNull JavaScriptParser.VarAssignmentContext ctx) {
String name = resolveSymbolName(ctx.ID().accept(this));
Memory.Reference resultRef = getReferenceOfJsObject(ctx.expression().accept(this));
scope.set(name, resultRef);
return null;
}
private JsObject ensureObject(Object ref) {
JsObject object = memory.getJsObject((Memory.Reference) ref);
if (object.isSymbol())
object = memory.getJsObject(scope.get((String) object.value()));
return object;
}
private Memory.Reference getReferenceOfJsObject(Object ref) {
Memory.Reference resultRef = (Memory.Reference) ref;
if (resultRef != null && memory.getJsObject(resultRef).isSymbol())
resultRef = scope.get((String) memory.getJsObject(resultRef).value());
return resultRef;
}
private JsObject resolveSymbolToJsObjectFromThisScope(Object id) {
return resolveSymbolToJsObjectFromScope(id, thisScope);
}
private JsObject resolveSymbolToJsObject(Object id) {
return resolveSymbolToJsObjectFromScope(id, scope);
}
private JsObject resolveSymbolToJsObjectFromScope(Object id, Scope scopeToUse) {
final String symbol = resolveSymbolName(id);
final Memory.Reference instanceRed = scopeToUse.get(symbol);
return memory.getJsObject(instanceRed);
}
private String resolveSymbolName(Object nameRef) {
final Symbol instanceName = (Symbol) memory.getJsObject((Memory.Reference) nameRef);
return (String) instanceName.value();
}
@Override
public Object visitAssignment(@NotNull JavaScriptParser.AssignmentContext ctx) {
Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
Memory.Reference resultRef = (Memory.Reference) ctx.expression().accept(this);
if (resultRef != null && memory.getJsObject(resultRef).isSymbol())
resultRef = scope.get((String) memory.getJsObject(resultRef).value());
scope.set((String) memory.getJsObject(nameRef).value(), resultRef);
return null;
}
@Override
public Object visitPrototypeAssignmentExpressionExpression(@NotNull JavaScriptParser.PrototypeAssignmentExpressionExpressionContext ctx) {
ctx.prototypeAssignmentExpression().accept(this);
return null;
}
@Override
public Object visitPrototypeAssignment(@NotNull JavaScriptParser.PrototypeAssignmentContext ctx) {
final Memory.Reference nameRef = (Memory.Reference) ctx.ID().accept(this);
final Memory.Reference objectRef = scope.get((String) memory.getJsObject(nameRef).value());
final JsObject jsObject = memory.getJsObject(objectRef);
jsObject.setPrototype((Memory.Reference) ctx.expression().accept(this));
return null;
}
@Override
public Object visitAnonymousFunctionExpression(@NotNull JavaScriptParser.AnonymousFunctionExpressionContext ctx) {
return ctx.anonymousFunction().accept(new DefinitionCollectingVisitor(memory, scope));
}
@Override
public Object visitAnonymousFunction(@NotNull JavaScriptParser.AnonymousFunctionContext ctx) {
JsFunction function = new JsFunction(null, getFunctionParams(ctx.functionParameters()), ctx.functionBody(), scope);
return memory.storeJsObject(function);
}
private List getFunctionParams(JavaScriptParser.FunctionParametersContext functionParameters) {
return functionParameters == null ? new ArrayList() : (List) functionParameters.accept(this);
}
@Override
public Object visitFunctionParameters(@NotNull JavaScriptParser.FunctionParametersContext ctx) {
List<Memory.Reference> params = new ArrayList<Memory.Reference>();
if (ctx.functionParameter() != null) {
for (JavaScriptParser.FunctionParameterContext param : ctx.functionParameter()) {
params.add((Memory.Reference) param.accept(this));
}
}
return params;
}
@Override
public Object visitFunctionName(@NotNull JavaScriptParser.FunctionNameContext ctx) {
return ctx.ID().accept(this);
}
@Override
public Object visitFunctionParameter(@NotNull JavaScriptParser.FunctionParameterContext ctx) {
return ctx.ID().accept(this);
}
@Override
public Object visitArray(@NotNull JavaScriptParser.ArrayContext ctx) {
return ctx.createArray().accept(this);
}
@Override
public Object visitArrayAssignmentExpression(@NotNull JavaScriptParser.ArrayAssignmentExpressionContext ctx) {
return ctx.arrayAssignment().accept(this);
}
@Override
public Object visitArrayAccessExpression(@NotNull JavaScriptParser.ArrayAccessExpressionContext ctx) {
return ctx.arrayAccess().accept(this);
}
@Override
public Object visitCreateArray(@NotNull JavaScriptParser.CreateArrayContext ctx) {
List<Memory.Reference> refs = (List) ctx.callParams().accept(this);
List<Memory.Reference> arrayRefs = new ArrayList<Memory.Reference>(refs.size());
for (Memory.Reference ref : refs) {
final JsObject jsObject = memory.getJsObject(ref);
if (jsObject.isSymbol())
arrayRefs.add(scope.get((String) jsObject.value()));
else
arrayRefs.add(ref);
}
return memory.storeJsObject(new JsArray(arrayRefs));
}
@Override
public Object visitArrayAccess(@NotNull JavaScriptParser.ArrayAccessContext ctx) {
Memory.Reference idRef = (Memory.Reference) ctx.ID().accept(this);
JsObject id = memory.getJsObject(idRef);
Memory.Reference arrayRef = scope.get((String) id.value());
JsObject array = memory.getJsObject(arrayRef);
Memory.Reference indexRef = (Memory.Reference) ctx.INT().accept(this);
JsObject index = memory.getJsObject(indexRef);
if (array.isJsArray()) {
return ((JsArray) array).get((Integer) index.value());
}
throw new TypeError(id.value() + " is not array.");
}
@Override
public Object visitArrayAssignment(@NotNull JavaScriptParser.ArrayAssignmentContext ctx) {
Memory.Reference idRef = (Memory.Reference) ctx.ID().accept(this);
JsObject id = memory.getJsObject(idRef);
Memory.Reference arrayRef = scope.get((String) id.value());
JsObject array = memory.getJsObject(arrayRef);
Memory.Reference indexRef = (Memory.Reference) ctx.INT().accept(this);
JsObject index = memory.getJsObject(indexRef);
if (array.isJsArray()) {
((JsArray) array).set((Integer) index.value(), (Memory.Reference) ctx.expression().accept(this));
return null;
}
throw new TypeError(id.value() + " is not array.");
}
@Override
public Object visitInt(@NotNull JavaScriptParser.IntContext ctx) {
return ctx.INT().accept(this);
}
@Override
public Object visitId(@NotNull JavaScriptParser.IdContext ctx) {
return ctx.ID().accept(this);
}
@Override
public Object visitString(@NotNull JavaScriptParser.StringContext ctx) {
return ctx.STRING().accept(this);
}
@Override
public Object visitIfExpression(@NotNull JavaScriptParser.IfExpressionContext ctx) {
return ctx.ifStatement().accept(this);
}
@Override
public Object visitIfStatement(@NotNull JavaScriptParser.IfStatementContext ctx) {
Memory.Reference conditionRef = (Memory.Reference) ctx.expression().accept(this);
JsObject condition = memory.getJsObject(conditionRef);
if (condition.isSymbol())
condition = memory.getJsObject(scope.get((String) condition.value()));
if (!condition.isJsBoolean())
throw new TypeError("Not boolean expression");
if ((Boolean) condition.value()) {
ctx.functionBody(0).accept(this);
} else {
ctx.functionBody(1).accept(this);
}
return null;
}
@Override
public Object visitWhileExpression(@NotNull JavaScriptParser.WhileExpressionContext ctx) {
return ctx.whileStatement().accept(this);
}
@Override
public Object visitWhileStatement(@NotNull JavaScriptParser.WhileStatementContext ctx) {
Memory.Reference conditionRef = (Memory.Reference) ctx.expression().accept(this);
JsObject condition = memory.getJsObject(conditionRef);
if (condition.isSymbol())
condition = memory.getJsObject(scope.get((String) condition.value()));
if (!condition.isJsBoolean())
throw new TypeError("Not boolean expression");
while ((Boolean) condition.value()) {
ctx.functionBody().accept(this);
conditionRef = (Memory.Reference) ctx.expression().accept(this);
condition = memory.getJsObject(conditionRef);
if (condition.isSymbol())
condition = memory.getJsObject(scope.get((String) condition.value()));
}
return null;
}
@Override
public Memory.Reference visitTerminal(@NotNull TerminalNode node) {
JsObject terminal = null;
switch (node.getSymbol().getType()) {
case JavaScriptParser.INT:
terminal = new JsInt(Integer.parseInt(node.getText()));
break;
case JavaScriptParser.ID:
terminal = new Symbol(node.getText());
break;
case JavaScriptParser.STRING:
terminal = new JsString(node.getText().replace("\"", ""));
break;
case JavaScriptParser.TRUE:
terminal = new JsBoolean(Boolean.TRUE);
break;
case JavaScriptParser.FALSE:
terminal = new JsBoolean(Boolean.FALSE);
break;
default: throw new IllegalStateException("Unknown terminal node");
}
return memory.storeJsObject(terminal);
}
@Override
public Object visitVarDeclaration(@NotNull JavaScriptParser.VarDeclarationContext ctx) {
return null;
}
@Override
public Object visitFunctionDeclaration(@NotNull JavaScriptParser.FunctionDeclarationContext ctx) {
return null;
}
@Override
public Object visitErrorNode(@NotNull ErrorNode node) {
return null;
}
@Override
public Object visit(@NotNull ParseTree tree) {
return null;
}
@Override
public Object visitChildren(@NotNull RuleNode node) {
return null;
}
}
|
package de.rwth.dbis.layers.lapps.authenticate;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import javax.inject.Singleton;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.http.HTTPRequest;
import com.nimbusds.oauth2.sdk.http.HTTPRequest.Method;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse;
import com.nimbusds.openid.connect.sdk.UserInfoResponse;
import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;
import de.rwth.dbis.layers.lapps.domain.Facade;
import de.rwth.dbis.layers.lapps.entity.App;
import de.rwth.dbis.layers.lapps.entity.Comment;
import de.rwth.dbis.layers.lapps.entity.User;
import de.rwth.dbis.layers.lapps.exception.OIDCException;
/**
* AuthenticationProvider to authenticate an OpenIdToken.
*
*/
@Singleton
public class OIDCAuthentication {
private static final String OPEN_ID_PROVIDER = "https://api.learning-layers.eu/o/oauth2";
private static final String OPEN_ID_PROVIDER_CONFIGURATION_URI = OPEN_ID_PROVIDER.trim()
+ "/.well-known/openid-configuration";
// only for testing, will always be valid
public static final String OPEN_ID_TEST_TOKEN = "test_token";
public static final Long OPEN_ID_USER_ID = -1L;
private static Facade facade = new Facade();
/**
* Returns true, if the given token belongs to a user with at least(!) "user" rights (always true)
*
* @param openIdToken
* @return true, if the token belongs to a user
*/
public static boolean isUser(String openIdToken) {
try {
User user = authenticate(openIdToken);
if (user.getRole() >= User.USER) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Returns true, if the given token belongs to a user with exactly(!) "pending developer" rights.
*
* @param openIdToken
* @return true, if the user is a pending developer
*/
public static boolean isPendingDeveloper(String openIdToken) {
try {
User user = authenticate(openIdToken);
if (user.getRole() == User.PENDING_DEVELOPER) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Returns true, if the given token belongs to a user with at least(!) "developer" rights.
*
* @param openIdToken
* @return true, if the user is developer or admin
*/
public static boolean isDeveloper(String openIdToken) {
try {
User user = authenticate(openIdToken);
if (user.getRole() >= User.DEVELOPER) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Returns true, if the given token belongs to a user with "admin" rights.
*
* @param openIdToken the token
* @return true, if the user is an administrator
*/
public static boolean isAdmin(String openIdToken) {
try {
User user = authenticate(openIdToken);
if (user.getRole() == User.ADMIN) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Returns true, if the given token belongs to a user that has created the app with the given id.
*
* @param app The app
* @param openIdToken
* @return true, if the user is creator of the app
*/
public static boolean isCreatorOfApp(App app, String openIdToken) {
// no app provided
if (app == null) {
return false;
}
try {
User user = authenticate(openIdToken);
if (app.getCreator().getOidcId().equals(user.getOidcId())) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Returns true, if the given token belongs to a user with the given id.
*
* @param oidcId the oidcId of the user
* @param openIdToken
* @return true, if oidcId and openIdToken match
*/
public static boolean isSameUser(Long oidcId, String openIdToken) {
try {
User user = authenticate(openIdToken);
if (user.getOidcId().equals(oidcId)) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Returns true, if the given token belongs to the owner of the comment.
*
* @param openIdToken
* @param Comment entity
* @return true, if userId and comment.getUser.getId match
*/
public static boolean isCommentOwner(String openIdToken, Comment comment) {
// no token provided
if (openIdToken == null) {
return false;
}
try {
User user = authenticate(openIdToken);
if (comment.getUser().getOidcId().equals(user.getOidcId())) {
return true;
} else {
return false;
}
} catch (OIDCException e) {
return false;
}
}
/**
* Tries to authenticate a user for a given OpenIdToken. If the user is not yet registered, it
* will register him to the LAPPS backend. If only a role check is needed, better use the other
* methods of this class.
*
* @param openIdToken
*
* @return the user
* @throws OIDCException an exception thrown for all Open Id Connect issues
*/
public static User authenticate(String openIdToken) throws OIDCException {
// no token provided
if (openIdToken == null) {
throw new OIDCException("No token was provided");
}
// Return default OIDC user for test token
if (openIdToken.equals(OPEN_ID_TEST_TOKEN)) {
User superUser;
List<User> entities = facade.findByParam(User.class, "oidcId", OPEN_ID_USER_ID);
if (entities.isEmpty()) {
// Generate user that maps to open id test user
superUser =
new User(OIDCAuthentication.OPEN_ID_USER_ID, "OpenId Test User", "test@mail.com",
"persDescr", "someWeb.com", User.ADMIN);
superUser = facade.save(superUser);
} else {
superUser = entities.get(0);
}
return superUser;
}
// JSON initialization stuff
ObjectMapper mapper = new ObjectMapper();
JsonNode serverConfig;
// get provider configuration
URL providerConfigurationUri;
try {
providerConfigurationUri = new URL(OPEN_ID_PROVIDER_CONFIGURATION_URI);
} catch (MalformedURLException e) {
throw new OIDCException("Exception during Open Id Connect authentication occured: "
+ e.getMessage());
}
HTTPRequest providerConfigRequest = new HTTPRequest(Method.GET, providerConfigurationUri);
// parse JSON result from configuration request
try {
String configStr = providerConfigRequest.send().getContent();
serverConfig = mapper.readTree(configStr);
} catch (Exception e) {
throw new OIDCException("Exception during Open Id Connect authentication occured: "
+ e.getMessage());
}
// send access token, get user info
HTTPRequest httpRequest;
HTTPResponse httpResponse;
try {
URI userinfoEndpointUri = new URI(serverConfig.get("userinfo_endpoint").textValue());
httpRequest = new HTTPRequest(Method.GET, userinfoEndpointUri.toURL());
httpRequest.setAuthorization("Bearer " + openIdToken);
httpResponse = httpRequest.send();
} catch (IOException | URISyntaxException e) {
throw new OIDCException("Exception during Open Id Connect authentication occured: "
+ e.getMessage());
}
// ..and process the response
UserInfoResponse userInfoResponse;
try {
userInfoResponse = UserInfoResponse.parse(httpResponse);
} catch (ParseException e) {
throw new OIDCException("Exception during Open Id Authentication occured: " + e.getMessage());
}
// request failed (unauthorized)
if (userInfoResponse instanceof UserInfoErrorResponse) {
UserInfoErrorResponse uier = (UserInfoErrorResponse) userInfoResponse;
throw new OIDCException("Exception during Open Id Authentication occured: "
+ uier.getClass().toString());
}
// successful, now get the user info and start extracting content
UserInfo userInfo = ((UserInfoSuccessResponse) userInfoResponse).getUserInfo();
long sub = Long.parseLong(userInfo.getSubject().toString());
String mail = userInfo.getEmail().toString();
String userName = userInfo.getName();
// search for existing user
List<User> entities = facade.findByParam(User.class, "oidcId", sub);
// more than one means something bad happened, one means user is already known..
if (entities.size() > 1)
throw new OIDCException("Exception during Open Id Authentication occured.");
else if (entities.size() == 1) {
User user = entities.get(0);
// quick check, if mail or user name of OIDC server account differs (has changed) to our
// database entry; if so, update our user
if (!user.getEmail().equals(mail) || !user.getUsername().equals(userName)) {
user.setEmail(mail);
user.setUsername(userName);
user = facade.save(user);
}
return user;
}
// user is unknown, has to be created
return createNewUser(sub, mail, userName);
}
/**
* Creates a new user for a given oidc_id and mail.
*
* @param oidc_id the "subject" identifier of the open id connect authentication
* @param mail a user email
* @param userName the name of the user to be created
*
* @return the user
*/
private static User createNewUser(long oidc_id, String mail, String userName) {
User user = new User(oidc_id, userName, mail, null, null, User.USER);
user = facade.save(user);
return user;
}
}
|
package com.cleytongoncalves.popmovies.ui.mainscreen;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import com.cleytongoncalves.popmovies.BuildConfig;
import com.cleytongoncalves.popmovies.R;
import com.cleytongoncalves.popmovies.ui.detailscreen.DetailActivity;
import com.cleytongoncalves.popmovies.ui.models.Movie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnItemClick;
public class MainFragment extends Fragment {
private GridViewAdapter mMoviesAdapter;
private String mSortBy = MovieDataFetcher.SORT_POPULARITY;
@Bind(R.id.grid_view) GridView gridView;
public MainFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mMoviesAdapter = new GridViewAdapter(getActivity(), R.layout.grid_item_view, new
ArrayList<Movie>());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, rootView);
gridView.setAdapter(mMoviesAdapter);
return rootView;
}
@OnItemClick(R.id.grid_view)
protected void onItemClick(int position) {
Movie movieClicked = (Movie) mMoviesAdapter.getItem(position);
Intent intent = new Intent(getActivity(), DetailActivity.class)
.putExtra("movie", movieClicked);
startActivity(intent);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void onStart() {
super.onStart();
updateMovies();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_mainfragment, menu);
MenuItem menu_sort_popularity = menu.findItem(R.id.menu_sort_popularity);
MenuItem menu_sort_rating = menu.findItem(R.id.menu_sort_rating);
if (mSortBy == MovieDataFetcher.SORT_RATING) {
if (!menu_sort_rating.isChecked()) {
menu_sort_rating.setChecked(true);
}
} else {
if (!menu_sort_popularity.isChecked()) {
menu_sort_popularity.setChecked(true);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu_sort_popularity:
item.setChecked(true);
mSortBy = MovieDataFetcher.SORT_POPULARITY;
updateMovies();
break;
case R.id.menu_sort_rating:
item.setChecked(true);
mSortBy = MovieDataFetcher.SORT_RATING;
updateMovies();
break;
}
return super.onOptionsItemSelected(item);
}
private void updateMovies() {
MovieDataFetcher movieTask = new MovieDataFetcher();
movieTask.execute(mSortBy);
}
/*****
* INNER-CLASS TO DO BACKGROUND FETCHING AND PARSING OF THE DATA
*/
class MovieDataFetcher extends AsyncTask<String, Void, Movie[]> {
private final String LOG_TAG = MovieDataFetcher.class.getSimpleName();
public static final String SORT_POPULARITY = "0";
public static final String SORT_RATING = "1";
@Override
protected Movie[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
//Must be declared outside, because if a error happens anytime after their
// declaration, it would remain open
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String discoverJsonStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie";
final String SORT_PARAM = "sort_by";
final String API_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(SORT_PARAM, params[0] == SORT_RATING ? "vote_average.desc" : "popularity.desc")
.appendQueryParameter(API_PARAM, BuildConfig.TMDB_API_KEY)
.build();
URL theMovieDb = new URL(builtUri.toString());
//Create the request and open connection
urlConnection = (HttpURLConnection) theMovieDb.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Gets input stream from the page
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
if (builder.length() == 0) {
//Stream was empty
return null;
}
discoverJsonStr = builder.toString();
} catch (IOException e) {
//Happens if connection doesn't open
Log.e(LOG_TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing the stream", e);
}
}
}
try {
return getDiscoverDataFromJson(discoverJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
//Happens only if it fails to get or parse the data
return null;
}
private Movie[] getDiscoverDataFromJson(String discoverJsonStr) throws JSONException {
final String TMDB_RESULTS = "results";
final String TMDB_TITLE = "title";
final String TMDB_POSTER_PATH = "poster_path";
final String TMDB_RELEASE_DATE = "release_date";
final String TMDB_RATING = "vote_average";
final String TMDB_OVERVIEW = "overview";
JSONObject discoverJson = new JSONObject(discoverJsonStr);
JSONArray moviesJsonArray = discoverJson.getJSONArray(TMDB_RESULTS);
Movie[] resultMovies = new Movie[moviesJsonArray.length()];
for (int i = 0; i < moviesJsonArray.length(); i++) {
JSONObject movieData = moviesJsonArray.getJSONObject(i);
String movieName = movieData.getString(TMDB_TITLE);
String posterPath = movieData.getString(TMDB_POSTER_PATH);
String releaseYear = extractYear(movieData.getString(TMDB_RELEASE_DATE));
String rating = movieData.getString(TMDB_RATING);
String overview = movieData.getString(TMDB_OVERVIEW);
resultMovies[i] = new Movie(movieName, posterPath, releaseYear, rating, overview);
}
return resultMovies;
}
private String extractYear(String releaseDate) {
try {
return releaseDate.substring(0, 4);
} catch (StringIndexOutOfBoundsException e) {
return "
}
}
@Override
protected void onPostExecute(Movie[] movies) {
if (movies != null) {
mMoviesAdapter.clear();
mMoviesAdapter.addAll(Arrays.asList(movies));
}
}
}
}
|
package ee.ut.cs.rum.workspace.internal.ui.overview;
import java.text.SimpleDateFormat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import ee.ut.cs.rum.controller.RumController;
import ee.ut.cs.rum.database.domain.Project;
import ee.ut.cs.rum.enums.ControllerEntityType;
import ee.ut.cs.rum.enums.ControllerUpdateType;
import ee.ut.cs.rum.interfaces.RumUpdatableView;
public class WorkspaceProjectDetails extends Composite implements RumUpdatableView {
private static final long serialVersionUID = -5990558506997308715L;
private Display display;
private RumController rumController;
private Project project;
private Label projectName;
private Label projectDescription;
private Label createdAt;
private Label projectLastModifiedAt;
WorkspaceProjectDetails(WorkspaceDetailsContainer workspaceDetailsContainer, Project project, RumController rumController) {
super(workspaceDetailsContainer, SWT.NONE);
this.display=Display.getCurrent();
this.rumController=rumController;
rumController.registerView(this, ControllerEntityType.PROJECT);
this.project=project;
this.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true));
this.setLayout(new GridLayout(2, false));
Label nameLabel = new Label(this, SWT.NONE);
nameLabel.setText("Project name:");
nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false));
projectName = new Label(this, SWT.NONE);
projectName.setText(project.getName());
projectName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
nameLabel = new Label(this, SWT.NONE);
nameLabel.setText("Project description:");
nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false));
projectDescription = new Label(this, SWT.NONE);
projectDescription.setText(project.getDescription());
projectDescription.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
nameLabel = new Label(this, SWT.NONE);
nameLabel.setText("Created at:");
nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false));
createdAt = new Label(this, SWT.NONE);
createdAt.setText(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(project.getCreatedAt()));
createdAt.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
nameLabel = new Label(this, SWT.NONE);
nameLabel.setText("Last change at:");
nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false));
projectLastModifiedAt = new Label(this, SWT.NONE);
projectLastModifiedAt.setText(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(project.getLastModifiedAt()));
projectLastModifiedAt.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
Button openProjectButton = new Button(this, SWT.BORDER);
openProjectButton.setText("Open project");
openProjectButton.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, false, true));
((GridData) openProjectButton.getLayoutData()).horizontalSpan = ((GridLayout) this.getLayout()).numColumns;
openProjectButton.addListener(SWT.Selection, new Listener() {
private static final long serialVersionUID = 6660200337375128860L;
public void handleEvent(Event e) {
workspaceDetailsContainer.getWorkspaceOverview().getWorkspaceUI().getWorkspaceHeader().getProjectSelectorCombo().selectProject(project);
}
});
}
@Override
public void controllerUpdateNotify(ControllerUpdateType updateType, Object updatedEntity) {
if (updatedEntity instanceof Project) {
Project updatedProject=(Project)updatedEntity;
if (updatedProject.getId()==project.getId()) {
switch (updateType) {
case MODIFIY:
display.asyncExec(new Runnable() {
public void run() {
projectName.setText(updatedProject.getName());
projectDescription.setText(updatedProject.getDescription());
projectLastModifiedAt.setText(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(updatedProject.getLastModifiedAt()));
}
});
break;
case DELETE:
display.asyncExec(new Runnable() {
public void run() {
//TODO: Display a message to user
WorkspaceProjectDetails.this.dispose();
}
});
break;
default:
break;
}
}
}
}
@Override
public void dispose() {
rumController.unregisterView(this, ControllerEntityType.PROJECT);
super.dispose();
}
}
|
package com.twistedplane.sealnote.view.staggeredgrid;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ListAdapter;
import com.twistedplane.sealnote.data.CardGridStaggeredCursorAdapter;
import com.twistedplane.sealnote.utils.PreferenceHandler;
import it.gmariotti.cardslib.library.extra.staggeredgrid.internal.CardGridStaggeredArrayAdapter;
import it.gmariotti.cardslib.library.extra.staggeredgrid.view.CardGridStaggeredView;
/**
* Specialized CardGridStaggeredView class used in SealNote.
*
* + Add support for cursor adapter
* + Changes to make column mode change as per latest Sealnote settings
* preferences
*/
public class StaggeredGridView extends CardGridStaggeredView {
public final static String TAG = "StaggeredGridView";
public StaggeredGridView(Context context) {
super(context);
}
public StaggeredGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StaggeredGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* NOTE:
* Also restore the column counts. Somehow seems to fix the bug
* where the items tend have same x values while different columns
*/
@Override
public void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
updateGridColumnCount();
}
/**
* Uses CardGridStaggeredCursorAdapter to avoid dispatch to generic
* ListAdapter version of this function which doesn't support this
* kind of adapter.
*/
public void setAdapter(CardGridStaggeredCursorAdapter adapter) {
super.setAdapter(adapter);
adapter.setRowLayoutId(list_card_layout_resourceID);
adapter.setCardGridView(this);
}
/**
* Uses CardGridStaggeredCursorAdapter to avoid dispatch to generic
* ListAdapter version of this function which doesn't support this
* kind of adapter.
*/
public void setExternalAdapter(ListAdapter adapter, CardGridStaggeredCursorAdapter cardCursorAdapter) {
setAdapter(adapter);
cardCursorAdapter.setCardGridView(this);
cardCursorAdapter.setRowLayoutId(list_card_layout_resourceID);
}
/**
* Add support for CardGridStaggeredCursorAdapter.
*/
@Override
public void setAdapter(ListAdapter adapter) {
if (adapter instanceof CardGridStaggeredArrayAdapter) {
setAdapter((CardGridStaggeredArrayAdapter)adapter);
} else if (adapter instanceof CardGridStaggeredCursorAdapter) {
setAdapter((CardGridStaggeredCursorAdapter)adapter);
} else {
Log.w(TAG, "You are using a generic adapter. Pay attention: your adapter has to call cardGridArrayAdapter#getView method.");
super.setAdapter(adapter);
}
}
/**
* Update column count as per current orientation of device and SealNote
* multi-column/single-column preference value.
*/
public void updateGridColumnCount() {
if (!PreferenceHandler.isMultiColumnGridEnabled(getContext())) {
// Single-column mode is enabled
setColumnCount(1);
} else {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
setColumnCountPortrait(2);
setColumnCountLandscape(3);
} else {
setColumnCountLandscape(3);
setColumnCountPortrait(2);
}
}
}
}
|
package ru.stqa.java.adressbook.tests;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import ru.stqa.java.adressbook.model.ContactData;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class ContactDetailsTests extends TestBase {
@Test
public void testContactDetails() {
app.goTo().homePage();
ContactData contact = app.contact().all().iterator().next();
ContactData contactInfoDetailsForm = app.contact().contactInfoDetailsForm(contact);
assertThat(mergeAllContactInfo(contact.getAllContactinfo()), equalTo(mergeAllContactInfo(contactInfoDetailsForm)));
}
private String mergeAllContactInfo(ContactData contact) {
return Arrays.asList(contact.getLastname(),contact.getFirstname(),contact.getAddress(),
contact.getEmail(),contact.getEmail2(),contact.getEmail3(),
contact.getHomePhone(),contact.getMobilePhone(),contact.getWorkPhone())
.stream().filter((s) -> ! s.equals(""))
.map(ContactDetailsTests::cleaned)
.collect(Collectors.joining("\n"));
}
public static String cleaned(String details) {
return details.replaceAll("\\s", "")
.replaceAll("H:", "")
.replaceAll("W:", "")
.replaceAll("M:", "")
.replaceAll("[-()]", "");
}
}
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactsData;
import java.util.ArrayList;
import java.util.List;
public class ContactsHelper extends BaseHelper {
public ContactsHelper(WebDriver wd) {
super(wd);
}
public void returnToContactsPage() {
click(By.linkText("home page"));
}
public void submitContactCreation() {
click(By.xpath("//div[@id='content']/form/input[21]"));
}
public void fillContactForm(ContactsData contactsData) {
type(By.name("firstname"), contactsData.getFirstname());
type(By.name("lastname"), contactsData.getLastname());
type(By.name("nickname"), contactsData.getNickname());
type(By.name("company"), contactsData.getCompany());
type(By.name("address"), contactsData.getAddress());
type(By.name("home"), contactsData.getHomephone());
type(By.name("mobile"), contactsData.getMobilephone());
type(By.name("email"), contactsData.getEmail1());
}
// if (creation) {
// new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactsData.getGroup());
// } else {
// Assert.assertFalse(isElementPresent(By.name("new_group")));
public void initContactCreation() {
click(By.linkText("add new"));
}
public void selectContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
public void initContactDeletion() {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
}
public void submitContactDeletion() {
wd.switchTo().alert().accept();
}
public void initContactModification() {
click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
}
public void submitContactModification() {
click(By.name("update"));
}
public void createContact(ContactsData contact) {
initContactCreation();
fillContactForm(contact);
submitContactCreation();
returnToContactsPage();
}
public boolean isThereAContact() {
return isElementPresent(By.name("selected[]"));
}
public void returnToHomePage() {
click(By.linkText("home"));
}
public int getContactCount() {
return wd.findElements(By.name("selected[]")).size();
}
public List<ContactsData> getContactsList() {
List<ContactsData> contacts = new ArrayList<ContactsData>();
List<WebElement> elements = wd.findElements(By.name("entry"));
for (WebElement element : elements) {
String name = element.getText();
String id = element.findElement(By.tagName("input")).getAttribute("value");
ContactsData contact = new ContactsData(id, name, null, null, null, null, null, null, null, null);
contacts.add(contact);
}
return contacts;
}
}
|
package org.cytoscape.app.internal.net.server;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.apache.http.HttpStatus;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AddAllowOriginHeaderTest {
@Test
public void testAddAccessControlAllowOriginHeader() throws Exception
{
final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611));
final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
httpd.addResponder(new CyHttpResponder()
{
public Pattern getURIPattern()
{
return Pattern.compile("^/test$");
}
public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI)
{
return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
}
});
httpd.addAfterResponse(new AddAllowOriginHeader());
httpd.start();
HttpURLConnection connection = null;
final String url = "http://localhost:2611/test";
connection = connectToURL(url, "GET");
assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
assertEquals(readConnection(connection), "test response ok");
httpd.stop();
}
private static HttpURLConnection connectToURL(String urlString, String method) throws Exception
{
final URL url = new URL(urlString);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.setConnectTimeout(1000);
connection.connect();
return connection;
}
private static String readConnection(HttpURLConnection connection) throws Exception
{
final StringBuffer buffer = new StringBuffer();
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (true)
{
final String line = reader.readLine();
if (line == null)
break;
buffer.append(line);
}
return buffer.toString();
}
}
|
package edu.csulb.android.androidscoretracker;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class SessionHistoryDatabaseManager {
private SQLiteDatabase db;
private SimpleDateFormat dateFormat;
private final String TABLE_NAME = "sessionHistory";
private final String COLUMN_ID = "id";
private final String COLUMN_SESSION_ID = "sessionId";
private final String COLUMN_DATE = "date";
private final String COLUMN_COMMENT = "comment";
private final String COLUMN_TYPE = "type";
public SessionHistoryDatabaseManager() {
db = DatabaseManager.getInstance().getDb();
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
//add an history in the database
public int addHistory(SessionHistory history) {
ContentValues values = new ContentValues();
values.put(COLUMN_SESSION_ID, history.getSessionId());
values.put(COLUMN_COMMENT, history.getComment());
values.put(COLUMN_TYPE, history.getType());
values.put(COLUMN_DATE, dateFormat.format(history.getDate()));
db.insert(TABLE_NAME, null, values);
return this.getLastHistoryId();
}
public int getLastHistoryId() {
Cursor res = db.rawQuery("select * from " + TABLE_NAME + " order by " + COLUMN_ID + " DESC LIMIT 1;", null);
res.moveToFirst();
int ret = res.getInt(res.getColumnIndex(COLUMN_ID));
res.close();
return ret;
}
public SessionHistory getLastHistoryIdForType(int type, int sessionId) {
Cursor res = db.rawQuery("select * from " + TABLE_NAME +
" WHERE " + COLUMN_TYPE + " = " + type +
" AND " + COLUMN_SESSION_ID + " = " + sessionId +
" order by " + COLUMN_ID +
" DESC LIMIT 1;", null);
res.moveToFirst();
SessionHistory history = new SessionHistory();
history.setId(res.getInt(res.getColumnIndex(COLUMN_ID)));
history.setSessionId(res.getInt(res.getColumnIndex(COLUMN_SESSION_ID)));
history.setComment(res.getString(res.getColumnIndex(COLUMN_COMMENT)));
history.setType(res.getInt(res.getColumnIndex(COLUMN_TYPE)));
try {
history.setDate(dateFormat.parse(res.getString(res.getColumnIndex(COLUMN_DATE))));
} catch (Exception e) {
}
res.close();
return history;
}
public int countHistory(int sessionId) {
Cursor res= db.rawQuery("select COUNT(*) from " + TABLE_NAME + " where " + COLUMN_SESSION_ID + " = '" + sessionId + "';", null);
res.moveToFirst();
int count= res.getInt(0);
res.close();
return count;
}
//Get all history from the database
public ArrayList<SessionHistory> getAllHistory(int sessionId) {
ArrayList<SessionHistory> histories = new ArrayList<>();
Cursor res = db.rawQuery("select * from " + TABLE_NAME + " where " + COLUMN_SESSION_ID + " = '" + sessionId + "' order by " + COLUMN_DATE + " desc;", null);
res.moveToFirst();
while(!res.isAfterLast()){
SessionHistory history = new SessionHistory();
history.setId(res.getInt(res.getColumnIndex(COLUMN_ID)));
history.setSessionId(res.getInt(res.getColumnIndex(COLUMN_SESSION_ID)));
history.setComment(res.getString(res.getColumnIndex(COLUMN_COMMENT)));
history.setType(res.getInt(res.getColumnIndex(COLUMN_TYPE)));
try {
history.setDate(dateFormat.parse(res.getString(res.getColumnIndex(COLUMN_DATE))));
} catch (Exception e) {
}
histories.add(history);
res.moveToNext();
}
res.close();
return histories;
}
//Delete an history session from a database
public void deleteHistory(SessionHistory history) {
db.delete(TABLE_NAME, "id = ?", new String[]{Integer.toString(history.getId())});
}
//Update a history session in the database
public void updateHistorySession(SessionHistory history) {
ContentValues values = new ContentValues();
values.put(COLUMN_COMMENT, history.getComment());
values.put(COLUMN_TYPE, history.getType());
values.put(COLUMN_DATE, dateFormat.format(history.getDate()));
db.update(TABLE_NAME, values, "id = ?", new String[] {Integer.toString(history.getId())});
}
}
|
package nodomain.freeyourgadget.gadgetbridge.devices.qhybrid;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.GBException;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.activities.AbstractGBActivity;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceType;
import nodomain.freeyourgadget.gadgetbridge.model.GenericItem;
import nodomain.freeyourgadget.gadgetbridge.model.ItemWithDetails;
import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.DeviceInfo;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.QHybridSupport;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.adapter.fossil.FossilWatchAdapter;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.buttonconfig.ConfigPayload;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.FossilRequest;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
public class ConfigActivity extends AbstractGBActivity {
PackageAdapter adapter;
ArrayList<NotificationConfiguration> list;
PackageConfigHelper helper;
final int REQUEST_CODE_ADD_APP = 0;
private boolean hasControl = false;
SharedPreferences prefs;
TextView timeOffsetView, timezoneOffsetView;
GBDevice device;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qhybrid_settings);
findViewById(R.id.buttonOverwriteButtons).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_OVERWRITE_BUTTONS));
}
});
prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
timeOffsetView = findViewById(R.id.qhybridTimeOffset);
timeOffsetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int timeOffset = prefs.getInt("QHYBRID_TIME_OFFSET", 0);
LinearLayout layout2 = new LinearLayout(ConfigActivity.this);
layout2.setOrientation(LinearLayout.HORIZONTAL);
final NumberPicker hourPicker = new NumberPicker(ConfigActivity.this);
hourPicker.setMinValue(0);
hourPicker.setMaxValue(23);
hourPicker.setValue(timeOffset / 60);
final NumberPicker minPicker = new NumberPicker(ConfigActivity.this);
minPicker.setMinValue(0);
minPicker.setMaxValue(59);
minPicker.setValue(timeOffset % 60);
layout2.addView(hourPicker);
TextView tw = new TextView(ConfigActivity.this);
tw.setText(":");
layout2.addView(tw);
layout2.addView(minPicker);
layout2.setGravity(Gravity.CENTER);
new AlertDialog.Builder(ConfigActivity.this)
.setTitle("offset time by")
.setView(layout2)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
prefs.edit().putInt("QHYBRID_TIME_OFFSET", hourPicker.getValue() * 60 + minPicker.getValue()).apply();
updateTimeOffset();
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE));
Toast.makeText(ConfigActivity.this, "change might take some seconds...", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", null)
.show();
}
});
updateTimeOffset();
timezoneOffsetView = findViewById(R.id.timezoneOffset);
timezoneOffsetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int timeOffset = prefs.getInt("QHYBRID_TIMEZONE_OFFSET", 0);
LinearLayout layout2 = new LinearLayout(ConfigActivity.this);
layout2.setOrientation(LinearLayout.HORIZONTAL);
final NumberPicker hourPicker = new NumberPicker(ConfigActivity.this);
hourPicker.setMinValue(0);
hourPicker.setMaxValue(23);
hourPicker.setValue(timeOffset / 60);
final NumberPicker minPicker = new NumberPicker(ConfigActivity.this);
minPicker.setMinValue(0);
minPicker.setMaxValue(59);
minPicker.setValue(timeOffset % 60);
layout2.addView(hourPicker);
TextView tw = new TextView(ConfigActivity.this);
tw.setText(":");
layout2.addView(tw);
layout2.addView(minPicker);
layout2.setGravity(Gravity.CENTER);
new AlertDialog.Builder(ConfigActivity.this)
.setTitle("offset timezone by")
.setView(layout2)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
prefs.edit().putInt("QHYBRID_TIMEZONE_OFFSET", hourPicker.getValue() * 60 + minPicker.getValue()).apply();
updateTimezoneOffset();
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_TIMEZONE));
Toast.makeText(ConfigActivity.this, "change might take some seconds...", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", null)
.show();
}
});
updateTimezoneOffset();
setTitle(R.string.preferences_qhybrid_settings);
ListView appList = findViewById(R.id.qhybrid_appList);
try {
helper = new PackageConfigHelper(getApplicationContext());
list = helper.getNotificationConfigurations();
} catch (GBException e) {
e.printStackTrace();
GB.toast("error getting configurations", Toast.LENGTH_SHORT, GB.ERROR, e);
list = new ArrayList<>();
}
// null is added to indicate the plus button added handled in PackageAdapter#getView
list.add(null);
appList.setAdapter(adapter = new PackageAdapter(this, R.layout.qhybrid_package_settings_item, list));
appList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int i, long l) {
PopupMenu menu = new PopupMenu(ConfigActivity.this, view);
menu.getMenu().add(0, 0, 0, "edit");
menu.getMenu().add(0, 1, 1, "delete");
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case 0: {
TimePicker picker = new TimePicker(ConfigActivity.this, (NotificationConfiguration) adapterView.getItemAtPosition(i));
picker.finishListener = new TimePicker.OnFinishListener() {
@Override
public void onFinish(boolean success, NotificationConfiguration config) {
setControl(false, null);
if (success) {
try {
helper.saveNotificationConfiguration(config);
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_NOTIFICATION_CONFIG_CHANGED));
} catch (GBException e) {
e.printStackTrace();
GB.toast("error saving notification", Toast.LENGTH_SHORT, GB.ERROR, e);
}
refreshList();
}
}
};
picker.handsListener = new TimePicker.OnHandsSetListener() {
@Override
public void onHandsSet(NotificationConfiguration config) {
setHands(config);
}
};
picker.vibrationListener = new TimePicker.OnVibrationSetListener() {
@Override
public void onVibrationSet(NotificationConfiguration config) {
vibrate(config);
}
};
setControl(true, picker.getSettings());
break;
}
case 1: {
try {
helper.deleteNotificationConfiguration((NotificationConfiguration) adapterView.getItemAtPosition(i));
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(new Intent(QHybridSupport.QHYBRID_COMMAND_NOTIFICATION_CONFIG_CHANGED));
} catch (GBException e) {
e.printStackTrace();
GB.toast("error deleting setting", Toast.LENGTH_SHORT, GB.ERROR, e);
}
refreshList();
break;
}
}
return true;
}
});
menu.show();
return true;
}
});
appList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent notificationIntent = new Intent(QHybridSupport.QHYBRID_COMMAND_NOTIFICATION);
notificationIntent.putExtra("CONFIG", (NotificationConfiguration) adapterView.getItemAtPosition(i));
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(notificationIntent);
}
});
SeekBar vibeBar = findViewById(R.id.vibrationStrengthBar);
vibeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int start;
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
start = seekBar.getProgress();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress;
if ((progress = seekBar.getProgress()) == start) return;
String[] values = {"25", "50", "100"};
device.addDeviceInfo(new GenericItem(QHybridSupport.ITEM_VIBRATION_STRENGTH, values[progress]));
Intent intent = new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_SETTINGS);
intent.putExtra("EXTRA_SETTING", QHybridSupport.ITEM_VIBRATION_STRENGTH);
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(intent);
}
});
device = GBApplication.app().getDeviceManager().getSelectedDevice();
if (device == null || device.getType() != DeviceType.FOSSILQHYBRID) {
setSettingsError("Watch not connected");
} else {
updateSettings();
}
}
private void updateTimeOffset() {
int timeOffset = prefs.getInt("QHYBRID_TIME_OFFSET", 0);
DecimalFormat format = new DecimalFormat("00");
timeOffsetView.setText(
format.format(timeOffset / 60) + ":" +
format.format(timeOffset % 60)
);
}
private void updateTimezoneOffset() {
int timeOffset = prefs.getInt("QHYBRID_TIMEZONE_OFFSET", 0);
DecimalFormat format = new DecimalFormat("00");
timezoneOffsetView.setText(
format.format(timeOffset / 60) + ":" +
format.format(timeOffset % 60)
);
}
private void setSettingsEnabled(boolean enables) {
findViewById(R.id.settingsLayout).setAlpha(enables ? 1f : 0.2f);
}
private void updateSettings() {
runOnUiThread(new Runnable() {
@Override
public void run() {
EditText et = findViewById(R.id.stepGoalEt);
et.setOnEditorActionListener(null);
final String text = device.getDeviceInfo(QHybridSupport.ITEM_STEP_GOAL).getDetails();
et.setText(text);
et.setSelection(text.length());
et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE || i == EditorInfo.IME_ACTION_NEXT) {
String t = textView.getText().toString();
if (!t.isEmpty()) {
device.addDeviceInfo(new GenericItem(QHybridSupport.ITEM_STEP_GOAL, t));
Intent intent = new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_SETTINGS);
intent.putExtra("EXTRA_SETTING", QHybridSupport.ITEM_STEP_GOAL);
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(intent);
updateSettings();
}
((InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
return true;
}
});
if ("true".equals(device.getDeviceInfo(QHybridSupport.ITEM_EXTENDED_VIBRATION_SUPPORT).getDetails())) {
final int strengthProgress = (int) (Math.log(Double.parseDouble(device.getDeviceInfo(QHybridSupport.ITEM_VIBRATION_STRENGTH).getDetails()) / 25) / Math.log(2));
setSettingsEnabled(true);
SeekBar seekBar = findViewById(R.id.vibrationStrengthBar);
seekBar.setProgress(strengthProgress);
} else {
findViewById(R.id.vibrationStrengthBar).setEnabled(false);
findViewById(R.id.vibrationStrengthLayout).setAlpha(0.5f);
}
CheckBox activityHandCheckbox = findViewById(R.id.checkBoxUserActivityHand);
if (device.getDeviceInfo(QHybridSupport.ITEM_HAS_ACTIVITY_HAND).getDetails().equals("true")) {
if (device.getDeviceInfo(QHybridSupport.ITEM_USE_ACTIVITY_HAND).getDetails().equals("true")) {
activityHandCheckbox.setChecked(true);
}
activityHandCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean checked) {
if (!device.getDeviceInfo(QHybridSupport.ITEM_STEP_GOAL).getDetails().equals("1000000")) {
new AlertDialog.Builder(ConfigActivity.this)
.setMessage("Please set the step count to a million to activate that.")
.setPositiveButton("ok", null)
.show();
buttonView.setChecked(false);
return;
}
device.addDeviceInfo(new GenericItem(QHybridSupport.ITEM_USE_ACTIVITY_HAND, String.valueOf(checked)));
Intent intent = new Intent(QHybridSupport.QHYBRID_COMMAND_UPDATE_SETTINGS);
intent.putExtra("EXTRA_SETTING", QHybridSupport.ITEM_USE_ACTIVITY_HAND);
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(intent);
}
});
} else {
// activityHandCheckbox.setEnabled(false);
activityHandCheckbox.setAlpha(0.2f);
activityHandCheckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GB.toast("nah.", Toast.LENGTH_SHORT, GB.INFO);
((CheckBox) v).setChecked(false);
}
});
}
final String buttonJson = device.getDeviceInfo(FossilWatchAdapter.ITEM_BUTTONS).getDetails();
try {
JSONArray buttonConfig_;
if (buttonJson == null || buttonJson.isEmpty()) {
buttonConfig_ = new JSONArray(new String[]{"", "", ""});
}else{
buttonConfig_ = new JSONArray(buttonJson);
}
final JSONArray buttonConfig = buttonConfig_;
LinearLayout buttonLayout = findViewById(R.id.buttonConfigLayout);
buttonLayout.removeAllViews();
findViewById(R.id.buttonOverwriteButtons).setVisibility(View.GONE);
final ConfigPayload[] payloads = ConfigPayload.values();
final String[] names = new String[payloads.length];
for (int i = 0; i < payloads.length; i++)
names[i] = payloads[i].getDescription();
for (int i = 0; i < buttonConfig.length(); i++) {
final int currentIndex = i;
String configName = buttonConfig.getString(i);
TextView buttonTextView = new TextView(ConfigActivity.this);
buttonTextView.setTextColor(Color.WHITE);
buttonTextView.setTextSize(20);
try {
ConfigPayload payload = ConfigPayload.valueOf(configName);
buttonTextView.setText("Button " + (i + 1) + ": " + payload.getDescription());
} catch (IllegalArgumentException e) {
buttonTextView.setText("Button " + (i + 1) + ": Unknown");
}
buttonTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(ConfigActivity.this)
.setItems(names, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
ConfigPayload selected = payloads[which];
try {
buttonConfig.put(currentIndex, selected.toString());
device.addDeviceInfo(new GenericItem(FossilWatchAdapter.ITEM_BUTTONS, buttonConfig.toString()));
updateSettings();
Intent buttonIntent = new Intent(QHybridSupport.QHYBRID_COMMAND_OVERWRITE_BUTTONS);
buttonIntent.putExtra(FossilWatchAdapter.ITEM_BUTTONS, buttonConfig.toString());
LocalBroadcastManager.getInstance(ConfigActivity.this).sendBroadcast(buttonIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
})
.setTitle("Button " + (currentIndex + 1))
.create();
dialog.show();
}
});
buttonLayout.addView(buttonTextView);
}
} catch (JSONException e) {
e.printStackTrace();
GB.toast("error parsing button config", Toast.LENGTH_LONG, GB.ERROR);
}
}
});
}
private void setControl(boolean control, NotificationConfiguration config) {
if (hasControl == control) return;
Intent intent = new Intent(control ? QHybridSupport.QHYBRID_COMMAND_CONTROL : QHybridSupport.QHYBRID_COMMAND_UNCONTROL);
intent.putExtra("CONFIG", config);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
this.hasControl = control;
}
private void setHands(NotificationConfiguration config) {
sendControl(config, QHybridSupport.QHYBRID_COMMAND_SET);
}
private void vibrate(NotificationConfiguration config) {
sendControl(config, QHybridSupport.QHYBRID_COMMAND_VIBRATE);
}
private void sendControl(NotificationConfiguration config, String request) {
Intent intent = new Intent(request);
intent.putExtra("CONFIG", config);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void refreshList() {
list.clear();
try {
list.addAll(helper.getNotificationConfigurations());
} catch (GBException e) {
e.printStackTrace();
GB.toast("error getting configurations", Toast.LENGTH_SHORT, GB.ERROR, e);
}
// null is added to indicate the plus button added handled in PackageAdapter#getView
list.add(null);
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
refreshList();
registerReceiver(buttonReceiver, new IntentFilter(QHybridSupport.QHYBRID_EVENT_BUTTON_PRESS));
LocalBroadcastManager.getInstance(this).registerReceiver(settingsReceiver, new IntentFilter(QHybridSupport.QHYBRID_EVENT_SETTINGS_UPDATED));
LocalBroadcastManager.getInstance(this).registerReceiver(fileReceiver, new IntentFilter(QHybridSupport.QHYBRID_EVENT_FILE_UPLOADED));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(buttonReceiver);
LocalBroadcastManager.getInstance(this).unregisterReceiver(settingsReceiver);
LocalBroadcastManager.getInstance(this).unregisterReceiver(fileReceiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private void setSettingsError(final String error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setSettingsEnabled(false);
((TextView) findViewById(R.id.settingsErrorText)).setVisibility(View.VISIBLE);
((TextView) findViewById(R.id.settingsErrorText)).setText(error);
}
});
}
class PackageAdapter extends ArrayAdapter<NotificationConfiguration> {
PackageManager manager;
PackageAdapter(@NonNull Context context, int resource, @NonNull List<NotificationConfiguration> objects) {
super(context, resource, objects);
manager = context.getPackageManager();
}
@NonNull
@Override
public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) {
if (!(view instanceof RelativeLayout))
view = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.qhybrid_package_settings_item, null);
NotificationConfiguration settings = getItem(position);
if (settings == null) {
Button addButton = new Button(ConfigActivity.this);
addButton.setText("+");
addButton.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(ConfigActivity.this, QHybridAppChoserActivity.class), REQUEST_CODE_ADD_APP);
}
});
return addButton;
}
try {
((ImageView) view.findViewById(R.id.packageIcon)).setImageDrawable(manager.getApplicationIcon(settings.getPackageName()));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
final int width = 100;
((TextView) view.findViewById(R.id.packageName)).setText(settings.getAppName());
Bitmap bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Paint black = new Paint();
black.setColor(Color.BLACK);
black.setStyle(Paint.Style.STROKE);
black.setStrokeWidth(5);
c.drawCircle(width / 2, width / 2, width / 2 - 3, black);
int center = width / 2;
if (settings.getHour() != -1) {
c.drawLine(
center,
center,
(float) (center + Math.sin(Math.toRadians(settings.getHour())) * (width / 4)),
(float) (center - Math.cos(Math.toRadians(settings.getHour())) * (width / 4)),
black
);
}
if (settings.getMin() != -1) {
c.drawLine(
center,
center,
(float) (center + Math.sin(Math.toRadians(settings.getMin())) * (width / 3)),
(float) (center - Math.cos(Math.toRadians(settings.getMin())) * (width / 3)),
black
);
}
((ImageView) view.findViewById(R.id.packageClock)).setImageBitmap(bitmap);
return view;
}
}
BroadcastReceiver fileReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean error = intent.getBooleanExtra("EXTRA_ERROR", false);
if (error) {
Toast.makeText(ConfigActivity.this, "Error overwriting buttons", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(ConfigActivity.this, "Successfully overwritten buttons", Toast.LENGTH_SHORT).show();
}
};
BroadcastReceiver buttonReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(ConfigActivity.this, "Button " + intent.getIntExtra("BUTTON", -1) + " pressed", Toast.LENGTH_SHORT).show();
}
};
BroadcastReceiver settingsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(ConfigActivity.this, "Setting updated", Toast.LENGTH_SHORT).show();
updateSettings();
}
};
}
|
package org.mifos.mobilebanking.ui.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler;
import org.mifos.mobilebanking.R;
import org.mifos.mobilebanking.models.beneficiary.Beneficiary;
import org.mifos.mobilebanking.models.beneficiary.BeneficiaryPayload;
import org.mifos.mobilebanking.models.beneficiary.BeneficiaryUpdatePayload;
import org.mifos.mobilebanking.models.templates.beneficiary.AccountTypeOption;
import org.mifos.mobilebanking.models.templates.beneficiary.BeneficiaryTemplate;
import org.mifos.mobilebanking.presenters.BeneficiaryApplicationPresenter;
import org.mifos.mobilebanking.ui.activities.base.BaseActivity;
import org.mifos.mobilebanking.ui.enums.BeneficiaryState;
import org.mifos.mobilebanking.ui.fragments.base.BaseFragment;
import org.mifos.mobilebanking.ui.views.BeneficiaryApplicationView;
import org.mifos.mobilebanking.utils.Constants;
import org.mifos.mobilebanking.utils.Network;
import org.mifos.mobilebanking.utils.Toaster;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class BeneficiaryApplicationFragment extends BaseFragment implements
BeneficiaryApplicationView, AdapterView.OnItemSelectedListener {
@BindView(R.id.sp_account_type)
Spinner spAccountType;
@BindView(R.id.ll_application_beneficiary)
LinearLayout llApplicationBeneficiary;
@BindView(R.id.til_account_number)
TextInputLayout tilAccountNumber;
@BindView(R.id.til_office_name)
TextInputLayout tilOfficeName;
@BindView(R.id.til_transfer_limit)
TextInputLayout tilTransferLimit;
@BindView(R.id.til_beneficiary_name)
TextInputLayout tilBeneficiaryName;
@BindView(R.id.layout_error)
View layoutError;
@BindView(R.id.view_flipper)
NestedScrollView nsvBeneficiary;
@Inject
BeneficiaryApplicationPresenter presenter;
private List<String> listAccountType = new ArrayList<>();
private ArrayAdapter<String> accountTypeAdapter;
private BeneficiaryState beneficiaryState;
private Beneficiary beneficiary;
private BeneficiaryTemplate beneficiaryTemplate;
private int accountTypeId = -1;
private View rootView;
private SweetUIErrorHandler sweetUIErrorHandler;
public static BeneficiaryApplicationFragment newInstance(BeneficiaryState beneficiaryState,
@Nullable Beneficiary beneficiary) {
BeneficiaryApplicationFragment fragment = new BeneficiaryApplicationFragment();
Bundle args = new Bundle();
args.putSerializable(Constants.BENEFICIARY_STATE, beneficiaryState);
if (beneficiary != null) {
args.putParcelable(Constants.BENEFICIARY, beneficiary);
}
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setToolbarTitle(getString(R.string.add_beneficiary));
if (getArguments() != null) {
beneficiaryState = (BeneficiaryState) getArguments()
.getSerializable(Constants.BENEFICIARY_STATE);
if (beneficiaryState == BeneficiaryState.UPDATE) {
beneficiary = getArguments().getParcelable(Constants.BENEFICIARY);
setToolbarTitle(getString(R.string.update_beneficiary));
} else if (beneficiaryState == BeneficiaryState.CREATE_QR) {
beneficiary = getArguments().getParcelable(Constants.BENEFICIARY);
setToolbarTitle(getString(R.string.add_beneficiary));
} else {
setToolbarTitle(getString(R.string.add_beneficiary));
}
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_beneficiary_application, container, false);
((BaseActivity) getActivity()).getActivityComponent().inject(this);
ButterKnife.bind(this, rootView);
sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView);
showUserInterface();
presenter.attachView(this);
if (savedInstanceState == null) {
presenter.loadBeneficiaryTemplate();
}
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constants.TEMPLATE, beneficiaryTemplate);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
showBeneficiaryTemplate((BeneficiaryTemplate) savedInstanceState.
getParcelable(Constants.TEMPLATE));
}
}
/**
* Setting up {@code accountTypeAdapter} and {@code} spAccountType
*/
@Override
public void showUserInterface() {
accountTypeAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, listAccountType);
accountTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spAccountType.setOnItemSelectedListener(this);
if (!Network.isConnected(getContext())) {
spAccountType.setEnabled(false);
}
spAccountType.setAdapter(accountTypeAdapter);
}
/**
* Fetches {@link BeneficiaryTemplate} from server and further updates the UI according to
* {@link BeneficiaryState} which is initialized in {@code newInstance()} as
* {@code beneficiaryState}
* @param beneficiaryTemplate {@link BeneficiaryTemplate} fetched from server
*/
@Override
public void showBeneficiaryTemplate(BeneficiaryTemplate beneficiaryTemplate) {
this.beneficiaryTemplate = beneficiaryTemplate;
for (AccountTypeOption accountTypeOption : beneficiaryTemplate.getAccountTypeOptions()) {
listAccountType.add(accountTypeOption.getValue());
}
accountTypeAdapter.notifyDataSetChanged();
if (beneficiaryState == BeneficiaryState.UPDATE) {
spAccountType.setSelection(accountTypeAdapter.getPosition(beneficiary
.getAccountType().getValue()));
spAccountType.setEnabled(false);
tilAccountNumber.getEditText().setText(beneficiary.getAccountNumber());
tilAccountNumber.setEnabled(false);
tilOfficeName.getEditText().setText(beneficiary.getOfficeName());
tilOfficeName.setEnabled(false);
tilBeneficiaryName.getEditText().setText(beneficiary.getName());
tilTransferLimit.getEditText().setText(String.valueOf(beneficiary.getTransferLimit()));
} else if (beneficiaryState == BeneficiaryState.CREATE_QR) {
spAccountType.setSelection(beneficiary.getAccountType().getId());
tilAccountNumber.getEditText().setText(beneficiary.getAccountNumber());
tilOfficeName.getEditText().setText(beneficiary.getOfficeName());
}
}
/**
* Used for submitting a new or updating beneficiary application
*/
@OnClick(R.id.btn_beneficiary_submit)
public void submitBeneficiary() {
tilAccountNumber.setErrorEnabled(false);
tilOfficeName.setErrorEnabled(false);
tilTransferLimit.setErrorEnabled(false);
tilBeneficiaryName.setErrorEnabled(false);
if (accountTypeId == -1) {
Toaster.show(rootView, getString(R.string.choose_account_type));
return;
} else if (tilAccountNumber.getEditText().getText().toString().trim().equals("")) {
tilAccountNumber.setError(getString(R.string.enter_account_number));
return;
} else if (tilOfficeName.getEditText().getText().toString().trim().equals("")) {
tilOfficeName.setError(getString(R.string.enter_office_name));
return;
} else if (tilTransferLimit.getEditText().getText().toString().equals("")) {
tilTransferLimit.setError(getString(R.string.enter_transfer_limit));
return;
} else if (tilTransferLimit.getEditText().getText().toString().equals(".")) {
tilTransferLimit.setError(getString(R.string.invalid_amount));
return;
} else if (tilTransferLimit.getEditText().getText().toString().matches("^0*")) {
tilTransferLimit.setError(getString(R.string.amount_greater_than_zero));
return;
} else if (tilBeneficiaryName.getEditText().getText().toString().trim().equals("")) {
tilBeneficiaryName.setError(getString(R.string.enter_beneficiary_name));
return;
}
if (beneficiaryState == BeneficiaryState.CREATE_MANUAL ||
beneficiaryState == BeneficiaryState.CREATE_QR ) {
submitNewBeneficiaryApplication();
} else if (beneficiaryState == BeneficiaryState.UPDATE ) {
submitUpdateBeneficiaryApplication();
}
}
@OnClick(R.id.btn_try_again)
public void onRetry() {
if (Network.isConnected(getContext())) {
presenter.loadBeneficiaryTemplate();
sweetUIErrorHandler.hideSweetErrorLayoutUI(nsvBeneficiary, layoutError);
} else {
Toaster.show(rootView, getString(R.string.internet_not_connected));
}
}
/**
* Submit a new Beneficiary application
*/
private void submitNewBeneficiaryApplication() {
BeneficiaryPayload beneficiaryPayload = new BeneficiaryPayload();
beneficiaryPayload.setAccountNumber(tilAccountNumber.getEditText().getText().toString());
beneficiaryPayload.setOfficeName(tilOfficeName.getEditText().getText().toString());
beneficiaryPayload.setAccountType(accountTypeId);
beneficiaryPayload.setName(tilBeneficiaryName.getEditText().getText().toString());
beneficiaryPayload.setTransferLimit(Integer.parseInt(tilTransferLimit.getEditText().
getText().toString()));
presenter.createBeneficiary(beneficiaryPayload);
}
/**
* Updates an existing beneficiary application
*/
private void submitUpdateBeneficiaryApplication() {
BeneficiaryUpdatePayload payload = new BeneficiaryUpdatePayload();
payload.setName(tilBeneficiaryName.getEditText().getText().toString());
payload.setTransferLimit(Float.parseFloat(tilTransferLimit.getEditText().getText().
toString()));
presenter.updateBeneficiary(beneficiary.getId(), payload);
}
/**
* Displays a {@link android.support.design.widget.Snackbar} on successfully creation of
* Beneficiary and pops fragments in order to go back to {@link BeneficiaryListFragment}
*/
@Override
public void showBeneficiaryCreatedSuccessfully() {
Toaster.show(rootView, getString(R.string.beneficiary_created_successfully));
getActivity().finish();
}
/**
* Displays a {@link android.support.design.widget.Snackbar} on successfully updation of
* Beneficiary and pops fragments in order to go back to {@link BeneficiaryListFragment}
*/
@Override
public void showBeneficiaryUpdatedSuccessfully() {
Toaster.show(rootView, getString(R.string.beneficiary_updated_successfully));
getActivity().getSupportFragmentManager().popBackStack();
getActivity().getSupportFragmentManager().popBackStack();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
accountTypeId = beneficiaryTemplate.getAccountTypeOptions().get(position).getId();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
/**
* It is called whenever any error occurs while executing a request
* @param msg Error message that tells the user about the problem.
*/
@Override
public void showError(String msg ) {
if (!Network.isConnected(getContext())) {
sweetUIErrorHandler.showSweetNoInternetUI(nsvBeneficiary, layoutError);
} else {
sweetUIErrorHandler.showSweetErrorUI(msg, nsvBeneficiary, layoutError);
Toaster.show(rootView, msg);
}
}
@Override
public void setVisibility(int state) {
llApplicationBeneficiary.setVisibility(state);
}
@Override
public void showProgress() {
showProgressBar();
}
@Override
public void hideProgress() {
hideProgressBar();
}
@Override
public void onDestroyView() {
super.onDestroyView();
hideProgress();
presenter.detachView();
}
}
|
package nodomain.freeyourgadget.gadgetbridge.test;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import nodomain.freeyourgadget.gadgetbridge.devices.amazfitbip.BipActivitySummary;
import nodomain.freeyourgadget.gadgetbridge.entities.Device;
import nodomain.freeyourgadget.gadgetbridge.entities.User;
import nodomain.freeyourgadget.gadgetbridge.export.GPXExporter;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityPoint;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityTrack;
import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions;
import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitbip.ActivityDetailsParser;
import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils;
import nodomain.freeyourgadget.gadgetbridge.util.FileUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ActivityDetailsParserTest extends TestBase {
private static final URL DETAILS_1 = ActivityDetailsParserTest.class.getClassLoader().getResource("ActivityDetailsDump1.txt");
private static final long MAX_DETAILS = 1024 * 1024;
private static Date baseTime;
@BeforeClass
public static void setUpSuite() throws Exception {
baseTime = DateTimeUtils.ISO_8601_FORMAT.parse("2017-01-20T14:00:00-00:00"); // yyyy-mm-dd'T'hh:mm:ssZ
}
@Test
public void testActivityDetails() throws Exception {
BipActivitySummary summary = createSummary();
ActivityDetailsParser parser = new ActivityDetailsParser(summary);
parser.setSkipCounterByte(true);
try (InputStream in = getContents(DETAILS_1)) {
ActivityTrack track = parser.parse(FileUtils.readAll(in, MAX_DETAILS));
assertEquals("SuperBand 2000", track.getDevice().getName());
assertEquals("Elvis", track.getUser().getName());
List<ActivityPoint> trackPoints = track.getTrackPoints();
assertEquals(972, trackPoints.size());
}
}
private BipActivitySummary createSummary() {
BipActivitySummary summary = new BipActivitySummary();
summary.setBaseLongitude(1);
summary.setBaseLatitude(1);
summary.setBaseAltitude(1);
summary.setStartTime(baseTime);
User dummyUser = new User(0L);
dummyUser.setName("Elvis");
summary.setName("testtrack");
summary.setUser(dummyUser);
Device device = new Device(0l);
device.setName("SuperBand 2000");
summary.setDevice(device);
return summary;
}
@Test
public void testGPXExport() throws Exception {
BipActivitySummary summary = createSummary();
int baseLongi = BLETypeConversions.toUint32((byte) 0xd6, (byte) 0xc4,(byte) 0x62,(byte) 0x02);
int baseLati = BLETypeConversions.toUint32((byte) 0xff, (byte) 0xa9, (byte) 0x61, (byte) 0x9);
int baseAlti = BLETypeConversions.toUint32((byte) 0x30, (byte) 0x0, (byte) 0x0, (byte) 0x0);
summary.setBaseLongitude(baseLongi);
summary.setBaseLatitude(baseLati);
summary.setBaseAltitude(baseAlti);
ActivityDetailsParser parser = new ActivityDetailsParser(summary);
parser.setSkipCounterByte(true);
try (InputStream in = getContents(DETAILS_1)) {
ActivityTrack track = parser.parse(FileUtils.readAll(in, MAX_DETAILS));
List<ActivityPoint> trackPoints = track.getTrackPoints();
assertEquals(972, trackPoints.size());
GPXExporter exporter = new GPXExporter();
exporter.setIncludeHeartRate(false);
exporter.setCreator(getClass().getName());
File targetFile = File.createTempFile("gadgetbridge-track", ".gpx");
System.out.println("Writing GPX file: " + targetFile);
exporter.performExport(track, targetFile);
assertTrue(targetFile.length() > 1024);
}
}
private InputStream getContents(URL hexFile) throws IOException {
return new HexToBinaryInputStream(hexFile.openStream());
}
}
|
package org.ovirt.engine.core.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.HypervisorType;
import org.ovirt.engine.core.common.businessentities.MigrationSupport;
import org.ovirt.engine.core.common.businessentities.OperationMode;
import org.ovirt.engine.core.common.businessentities.OriginType;
import org.ovirt.engine.core.common.businessentities.SessionState;
import org.ovirt.engine.core.common.businessentities.UsbPolicy;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VdsSelectionAlgorithm;
import org.ovirt.engine.core.common.businessentities.VmExitStatus;
import org.ovirt.engine.core.common.businessentities.VmOsType;
import org.ovirt.engine.core.common.businessentities.VmPauseStatus;
import org.ovirt.engine.core.common.businessentities.VmType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.DbFacadeUtils;
import org.ovirt.engine.core.utils.vmproperties.VmPropertiesUtils;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
/**
* <code>VmDAODbFacadeImpl</code> provides a concrete implementation of {@link VmDAO}. The functionality is code
* refactored out of {@link DbFacade}.
*/
public class VmDAODbFacadeImpl extends BaseDAODbFacade implements VmDAO {
@Override
public VM get(Guid id) {
return getCallsHandler().executeRead("GetVmByVmGuid", VMRowMapper.instance, getCustomMapSqlParameterSource()
.addValue("vm_guid", id));
}
@Override
public VM getById(Guid id) {
VM vm = get(id);
if (vm != null) {
vm.setInterfaces(DbFacade.getInstance().getVmNetworkInterfaceDAO().getAllForVm(vm.getId()));
}
return vm;
}
@Override
public VM getForHibernationImage(Guid id) {
return getCallsHandler().executeRead("GetVmByHibernationImageId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("image_id", id));
}
@Override
public VM getForImage(Guid id) {
return getCallsHandler().executeRead("GetVmByImageId", VMRowMapper.instance, getCustomMapSqlParameterSource()
.addValue("image_guid", id));
}
@Override
public VM getForImageGroup(Guid id) {
return getCallsHandler().executeRead("GetVmByImageGroupId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("image_group_id", id));
}
@Override
public List<VM> getAllForUser(Guid id) {
return getCallsHandler().executeReadList("GetVmsByUserId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("user_id", id));
}
@Override
public List<VM> getAllForUserWithGroupsAndUserRoles(Guid id) {
return getCallsHandler().executeReadList("GetVmsByUserIdWithGroupsAndUserRoles", VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("user_id", id));
}
@Override
public List<VM> getAllForAdGroupByName(String name) {
return getCallsHandler().executeReadList("GetVmsByAdGroupNames",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("ad_group_names", name));
}
@Override
public List<VM> getAllWithTemplate(Guid id) {
return getCallsHandler().executeReadList("GetVmsByVmtGuid",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("vmt_guid", id));
}
@Override
public List<VM> getAllRunningForVds(Guid id) {
return getCallsHandler().executeReadList("GetVmsRunningOnVds",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("vds_id", id));
}
@Override
public List<VM> getAllForDedicatedPowerClientByVds(Guid id) {
return getCallsHandler().executeReadList("GetVmsDedicatedToPowerClientByVdsId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("dedicated_vm_for_vds", id));
}
@Override
public Map<Guid, VM> getAllRunningByVds(Guid id) {
HashMap<Guid, VM> map = new HashMap<Guid, VM>();
for (VM vm : getAllRunningForVds(id)) {
map.put(vm.getId(), vm);
}
return map;
}
@Override
public List<VM> getAllUsingQuery(String query) {
return new SimpleJdbcTemplate(jdbcTemplate).query(query, VMRowMapper.instance);
}
@Override
public List<VM> getAllForStorageDomain(Guid id) {
return getCallsHandler().executeReadList("GetVmsByStorageDomainId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("storage_domain_id", id));
}
@Override
public List<VM> getAllVmsRelatedToQuotaId(Guid quotaId) {
return getCallsHandler().executeReadList("getAllVmsRelatedToQuotaId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("quota_id", quotaId));
}
@Override
public List<VM> getAllRunningForStorageDomain(Guid id) {
return getCallsHandler().executeReadList("GetRunningVmsByStorageDomainId",
VMRowMapper.instance,
getCustomMapSqlParameterSource()
.addValue("storage_domain_id", id));
}
@Override
public List<VM> getAll() {
return getCallsHandler().executeReadList("GetAllFromVms",
VMRowMapper.instance,
getCustomMapSqlParameterSource());
}
@Override
public void save(VM vm) {
getCallsHandler().executeModification("InsertVm", getCustomMapSqlParameterSource()
.addValue("description", vm.getdescription())
.addValue("mem_size_mb", vm.getmem_size_mb())
.addValue("os", vm.getos())
.addValue("vds_group_id", vm.getvds_group_id())
.addValue("vm_guid", vm.getId())
.addValue("vm_name", vm.getvm_name())
.addValue("vmt_guid", vm.getvmt_guid())
.addValue("num_of_monitors", vm.getnum_of_monitors())
.addValue("is_initialized", vm.getis_initialized())
.addValue("is_auto_suspend", vm.getis_auto_suspend())
.addValue("num_of_sockets", vm.getnum_of_sockets())
.addValue("cpu_per_socket", vm.getcpu_per_socket())
.addValue("usb_policy", vm.getusb_policy())
.addValue("time_zone", vm.gettime_zone())
.addValue("auto_startup", vm.getauto_startup())
.addValue("is_stateless", vm.getis_stateless())
.addValue("dedicated_vm_for_vds", vm.getdedicated_vm_for_vds())
.addValue("fail_back", vm.getfail_back())
.addValue("vm_type", vm.getvm_type())
.addValue("hypervisor_type", vm.gethypervisor_type())
.addValue("operation_mode", vm.getoperation_mode())
.addValue("nice_level", vm.getnice_level())
.addValue("default_boot_sequence",
vm.getdefault_boot_sequence())
.addValue("default_display_type", vm.getdefault_display_type())
.addValue("priority", vm.getpriority())
.addValue("iso_path", vm.getiso_path())
.addValue("origin", vm.getorigin())
.addValue("initrd_url", vm.getinitrd_url())
.addValue("kernel_url", vm.getkernel_url())
.addValue("kernel_params", vm.getkernel_params())
.addValue("migration_support",
vm.getMigrationSupport().getValue())
.addValue("predefined_properties", vm.getPredefinedProperties())
.addValue("userdefined_properties",
vm.getUserDefinedProperties())
.addValue("min_allocated_mem", vm.getMinAllocatedMem()));
}
@Override
public void remove(Guid id) {
getCallsHandler().executeModification("DeleteVm", getCustomMapSqlParameterSource()
.addValue("vm_guid", id));
}
private static final class VMRowMapper implements ParameterizedRowMapper<VM> {
public static final VMRowMapper instance = new VMRowMapper();
@Override
public VM mapRow(ResultSet rs, int rowNum) throws SQLException {
VM entity = new VM();
entity.setId(Guid.createGuidFromString(rs.getString("vm_guid")));
entity.setvm_name(rs.getString("vm_name"));
entity.setQuotaId(Guid.createGuidFromString(rs.getString("quota_id")));
entity.setQuotaName(rs.getString("quota_name"));
entity.setvm_mem_size_mb(rs.getInt("vm_mem_size_mb"));
entity.setvmt_guid(Guid.createGuidFromString(rs.getString("vmt_guid")));
entity.setvm_os(VmOsType.forValue(rs.getInt("vm_os")));
entity.setvm_description(rs.getString("vm_description"));
entity.setvds_group_id(Guid.createGuidFromString(rs.getString("vds_group_id")));
entity.setvm_domain(rs.getString("vm_domain"));
entity.setvm_creation_date(DbFacadeUtils.fromDate(rs.getTimestamp("vm_creation_date")));
entity.setvds_group_name(rs.getString("vds_group_name"));
entity.setvds_group_description(rs.getString("vds_group_description"));
entity.setvmt_name(rs.getString("vmt_name"));
entity.setvmt_mem_size_mb(rs.getInt("vmt_mem_size_mb"));
entity.setvmt_os(VmOsType.forValue(rs.getInt("vmt_os")));
entity.setvmt_creation_date(DbFacadeUtils.fromDate(rs.getTimestamp("vmt_creation_date")));
entity.setvmt_child_count(rs.getInt("vmt_child_count"));
entity.setvmt_num_of_cpus(rs.getInt("vmt_num_of_cpus"));
entity.setvmt_num_of_sockets(rs.getInt("vmt_num_of_sockets"));
entity.setvmt_cpu_per_socket(rs.getInt("vmt_cpu_per_socket"));
entity.setvmt_description(rs.getString("vmt_description"));
entity.setstatus(VMStatus.forValue(rs.getInt("status")));
entity.setvm_ip(rs.getString("vm_ip"));
entity.setvm_host(rs.getString("vm_host"));
entity.setvm_pid((Integer) rs.getObject("vm_pid"));
entity.setvm_last_up_time(DbFacadeUtils.fromDate(rs.getTimestamp("vm_last_up_time")));
entity.setvm_last_boot_time(DbFacadeUtils.fromDate(rs.getTimestamp("vm_last_boot_time")));
entity.setguest_cur_user_name(rs.getString("guest_cur_user_name"));
entity.setguest_last_login_time(DbFacadeUtils.fromDate(rs.getTimestamp("guest_last_login_time")));
entity.setguest_cur_user_id(NGuid.createGuidFromString(rs.getString("guest_cur_user_id")));
entity.setguest_last_logout_time(DbFacadeUtils.fromDate(rs.getTimestamp("guest_last_logout_time")));
entity.setguest_os(rs.getString("guest_os"));
entity.setcpu_user(rs.getDouble("cpu_user"));
entity.setcpu_sys(rs.getDouble("cpu_sys"));
entity.setelapsed_time(rs.getDouble("elapsed_time"));
entity.setusage_network_percent((Integer) rs.getObject("usage_network_percent"));
entity.setusage_mem_percent((Integer) rs.getObject("usage_mem_percent"));
entity.setusage_cpu_percent((Integer) rs.getObject("usage_cpu_percent"));
entity.setrun_on_vds(NGuid.createGuidFromString(rs.getString("run_on_vds")));
entity.setmigrating_to_vds(NGuid.createGuidFromString(rs.getString("migrating_to_vds")));
entity.setapp_list(rs.getString("app_list"));
entity.setdisplay((Integer) rs.getObject("display"));
entity.setVmPoolName(rs.getString("vm_pool_name"));
entity.setVmPoolId(NGuid.createGuidFromString(rs.getString("vm_pool_id")));
entity.setnum_of_monitors(rs.getInt("num_of_monitors"));
entity.setis_initialized(rs.getBoolean("is_initialized"));
entity.setis_auto_suspend(rs.getBoolean("is_auto_suspend"));
entity.setnum_of_sockets(rs.getInt("num_of_sockets"));
entity.setcpu_per_socket(rs.getInt("cpu_per_socket"));
entity.setusb_policy(UsbPolicy.forValue(rs.getInt("usb_policy")));
entity.setacpi_enable((Boolean) rs.getObject("acpi_enable"));
entity.setsession(SessionState.forValue(rs.getInt("session")));
entity.setdisplay_ip(rs.getString("display_ip"));
entity.setdisplay_type(DisplayType.forValue(rs.getInt("display_type")));
entity.setkvm_enable((Boolean) rs.getObject("kvm_enable"));
entity.setboot_sequence(BootSequence.forValue(rs.getInt("boot_sequence")));
entity.setrun_on_vds_name(rs.getString("run_on_vds_name"));
entity.settime_zone(rs.getString("time_zone"));
entity.setdisplay_secure_port((Integer) rs.getObject("display_secure_port"));
entity.setutc_diff((Integer) rs.getObject("utc_diff"));
entity.setauto_startup(rs.getBoolean("auto_startup"));
entity.setis_stateless(rs.getBoolean("is_stateless"));
entity.setdedicated_vm_for_vds(NGuid.createGuidFromString(rs.getString("dedicated_vm_for_vds")));
entity.setfail_back(rs.getBoolean("fail_back"));
entity.setlast_vds_run_on(NGuid.createGuidFromString(rs.getString("last_vds_run_on")));
entity.setclient_ip(rs.getString("client_ip"));
entity.setguest_requested_memory((Integer) rs.getObject("guest_requested_memory"));
entity.setvds_group_cpu_name(rs.getString("vds_group_cpu_name"));
entity.setvm_type(VmType.forValue(rs.getInt("vm_type")));
entity.setstorage_pool_id(Guid.createGuidFromString(rs.getString("storage_pool_id")));
entity.setstorage_pool_name(rs.getString("storage_pool_name"));
entity.sethypervisor_type(HypervisorType.forValue(rs.getInt("hypervisor_type")));
entity.setoperation_mode(OperationMode.forValue(rs.getInt("operation_mode")));
entity.setselection_algorithm(VdsSelectionAlgorithm.forValue(rs.getInt("selection_algorithm")));
entity.setTransparentHugePages(rs.getBoolean("transparent_hugepages"));
entity.setnice_level(rs.getInt("nice_level"));
entity.sethibernation_vol_handle(rs.getString("hibernation_vol_handle"));
entity.setdefault_boot_sequence(BootSequence.forValue(rs.getInt("default_boot_sequence")));
entity.setdefault_display_type(DisplayType.forValue(rs.getInt("default_display_type")));
entity.setpriority(rs.getInt("priority"));
entity.setiso_path(rs.getString("iso_path"));
entity.setorigin(OriginType.forValue(rs.getInt("origin")));
entity.setinitrd_url(rs.getString("initrd_url"));
entity.setkernel_url(rs.getString("kernel_url"));
entity.setkernel_params(rs.getString("kernel_params"));
entity.setvds_group_compatibility_version(new Version(rs.getString("vds_group_compatibility_version")));
entity.setExitMessage(rs.getString("exit_message"));
entity.setExitStatus(VmExitStatus.forValue(rs.getInt("exit_status")));
entity.setVmPauseStatus(VmPauseStatus.forValue(rs.getInt("pause_status")));
entity.setMigrationSupport(MigrationSupport.forValue(rs.getInt("migration_support")));
String predefinedProperties = rs.getString("predefined_properties");
String userDefinedProperties = rs.getString("userdefined_properties");
entity.setPredefinedProperties(predefinedProperties);
entity.setUserDefinedProperties(userDefinedProperties);
entity.setCustomProperties(VmPropertiesUtils.customProperties(predefinedProperties, userDefinedProperties));
entity.setMinAllocatedMem(rs.getInt("min_allocated_mem"));
entity.setHash(rs.getString("hash"));
return entity;
}
}
}
|
package org.jenkinsci.plugins.workflow.steps;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Run;
import jenkins.model.ArtifactManager;
import jenkins.util.VirtualFile;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static com.trilead.ssh2.util.IOUtils.*;
import hudson.AbortException;
/**
* @author Kohsuke Kawaguchi
*/
public class ArtifactUnarchiverStep extends AbstractSynchronousStepImpl<List<FilePath>> {
@StepContextParameter
private transient FilePath ws;
@StepContextParameter
private transient Run build;
/**
* Files to copy over.
*/
private Map<String, String> files;
@DataBoundSetter
private Run from;
@DataBoundConstructor
public ArtifactUnarchiverStep(Map<String,String> mapping) {
this.files = mapping;
}
@Override
protected List<FilePath> run(StepContext context) throws Exception {
// where to copy artifacts from?
Run r = from;
if (r==null) r=build;
ArtifactManager am = r.getArtifactManager();
List<FilePath> files = new ArrayList<FilePath>();
for (Entry<String, String> e : this.files.entrySet()) {
FilePath dst = new FilePath(ws,e.getValue());
String[] all = am.root().list(e.getKey());
if (all.length == 0) {
throw new AbortException("no artifacts to unarchive");
} else if (all.length==1 && all[0].equals(e.getKey())) {
// the source is a file
if (dst.isDirectory())
dst = dst.child(getFileName(all[0]));
files.add(copy(am.root().child(all[0]), dst));
} else {
// copy into a directory
for (String path : all) {
files.add(copy(am.root().child(path), dst.child(path)));
}
}
}
return files;
}
private FilePath copy(VirtualFile src, FilePath dst) throws IOException, InterruptedException {
InputStream in = src.open();
try {
dst.copyFrom(in);
} finally {
closeQuietly(in);
}
return dst;
}
/**
* Grabs the file name portion out of a path name.
*/
private String getFileName(String s) {
int idx = s.lastIndexOf('/');
if (idx>=0) s=s.substring(idx+1);
idx = s.lastIndexOf('\\');
if (idx>=0) s=s.substring(idx+1);
return s;
}
@Extension
public static class DescriptorImpl extends AbstractStepDescriptorImpl {
@Override
public String getFunctionName() {
return "unarchive";
}
@Override
public String getDisplayName() {
return "Copy archived artifacts into the workspace";
}
@Override
public Step newInstance(Map<String, Object> arguments) {
Object v = arguments.get("value");
if (v!=null) {
// sole string invocation like : unarchive('target/x.war')
return new ArtifactUnarchiverStep(Collections.singletonMap(v.toString(), "."));
}
// multi-argument invocations like: unarchive(mapping:['x.txt':'y.txt'], from:anotherBuild)
return super.newInstance(arguments);
}
}
}
|
package org.biojava.bio.structure.align.gui;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.align.StructureAlignment;
import org.biojava.bio.structure.align.StructureAlignmentFactory;
import org.biojava.bio.structure.align.ce.AbstractUserArgumentProcessor;
import org.biojava.bio.structure.align.gui.AlignmentGui;
import org.biojava.bio.structure.align.gui.ProgressThreadDrawer;
import org.biojava.bio.structure.align.util.ResourceManager;
import org.biojava.bio.structure.align.util.UserConfiguration;
import org.biojava.bio.structure.align.webstart.AligUIManager;
import org.biojava.bio.structure.align.webstart.WebStartMain;
import org.biojava.bio.structure.gui.util.PDBUploadPanel;
import org.biojava.bio.structure.gui.util.ScopSelectPanel;
import org.biojava.bio.structure.gui.util.StructurePairSelector;
/** A JFrame that allows to trigger a pairwise structure alignment,
* either from files in a directory,
* or after manual upload.
*
* @author Andreas Prlic
*
* @since 1.7
*
*
*
*/
public class AlignmentGui extends JFrame{
private final static long serialVersionUID =0l;
public static Logger logger = Logger.getLogger("org.biojava.spice");
StructureAlignment algorithm;
JButton abortB;
SelectPDBPanel tab1 ;
PDBUploadPanel tab2;
ScopSelectPanel tab3;
Thread thread;
AlignmentCalculationRunnable alicalc;
JTabbedPane masterPane;
JTabbedPane tabPane;
JProgressBar progress;
private DBSearchGUI dbsearch;
public static void main(String[] args){
AlignmentGui.getInstance();
}
static final ResourceManager resourceManager = ResourceManager.getResourceManager("ce");
private static final String MAIN_TITLE = "Pairwise Structure Alignment - Main - V." + resourceManager.getString("ce.version");;
private static final AlignmentGui me = new AlignmentGui();
public static AlignmentGui getInstance(){
AbstractUserArgumentProcessor.printAboutMe();
AligUIManager.setLookAndFeel();
if (! me.isVisible())
me.setVisible(true);
if ( ! me.isActive())
me.requestFocus();
return me;
}
public static AlignmentGui getInstanceNoVisibilityChange(){
return me;
}
private AlignmentGui() {
super();
thread = null;
JMenuBar menu = MenuCreator.initAlignmentGUIMenu(this);
this.setJMenuBar(menu);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle(MAIN_TITLE);
tab1 = new SelectPDBPanel();
tab2 = new PDBUploadPanel();
tab3 = new ScopSelectPanel();
// setup tabPane
tabPane = new JTabbedPane();
tabPane.addTab("Select PDB ID", null, tab1, "Select PDB ID to align");
tabPane.addTab("Domains",null, tab3,"Select domains to align.");
tabPane.addTab("Custom files",null, tab2,"Align your own files.");
Box hBoxAlgo = setupAlgorithm();
Box vBox = Box.createVerticalBox();
//vBox.add(hBoxAlgo);
vBox.add(tabPane);
vBox.add(Box.createGlue());
//vBox.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
masterPane = new JTabbedPane();
masterPane.addTab("Pairwise Comparison", vBox);
dbsearch = new DBSearchGUI();
masterPane.addTab("Database Search",dbsearch);
//JPanel dir = tab1.getPDBDirPanel(pdbDir);
Box vBoxMain = Box.createVerticalBox();
vBoxMain.add(hBoxAlgo);
// pairwise or db search
vBoxMain.add(masterPane);
// algorithm selection
// PDB install config
//vBoxMain.add(dir);
// buttons
vBoxMain.add(initButtons());
this.getContentPane().add(vBoxMain);
//SwingUtilities.updateComponentTreeUI( me);
this.pack();
this.setVisible(true);
}
private Box setupAlgorithm()
{
String[] algorithms = StructureAlignmentFactory.getAllAlgorithmNames();
try {
algorithm = StructureAlignmentFactory.getAlgorithm(algorithms[0]);
} catch (StructureException e){
e.printStackTrace();
}
JLabel algoLabel = new JLabel("Select alignment algorithm: ");
JComboBox algorithmList = new JComboBox(algorithms);
algorithmList.setSelectedIndex(0);
Action actionAlgorithm = new AbstractAction("Algorithm") {
public static final long serialVersionUID = 0l;
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
String algorithmName = (String)cb.getSelectedItem();
// Perform action...
//System.out.println("calc structure alignment");
updateAlgorithm(algorithmName);
}
};
algorithmList.addActionListener(actionAlgorithm);
Action paramAction = new AbstractAction("Parameters") {
public static final long serialVersionUID = 0l;
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
//System.out.println("calc structure alignment");
configureParameters();
}
};
JButton parameterButton = new JButton(paramAction);
Box hBoxAlgo = Box.createHorizontalBox();
hBoxAlgo.add(Box.createGlue());
hBoxAlgo.add(algoLabel);
hBoxAlgo.add(algorithmList);
hBoxAlgo.add(Box.createGlue());
hBoxAlgo.add(parameterButton);
hBoxAlgo.add(Box.createGlue());
return hBoxAlgo;
}
private Box initButtons(){
// Box hBox42 = Box.createHorizontalBox();
progress =new JProgressBar();
progress.setIndeterminate(false);
progress.setMaximumSize(new Dimension(10,100));
progress.setVisible(false);
// hBox42.add(Box.createGlue());
// hBox42.add(progress);
// hBox42.add(Box.createGlue());
// vBox.add(hBox42);
Action action1 = new AbstractAction("Align") {
public static final long serialVersionUID = 0l;
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
//System.out.println("calc structure alignment");
int selectedIndex = masterPane.getSelectedIndex();
if (selectedIndex == 0)
calcAlignment();
else if ( selectedIndex == 1)
calcDBSearch();
else {
System.err.println("Unknown TAB: " + selectedIndex);
}
}
};
JButton submitB = new JButton(action1);
Action action3 = new AbstractAction("Abort") {
public static final long serialVersionUID = 0l;
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
abortCalc();
}
};
abortB = new JButton(action3);
abortB.setEnabled(false);
Action action2 = new AbstractAction("Exit") {
public static final long serialVersionUID = 0l;
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
abortCalc();
dispose();
System.exit(0);
}
};
JButton closeB = new JButton(action2);
Box hBox = Box.createHorizontalBox();
hBox.add(closeB);
hBox.add(Box.createGlue());
hBox.add(progress);
hBox.add(abortB);
//hBox.add(Box.createGlue());
hBox.add(submitB);
return hBox;
}
protected void configureParameters() {
StructureAlignment algorithm = getStructureAlignment();
System.out.println("configure parameters for " + algorithm.getAlgorithmName());
// show a new config GUI
new ParameterGUI(algorithm);
}
public void cleanUp() {
if ( alicalc != null) {
alicalc.cleanup();
}
}
private void calcAlignment() {
int pos = tabPane.getSelectedIndex();
StructurePairSelector tab = null;
if (pos == 0 ){
tab = tab1;
} else if (pos == 1){
tab = tab3;
} else if (pos == 2){
tab = tab2;
}
try {
Structure s1 = tab.getStructure1();
Structure s2 = tab.getStructure2();
if ( s1 == null) {
System.err.println("please select structure 1");
return ;
}
if ( s2 == null) {
System.err.println("please select structure 2");
return;
}
String name1 = "custom1";
String name2 = "custom2";
if ( pos == 0){
name1 = tab1.getName1();
name2 = tab1.getName2();
} else {
name1 = s1.getName();
name2 = s2.getName();
}
System.out.println("aligning: " + name1 + " " + name2);
alicalc = new AlignmentCalc(this,s1,s2, name1, name2);
thread = new Thread(alicalc);
thread.start();
abortB.setEnabled(true);
progress.setIndeterminate(true);
ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress);
drawer.start();
} catch (StructureException e){
JOptionPane.showMessageDialog(null,"Could not align structures. Exception: " + e.getMessage());
}
}
private void calcDBSearch() {
JTabbedPane tabPane = dbsearch.getTabPane();
System.out.println("run DB search " + tabPane.getSelectedIndex());
Structure s = null;
boolean domainSplit = dbsearch.isDomainSplit();
StructurePairSelector tab = null;
int pos = tabPane.getSelectedIndex();
if (pos == 0 ){
tab = dbsearch.getSelectPDBPanel();
} else if (pos == 1){
tab = dbsearch.getScopSelectPanel();
} else if (pos == 2){
tab = dbsearch.getPDBUploadPanel();
}
try {
s = tab.getStructure1();
if ( s == null) {
System.err.println("please select structure 1");
return ;
}
} catch (Exception e){
e.printStackTrace();
}
String name1 = s.getName();
if ( name1 == null || name1.equals(""))
name1 = s.getPDBCode();
System.out.println("name1 in alig gui:" + name1);
String file = dbsearch.getOutFileLocation();
if ( file == null || file.equals("")){
JOptionPane.showMessageDialog(null,"Please select a directory to contain the DB search results.");
return;
}
UserConfiguration config = WebStartMain.getWebStartConfig();
int totalNrCPUs = Runtime.getRuntime().availableProcessors();
int useNrCPUs = 1;
if ( totalNrCPUs > 1){
Object[] options = new Integer[totalNrCPUs];
int posX = 0;
for ( int i = totalNrCPUs; i> 0 ; i
options[posX] = i;
posX++;
}
int n = JOptionPane.showOptionDialog(null,
"How many would you like to use for the calculations?",
"We detected " + totalNrCPUs + " processors on your system.",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if ( n < 0)
return;
useNrCPUs = (Integer) options[n];
System.out.println("will use " + useNrCPUs + " CPUs." );
}
System.out.println("using domainSplit data");
alicalc = new AlignmentCalcDB(this, s, name1,config,file, domainSplit);
alicalc.setNrCPUs(useNrCPUs);
abortB.setEnabled(true);
progress.setIndeterminate(true);
ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress);
drawer.start();
Thread t = new Thread(alicalc);
t.start();
}
public DBSearchGUI getDBSearch(){
return dbsearch;
}
public void notifyCalcFinished(){
abortB.setEnabled(false);
thread = null;
progress.setIndeterminate(false);
this.repaint();
}
private void abortCalc(){
System.err.println("Interrupting alignment ...");
if ( alicalc != null )
alicalc.interrupt();
notifyCalcFinished();
}
public StructureAlignment getStructureAlignment() {
return algorithm;
}
private void updateAlgorithm(String algorithmName) {
//String algorithmName = (String)algorithmList.getSelectedItem();
try {
algorithm = StructureAlignmentFactory.getAlgorithm(algorithmName);
} catch (StructureException ex){
ex.printStackTrace();
}
}
}
class ProgressThreadDrawer extends Thread {
JProgressBar progress;
static int interval = 300;
public ProgressThreadDrawer(JProgressBar progress) {
this.progress = progress;
}
public void run() {
progress.setVisible(true);
boolean finished = false;
while ( ! finished) {
try {
progress.repaint();
if ( ! progress.isIndeterminate() ){
finished =false;
break;
}
sleep(interval);
} catch (InterruptedException e){
}
progress.repaint();
}
progress.setVisible(false);
progress = null;
}
}
|
package org.biojava.bio.structure.align.model;
import java.io.StringWriter;
import java.util.List;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.ResidueNumber;
import org.biojava.bio.structure.StructureTools;
import org.biojava.bio.structure.align.ce.CeMain;
import org.biojava.bio.structure.align.ce.CeSideChainMain;
import org.biojava.bio.structure.align.fatcat.FatCatFlexible;
import org.biojava.bio.structure.align.seq.SmithWaterman3Daligner;
import org.biojava.bio.structure.align.util.AFPAlignmentDisplay;
import org.biojava.bio.structure.jama.Matrix;
public class AfpChainWriter
{
public static final String newline = System.getProperty("line.separator");
private static int LINELENGTH = 70;
public static String toFatCat(AFPChain afpChain, Atom[] ca1, Atom[] ca2)
{
boolean printLegend = true;
boolean longHeader = true;
boolean showHTML = false;
return toFatCatCore(afpChain, ca1, ca2, printLegend, longHeader, showHTML);
}
public static String toScoresList(AFPChain afpChain){
// see sippl On distance and similarity in fold space 2008 bioinformatics
StringWriter writer = new StringWriter();
writer.append("Sab (nr. equivalent residues): " );
writer.append(afpChain.getNrEQR()+"");
writer.append(newline);
writer.append("Dab (distance between folds a,b): ");
int dab = afpChain.getCa1Length()+afpChain.getCa2Length() - 2 * afpChain.getNrEQR();
writer.append(dab+"");
writer.append(newline);
writer.append("sab (relative similarity): ");
double sab = 2 * afpChain.getNrEQR() / (double)( afpChain.getCa1Length() + afpChain.getCa2Length());
writer.append(sab+"");
writer.append(newline);
writer.append("cab (coverage a): ");
double cab = afpChain.getNrEQR() / (double) afpChain.getCa1Length();
writer.append(cab+"");
writer.append(newline);
writer.append("cba (coverage b): ");
double cba = afpChain.getNrEQR() / (double) afpChain.getCa2Length();
writer.append(cba+"");
writer.append(newline);
writer.append("seq similarity: ");
writer.append(afpChain.getSimilarity()+"");
writer.append(newline);
writer.append("TM-score: ");
writer.append(afpChain.getTMScore()+"");
writer.append(newline);
return writer.toString();
}
public static String toFatCatCore(
AFPChain afpChain,
Atom[] ca1,
Atom[] ca2,
boolean printLegend, boolean longHeader, boolean showHTML){
if(!afpChain.isSequentialAlignment()) {
//TODO find some topology-independent output format
return "Can't display circular permutations";
}
String name1 = afpChain.getName1();
String name2 = afpChain.getName2();
int ca1Length = afpChain.getCa1Length();
int ca2Length = afpChain.getCa2Length();
int blockNum = afpChain.getBlockNum();
int totalLenIni = afpChain.getTotalLenIni();
double totalRmsdIni = afpChain.getTotalRmsdIni();
int optLength = afpChain.getOptLength();
double totalRmsdOpt = afpChain.getTotalRmsdOpt();
double chainRmsd = afpChain.getChainRmsd();
double alignScore = afpChain.getAlignScore();
int alnLength = afpChain.getAlnLength();
int gapLen = afpChain.getGapLen();
List<AFP> afpSet = afpChain.getAfpSet();
double similarity = afpChain.getSimilarity();
double identity = afpChain.getIdentity();
if (similarity <0 || identity < 0){
afpChain.calcSimilarity();
similarity = afpChain.getSimilarity();
identity = afpChain.getIdentity();
}
String algorithmName = afpChain.getAlgorithmName();
//String version = afpChain.getVersion();
double probability = afpChain.getProbability();
int afpNum = afpSet.size();
int[] blockGap = afpChain.getBlockGap();
double[] blockScore = afpChain.getBlockScore();
double[] blockRmsd = afpChain.getBlockRmsd();
int[] blockSize = afpChain.getBlockSize();
int alnbeg1 = afpChain.getAlnbeg1();
int alnbeg2 = afpChain.getAlnbeg2();
char[] alnseq1 = afpChain.getAlnseq1();
char[] alnseq2 = afpChain.getAlnseq2();
char[] alnsymb = afpChain.getAlnsymb();
// == end of extractation of data values from afpChain
StringBuffer txt = new StringBuffer();
if ( longHeader) {
txt.append(String.format("Align %s.pdb %d with %s.pdb %d", name1, ca1Length, name2, ca2Length));
}
else {
txt.append(String.format("Align %s.pdb Length1: %d with %s.pdb Length2: %d", name1, ca1Length, name2, ca2Length));
}
txt.append(newline);
if ( afpChain.isShortAlign()){
txt.append("Short match");
return txt.toString();
}
//txt.append(String.format("raw-score: %.2f norm.-score: %.2f ", alignScore, normAlignScore));
if ( longHeader ) {
txt.append(String.format( "Twists %d ini-len %d ini-rmsd %.2f opt-equ %d opt-rmsd %.2f chain-rmsd %.2f Score %.2f align-len %d gaps %d (%.2f%%)",
blockNum - 1, totalLenIni, totalRmsdIni, optLength, totalRmsdOpt, chainRmsd, alignScore,
alnLength, gapLen, (100.0 * (double)gapLen/(double)alnLength)) );
txt.append(newline);
} else {
if ( ! longHeader)
printScore(txt,algorithmName,probability,longHeader);
printScoresInLines(afpChain, blockNum, optLength, totalRmsdOpt, alignScore, alnLength, gapLen, identity, similarity,txt);
}
//txt.append(String.format("P-value %.2e Afp-num %d Identity %.2f%% Similarity %.2f%% norm.-score: %.2f"+newline, probability, afpNum, identity * 100, similarity * 100, normAlignScore));
if ( longHeader) {
printScore(txt,algorithmName,probability,longHeader);
txt.append(String.format("Afp-num %d Identity %.2f%% Similarity %.2f%%", afpNum, identity * 100, similarity * 100));
txt.append(newline);
}
int i;
double gap;
if ( longHeader ){
int fragLen = 8 ; // FatCatParameters.DEFAULT_FRAGLEN;
for(i = 0; i < blockNum; i ++) {
gap = (double)blockGap[i] /( (double)blockGap[i] + fragLen * blockSize[i]);
txt.append(String.format( "Block %2d afp %2d score %5.2f rmsd %5.2f gap %d (%.2f%%)",
i, blockSize[i], blockScore[i], blockRmsd[i], blockGap[i], gap));
txt.append(newline);
}
}
int linelen = 70;
String a;
String b;
String c;
int t = 0;
int ap = alnbeg1;
int bp = alnbeg2;
int k, len;
while((alnLength - t) > 0) {
if(alnLength - t > linelen) len = linelen;
else len = alnLength - t;
//System.err.println("t,len:"+t+":"+len);
String lseq1 = new String(alnseq1).substring(t,t+len);
String lseq2 = new String(alnseq2).substring(t,t+len);
String lsymb = new String(alnsymb).substring(t,t+len);
//System.err.println("B:" + b);
// check conservation and color accordingly, if requested by user.
if ( showHTML ) {
a = "";
b = "";
c = "";
// <span class=\"m\">|</span> ... Structurally equivalent and identical residues
// <span class=\"sm\">:</span> ... Structurally equivalent and similar residues
// <span class=\"qg\">.</span> ... Structurally equivalent, but not similar residues.
for (int pos = 0 ; pos < lseq1.length() ; pos ++){
char c1 = lseq1.charAt(pos);
char c2 = lseq2.charAt(pos);
char cl = lsymb.charAt(pos);
if ( c1 == c2 ){
a += "<span class=\"m\">" + c1 + "</span>";
b += "<span class=\"m\">" + c2 + "</span>";
c += "<span class=\"m\">" + cl + "</span>";
} else if ( cl != ' ') {
a += "<span class=\"sm\">" + c1 + "</span>";
b += "<span class=\"sm\">" + c2 + "</span>";
c += "<span class=\"sm\">" + cl + "</span>";
} else {
a += "<span class=\"qg\">" + c1 + "</span>";
b += "<span class=\"qg\">" + c2 + "</span>";
c += "<span class=\"qg\">" + cl + "</span>";
}
if(c1 != '-') ap ++;
if(c2 != '-') bp ++;
}
} else {
a = lseq1;
b = lseq2;
c = lsymb;
}
txt.append(newline);
if ( longHeader )
txt.append(String.format("%14s", " "));
else
txt.append(String.format("%14s", " "));
if ( longHeader ) {
for(k = 10; k <= len; k += 10)
txt.append(" . :");
if(k <= len + 5) txt.append(" .");
} else {
for(k = 10; k <= len; k += 10)
txt.append("
if(k <= len + 5) txt.append("
}
if ( ap >= ca1.length)
break;
if ( bp >= ca2.length)
break;
String pdb1 = ca1[ap].getGroup().getResidueNumber().toString();
String pdb2 = ca2[bp].getGroup().getResidueNumber().toString();
txt.append(newline);
txt.append(String.format("Chain 1:%5s %s"+newline +"%14s%s"+newline+"Chain 2:%5s %s",
pdb1, a, " ", c, pdb2, b));
txt.append(newline);
if ( ! showHTML){
for(k = 0; k < len; k ++) {
if(a.charAt(k) != '-') ap ++;
if(b.charAt(k) != '-') bp ++;
}
}
t += len;
}
txt.append(newline);
if ( printLegend ){
if ( algorithmName.equalsIgnoreCase(CeMain.algorithmName) ||
algorithmName.equalsIgnoreCase(SmithWaterman3Daligner.algorithmName)){
txt.append("Note: positions are from PDB; | means alignment of identical amino acids, : of similar amino acids ");
} else {
txt.append("Note: positions are from PDB; the numbers between alignments are block index");
}
txt.append(newline);
}
return txt.toString();
}
private static void printScoresInLines(AFPChain afpChain, int blockNum, int optLength, double totalRmsdOpt, double alignScore,
int alnLength, int gapLen, double identity, double similarity, StringBuffer txt)
{
if ( blockNum - 1 > 0) {
txt.append(String.format( "Twists %d ", blockNum -1 ));
txt.append(newline);
}
txt.append(String.format("Equ: %d ", optLength));
txt.append(newline);
txt.append(String.format("RMSD: %.2f ", totalRmsdOpt));
txt.append(newline);
txt.append(String.format("Score: %.2f ", alignScore));
txt.append(newline);
txt.append(String.format("Align-len: %d ", alnLength));
txt.append(newline);
txt.append(String.format("Gaps: %d (%.2f%%)",
gapLen, (100.0 * (double)gapLen/(double)alnLength)) );
txt.append(newline);
if ( afpChain.getTMScore() >= 0) {
txt.append(String.format("TM-score: %.2f",afpChain.getTMScore()));
txt.append(newline);
}
txt.append(newline);
txt.append(String.format("Identity: %.2f%% ", identity * 100 ));
txt.append(newline);
txt.append(String.format("Similarity: %.2f%%", similarity * 100));
txt.append(newline);
}
private static void printScore(StringBuffer txt,
String algorithmName,
double probability,
boolean longHeader)
{
if ( algorithmName.equalsIgnoreCase(CeMain.algorithmName) || algorithmName.equalsIgnoreCase(CeSideChainMain.algorithmName) ){
txt.append(String.format("Z-score %.2f ", probability));
if ( ! longHeader)
txt.append(newline);
} else if ( algorithmName.equalsIgnoreCase(SmithWaterman3Daligner.algorithmName)) {
} else {
if ( longHeader ){
txt.append(String.format("P-value %.2e ",probability));
} else {
txt.append(String.format("P-value: %.2e ",probability));
txt.append(newline);
}
}
}
/**
* Prints the afpChain as a nicely formatted alignment, including alignment
* statistics, the aligned sequences themselves, and information about the
* superposition.
* @param afpChain
* @param ca1
* @param ca2
* @return a String representation as it is used on the RCSB PDB web site for display.
*/
public static String toWebSiteDisplay(AFPChain afpChain, Atom[] ca1, Atom[] ca2){
if ( afpChain.getAlgorithmName().equalsIgnoreCase(FatCatFlexible.algorithmName)) {
boolean printLegend = true;
boolean longHeader = true;
boolean showHTML = true;
String msg = toFatCatCore(afpChain,ca1,ca2,printLegend,longHeader,showHTML);
return msg;
}
boolean showSeq = true;
AFPAlignmentDisplay.getAlign(afpChain, ca1, ca2, showSeq);
// String msg= toFatCatCore(afpChain,ca1,ca2, printLegend,longHeader);
String msg = toPrettyAlignment(afpChain, ca1, ca2, true);
msg = msg + newline +
" <span class=\"m\">|</span> ... Structurally equivalent and identical residues " + newline +
" <span class=\"sm\">:</span> ... Structurally equivalent and similar residues " + newline +
" <span class=\"qg\">.</span> ... Structurally equivalent, but not similar residues. " + newline;
msg += newline;
msg += " To calculate the coordinates of chain 2 aligned on chain 1 apply the following transformation: ";
msg += newline;
msg += newline;
msg += toRotMat(afpChain);
return msg;
}
private static String toPrettyAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2, boolean showHTML) {
String name1 = afpChain.getName1();
String name2 = afpChain.getName2();
int ca1Length = afpChain.getCa1Length();
int ca2Length = afpChain.getCa2Length();
int blockNum = afpChain.getBlockNum();
int optLength = afpChain.getOptLength();
double totalRmsdOpt = afpChain.getTotalRmsdOpt();
double alignScore = afpChain.getAlignScore();
int alnLength = afpChain.getAlnLength();
int gapLen = afpChain.getGapLen();
double similarity = afpChain.getSimilarity();
double identity = afpChain.getIdentity();
if (similarity <0 || identity < 0){
afpChain.calcSimilarity();
similarity = afpChain.getSimilarity();
identity = afpChain.getIdentity();
}
String algorithmName = afpChain.getAlgorithmName();
//String version = afpChain.getVersion();
double probability = afpChain.getProbability();
// == end of extractation of data values from afpChain
StringBuffer txt = new StringBuffer();
txt.append(String.format("Align %s.pdb Length1: %d with %s.pdb Length2: %d", name1, ca1Length, name2, ca2Length));
txt.append(newline);
if ( afpChain.isShortAlign()){
txt.append("Short match");
return txt.toString();
}
printScore(txt, algorithmName, probability, false);
printScoresInLines(afpChain, blockNum, optLength, totalRmsdOpt, alignScore, alnLength, gapLen,identity, similarity, txt);
txt.append(newline);
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
int i, j,p1, p2;
int k;
int p1b = 0;
int p2b = 0;
int len = 0;
StringWriter alnseq1 = new StringWriter();
StringWriter alnseq2 = new StringWriter();
StringWriter alnsymb = new StringWriter();
StringWriter header1 = new StringWriter();
StringWriter footer1 = new StringWriter();
StringWriter header2 = new StringWriter();
StringWriter footer2 = new StringWriter();
StringWriter block = new StringWriter();
for(i = 0; i < blockNum; i ++) {
for(j = 0; j < optLen[i]; j ++) {
p1 = optAln[i][0][j];
p2 = optAln[i][1][j];
// System.out.println(p1 + " " + p2 + " " + footer2.toString());
if ( len == 0){
//the first position of sequence in alignment
formatStartingText(p1,p2,header1,header2,footer1,footer2,ca1,ca2);
} else {
// check for gapped region
int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1);
for(k = 0; k < lmax; k ++) {
formatGappedRegion(ca1, ca2, txt, p1, p2, k, p1b, p2b, alnseq1, alnseq2, alnsymb, header1, footer1, header2,
footer2, block,len, showHTML);
len++;
doLenCheck(len,txt,header1,header2,alnseq1,alnsymb,alnseq2,footer1, footer2,block, showHTML) ;
}
}
// ALIGNED REGION
// System.out.println(len + " >" + header1.toString() +"< ");
// System.out.println(len + " >" + header2.toString() +"< ");
// System.out.println(len + " >" + alnseq1.toString() +"< ");
// System.out.println(len + " >" + alnsymb.toString() +"< ");
// System.out.println(len + " >" + alnseq2.toString() +"< ");
// System.out.println(len + " >" + footer1.toString() +"< ");
formatAlignedRegion(ca1, ca2, p1, p2, alnseq1, alnseq2, alnsymb, header1, footer1, header2, footer2, block,len, showHTML);
// System.out.println(len + " >" + header1.toString() +"< ");
// System.out.println(len + " >" + header2.toString() +"< ");
// System.out.println(len + " >" + alnseq1.toString() +"< ");
// System.out.println(len + " >" + alnsymb.toString() +"< ");
// System.out.println(len + " >" + alnseq2.toString() +"< ");
// System.out.println(len + " >" + footer1.toString() +"< ");
len++;
doLenCheck(len,txt,header1,header2,alnseq1,alnsymb,alnseq2,footer1, footer2,block, showHTML) ;
p1b = p1;
p2b = p2;
//header1.append(newline);
//header2.append(newline);
}
}
alnLength = len;
doLenCheck(LINELENGTH,txt,header1,header2,alnseq1,alnsymb,alnseq2,footer1, footer2,block, showHTML);
return txt.toString();
}
/**
* Prints the alignment in the simplest form: a list of aligned residues.
* Format is one line per residue pair, tab delimited:
* <ul><li>1. PDB number. Includes insertion code</li>
* <li>1. Chain.</li>
* <li>1. Amino Acid. Three letter code.</li>
* <li>2. PDB number.</li>
* <li>2. Chain.</li>
* <li>2. Amino Acid.</li>
* </ul>
* example:
* <code>152 A ALA 161S A VAL</code>
* <p>Note that this format loses information about blocks.
* @param afpChain
* @param ca1
* @param ca2
* @return a String representation of the aligned pairs.
*/
public static String toAlignedPairs(AFPChain afpChain, Atom[] ca1, Atom[] ca2) {
StringWriter pairs = new StringWriter();
//Write structure names & PDB codes
pairs.append("#Struct1:\t");
pairs.append(afpChain.getName1());
pairs.append("\n");
pairs.append("#Struct2:\t");
pairs.append(afpChain.getName2());
pairs.append("\n");
//Write optimally aligned pairs
pairs.append("#Num1\tChain1\tAA1\tNum2\tChain2\tAA2\n");
int[][][] optAln = afpChain.getOptAln();
int[] blockLen = afpChain.getOptLen();
for( int block=0;block<afpChain.getBlockNum(); block++) {
for(int i=0;i<blockLen[block];i++) {
Atom atom1 = ca1[ optAln[block][0][i] ];
Atom atom2 = ca2[ optAln[block][1][i] ];
pairs.append(atom1.getGroup().getResidueNumber().toString());
pairs.append('\t');
pairs.append(atom1.getGroup().getChain().getChainID());
pairs.append('\t');
pairs.append(atom1.getGroup().getPDBName());
pairs.append('\t');
pairs.append(atom2.getGroup().getResidueNumber().toString());
pairs.append('\t');
pairs.append(atom2.getGroup().getChain().getChainID());
pairs.append('\t');
pairs.append(atom2.getGroup().getPDBName());
pairs.append('\n');
}
}
return pairs.toString();
}
private static void formatGappedRegion(Atom[] ca1, Atom[] ca2, StringBuffer txt, int p1, int p2, int k, int p1b, int p2b,
StringWriter alnseq1, StringWriter alnseq2, StringWriter alnsymb, StringWriter header1, StringWriter footer1,
StringWriter header2, StringWriter footer2, StringWriter block, int len, boolean formatHTML)
{
// DEAL WITH GAPS
int tmppos = (p1 - p1b - 1);
block.append("g");
int pos1=p1b+1+k ;
char oneletter1 = ' ';
try {
oneletter1 = getOneLetter(ca1[pos1].getGroup());
} catch (Exception e){}
int pos2=p2b+1+k;
char oneletter2 = ' ';
try {
oneletter2 = getOneLetter(ca2[pos2].getGroup());
} catch (Exception e){}
if(k >= tmppos) {
//alnseq1[len] = '-';
if ( formatHTML){
alnseq1.append("<span class=\"qg\">-</span>");
header1.append(" ");
header2.append(" ");
} else {
alnseq1.append('-');
header1.append(" ");
header2.append(" ");
}
}
else {
if ( formatHTML){
alnseq1.append(getPrefix(oneletter1,oneletter2,0));
}
alnseq1.append(oneletter1);
if (formatHTML){
alnseq1.append("</span>");
}
formatPosition(pos1,ca1, len, header1, header2);
}
if(k >= (p2 - p2b - 1)) {
//alnseq2[len] = '-';
if ( formatHTML){
alnseq2.append("<span class=\"qg\">-</span>");
footer1.append(" ");
footer2.append(" ");
} else {
alnseq2.append('-');
footer1.append(" ");
footer2.append(" ");
}
}
else {
if ( formatHTML){
alnseq2.append(getPrefix(oneletter1,oneletter2,1));
}
alnseq2.append(oneletter2);
if (formatHTML){
alnseq2.append("</span>");
}
formatPosition(pos2, ca2, len, footer1, footer2);
}
//alnsymb[len ++] = ' ';
alnsymb.append(' ');
}
private static CharSequence getPrefix(char oneletter1, char oneletter2,
int i) {
if ( oneletter1 == '-' || oneletter2 == '-' ) {
// a gap in the alignment.
// label as mismatch
return "<span class=\"qg\">";
}
// an aligned position
if ( oneletter1 == oneletter2)
return "<span class=\"m\">";
double score = AFPAlignmentDisplay.aaScore(oneletter1,oneletter2);
if ( score > 0 )
return "<span class=\"sm\">";
// not similar
return "<span class=\"qg\">";
}
private static void formatPosition(int pos1, Atom[] ca, int len, StringWriter header1, StringWriter header2)
{
int linePos = len % LINELENGTH;
if ( header1.getBuffer().length() < linePos) {
// fill up the buffer, we are probably shortly after the start...
for ( int i = header1.getBuffer().length() ; i< linePos ; i++){
header1.append(" ");
}
}
Atom a = ca[pos1];
Group g = a.getGroup();
ResidueNumber residueNumber = g.getResidueNumber();
pos1 = residueNumber.getSeqNum();
boolean hasInsertionCode = false;
if ( residueNumber.getInsCode() != null) {
hasInsertionCode = true;
}
if ( (pos1 %10 == 0) && ( ! hasInsertionCode)) {
CharSequence display = getPDBPos(a);
boolean ignoreH1 = false;
// make sure we don't have a problem with the left boundary...
if ( header1.getBuffer().length()-1 > linePos) {
ignoreH1 = true;
System.out.println("Ignore h1: " + len + " " + header1.getBuffer().length() + " linePos: " + linePos +" >" + header1.toString() +"<");
}
//System.out.println(len + " p1:" + tmp + " = " + pos1 + " " + " " + display + " " + ignoreH1);
if ( ! ignoreH1) {
header1.append(String.format("%-10s",display ));
header2.append("|");
} else {
header2.append("|");
}
} else if ( hasInsertionCode){
Character insCode = g.getResidueNumber().getInsCode();
if ( insCode != null)
header2.append(insCode);
else {
header2.append("!");
}
} else if ( ((pos1) %5 ) == 0 && len > 5) {
header2.append(".");
} else {
if ( len > 0)
header2.append(" ");
}
}
private static void formatAlignedRegion(Atom[] ca1, Atom[] ca2, int p1, int p2,
StringWriter alnseq1, StringWriter alnseq2,
StringWriter alnsymb, StringWriter header1, StringWriter footer1, StringWriter header2,
StringWriter footer2, StringWriter block, int len, boolean showHTML)
{
char c1 = getOneLetter(ca1[p1].getGroup());
char c2 = getOneLetter(ca2[p2].getGroup());
double score = AFPAlignmentDisplay.aaScore(c1,c2);
if ( showHTML) {
alnseq1.append(getPrefix(c1,c2, 0));
alnseq2.append(getPrefix(c1,c2, 1));
}
alnseq1.append(c1);
alnseq2.append(c2);
if ( showHTML){
alnseq1.append("</span>");
alnseq2.append("</span>");
}
if ( c1 == c2){
if ( showHTML){
alnsymb.append("<span class=\"m\">|</span>");
} else {
alnsymb.append('|');
}
//alnsymb[len ++] = '|';
} else {
if ( score > 1) {
if ( showHTML){
alnsymb.append( "<span class=\"sm\">:</span>");
} else {
alnsymb.append( ':');
}
}
else {
if ( showHTML)
alnsymb.append( "<span class=\"qg\">.</span>");
else
alnsymb.append( '.');
}
}
formatPosition(p1, ca1,len, header1, header2);
formatPosition(p2,ca2,len, footer1, footer2);
}
private static void formatStartingText(int p1, int p2, StringWriter header1, StringWriter header2, StringWriter footer1,
StringWriter footer2, Atom[] ca1, Atom[] ca2)
{
header1.append(String.format("%-10s", getPDBPos(ca1[p1])));
header2.append("|");
footer1.append(String.format("%-10s", getPDBPos(ca2[p2])));
footer2.append("|");
}
private static boolean doLenCheck(int len, StringBuffer txt, StringWriter header1, StringWriter header2, StringWriter alnseq1,
StringWriter alnsymb, StringWriter alnseq2, StringWriter footer1, StringWriter footer2, StringWriter block, boolean formatHTML)
{
if ( len % LINELENGTH == 0) {
//txt.append("|");
txt.append(header1);
//txt.append("|");
txt.append(newline);
//txt.append("|");
txt.append(header2);
//txt.append("|");
txt.append(newline);
//txt.append("|");
txt.append(alnseq1);
//txt.append("|");
txt.append(newline);
//txt.append("|");
txt.append(alnsymb);
// txt.append(newline);
// txt.append(block);
//txt.append("|");
txt.append(newline);
//txt.append("|");
txt.append(alnseq2);
//txt.append("|");
txt.append(newline);
//txt.append("|");
txt.append(footer2);
//txt.append("|");
txt.append(newline);
//txt.append("|");
txt.append(footer1);
//txt.append("|");
txt.append(newline);
txt.append(newline);
txt.append(newline);
if (formatHTML ) {
int len1 = alnseq1.getBuffer().length();
int len2 = alnseq2.getBuffer().length();
int lens = alnsymb.getBuffer().length();
alnseq1.getBuffer().replace(0, len1, "");
alnseq2.getBuffer().replace(0, len2, "");
alnsymb.getBuffer().replace(0, lens, "");
header1.getBuffer().replace(0, LINELENGTH, "");
header2.getBuffer().replace(0, LINELENGTH , "");
footer1.getBuffer().replace(0, LINELENGTH, "");
footer2.getBuffer().replace(0, LINELENGTH, "");
block.getBuffer().replace(0, LINELENGTH, "");
} else {
alnseq1.getBuffer().replace(0, LINELENGTH, "");
alnseq2.getBuffer().replace(0, LINELENGTH, "");
alnsymb.getBuffer().replace(0, LINELENGTH, "");
header1.getBuffer().replace(0, LINELENGTH, "");
header2.getBuffer().replace(0, LINELENGTH , "");
footer1.getBuffer().replace(0, LINELENGTH, "");
footer2.getBuffer().replace(0, LINELENGTH, "");
block.getBuffer().replace(0, LINELENGTH, "");
}
StringBuffer buf = header1.getBuffer();
for ( int i=0;i<buf.length();i++){
char c = buf.charAt(i);
if ( c != ' '){
buf.setCharAt(i, ' ');
}
}
buf = footer1.getBuffer();
for ( int i=0;i<buf.length();i++){
char c = buf.charAt(i);
if ( c != ' '){
buf.setCharAt(i, ' ');
}
}
return true;
}
return false;
}
private static CharSequence getPDBPos(Atom atom)
{
Group g = atom.getGroup();
if ( g!= null){
Chain c = g.getChain();
if (c != null){
return g.getResidueNumber().toString()+":" + c.getChainID() ;
//return g.getPDBCode()+":" + c.getName() + "." + getOneLetter(g) ;
}
}
return "!";
}
private static char getOneLetter(Group g){
try {
Character c = StructureTools.get1LetterCode(g.getPDBName());
return c;
} catch (Exception e){
return 'X';
}
}
public static String toDBSearchResult(AFPChain afpChain)
{
StringBuffer str = new StringBuffer();
str.append(afpChain.getName1());
str.append("\t");
str.append(afpChain.getName2());
str.append("\t");
str.append(String.format("%.2f",afpChain.getAlignScore()));
str.append("\t");
if ( afpChain.getAlgorithmName().equalsIgnoreCase(CeMain.algorithmName)){
str.append(String.format("%.2f",afpChain.getProbability()));
} else {
str.append(String.format("%.2e",afpChain.getProbability()));
}
str.append("\t");
str.append(String.format("%.2f",afpChain.getTotalRmsdOpt()));
str.append("\t");
str.append(afpChain.getCa1Length());
str.append("\t");
str.append(afpChain.getCa2Length());
str.append("\t");
str.append(afpChain.getSimilarity1());
str.append("\t");
str.append(afpChain.getSimilarity2());
str.append("\t");
str.append(newline);
return str.toString();
}
public static String toRotMat(AFPChain afpChain)
{
Matrix[] blockRotationMatrix = afpChain.getBlockRotationMatrix();
int blockNum = afpChain.getBlockNum();
Atom[] blockShiftVector = afpChain.getBlockShiftVector();
StringBuffer txt = new StringBuffer();
if ( blockRotationMatrix == null || blockRotationMatrix.length < 1)
return "";
for ( int blockNr = 0 ; blockNr < blockNum ; blockNr++){
Matrix m = blockRotationMatrix[blockNr];
Atom shift = blockShiftVector[blockNr];
if ( blockNum > 1) {
txt.append("Operations for block " );
txt.append(blockNr);
txt.append(newline);
}
String origString = "orig";
if ( blockNr > 0)
origString = (blockNr)+"";
txt.append(String.format(" X"+(blockNr+1)+" = (%9.6f)*X"+ origString +" + (%9.6f)*Y"+ origString +" + (%9.6f)*Z"+ origString +" + (%12.6f)",m.get(0,0),m.get(1,0), m.get(2,0), shift.getX()));
txt.append( newline);
txt.append(String.format(" Y"+(blockNr+1)+" = (%9.6f)*X"+ origString +" + (%9.6f)*Y"+ origString +" + (%9.6f)*Z"+ origString +" + (%12.6f)",m.get(0,1),m.get(1,1), m.get(2,1), shift.getY()));
txt.append( newline);
txt.append(String.format(" Z"+(blockNr+1)+" = (%9.6f)*X"+ origString +" + (%9.6f)*Y"+ origString +" + (%9.6f)*Z"+ origString +" + (%12.6f)",m.get(0,2),m.get(1,2), m.get(2,2), shift.getZ()));
txt.append(newline);
}
return txt.toString();
}
public static String toCE(AFPChain afpChain, Atom[] ca1, Atom[] ca2)
{
String name1 = afpChain.getName1();
String name2 = afpChain.getName2();
int optLength = afpChain.getOptLength();
double totalRmsdOpt = afpChain.getTotalRmsdOpt();
int alnLength = afpChain.getAlnLength();
int gapLen = afpChain.getGapLen();
double similarity = afpChain.getSimilarity();
double identity = afpChain.getIdentity();
if (similarity == -1 || identity == -1){
afpChain.calcSimilarity();
similarity = afpChain.getSimilarity();
identity = afpChain.getIdentity();
}
double probability = afpChain.getProbability();
int alnbeg1 = afpChain.getAlnbeg1();
int alnbeg2 = afpChain.getAlnbeg2();
char[] alnseq1 = afpChain.getAlnseq1();
char[] alnseq2 = afpChain.getAlnseq2();
long calculationTime = afpChain.getCalculationTime();
// == end of extractation of data values from afpChain
StringBuffer txt = new StringBuffer();
txt.append("Chain 1: ");
txt.append(name1);
txt.append(" (Size=");
txt.append(ca1.length);
txt.append(")");
txt.append(newline);
txt.append("Chain 2: ");
txt.append(name2);
txt.append(" (Size=");
txt.append(ca2.length);
txt.append(")");
txt.append(newline);
txt.append(newline);
txt.append(String.format("Alignment length = %d Rmsd = %.2fA Z-Score = %.1f",optLength,totalRmsdOpt,probability));
txt.append(String.format(" Gaps = %d(%.1f%%) CPU = %d ms. Sequence identities = %.1f%%",gapLen,( gapLen*100.0/optLength),calculationTime,identity*100));
int linelen = 70;
String a;
String b;
int t = 0;
int ap = alnbeg1;
int bp = alnbeg2;
int k, len;
while((alnLength - t) > 0) {
if(alnLength - t > linelen) len = linelen;
else len = alnLength - t;
//System.err.println("t,len:"+t+":"+len);
a = new String(alnseq1).substring(t,t+len);
b = new String(alnseq2).substring(t,t+len);
//System.err.println("B:" + b);
/*
txt.append(newline);
txt.append(String.format("%14s", " "));
for(k = 10; k <= len; k += 10)
txt.append(" . :");
if(k <= len + 5) txt.append(" .");
*/
//String pdb1 = ca1[ap].getParent().getPDBCode();
//String pdb2 = ca2[bp].getParent().getPDBCode();
txt.append(newline);
txt.append(String.format("Chain 1:%5s %s"+newline+"Chain 2:%5s %s",
(ap+1), a, (bp+1), b));
txt.append(newline);
for(k = 0; k < len; k ++) {
if(a.charAt(k) != '-') ap ++;
if(b.charAt(k) != '-') bp ++;
}
t += len;
}
txt.append(newline);
txt.append(toRotMat(afpChain));
return txt.toString();
}
}
|
package org.apache.ode.bpel.engine.cron;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.xml.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.bpel.common.InstanceFilter;
import org.apache.ode.bpel.dao.BpelDAOConnection;
import org.apache.ode.bpel.dao.FilteredInstanceDeletable;
import org.apache.ode.bpel.engine.Contexts;
import org.apache.ode.bpel.engine.BpelServerImpl.ContextsAware;
import org.apache.ode.bpel.iapi.ProcessConf.CLEANUP_CATEGORY;
import org.apache.ode.bpel.iapi.ProcessConf.CleanupInfo;
import org.apache.ode.bpel.iapi.Scheduler.MapSerializableRunnable;
public class RuntimeDataCleanupRunnable implements MapSerializableRunnable, ContextsAware {
private final Log _log = LogFactory.getLog(RuntimeDataCleanupRunnable.class);
private static final long serialVersionUID = 1L;
private transient Contexts _contexts;
private int _transactionSize;
private CleanupInfo _cleanupInfo;
private QName _pid;
private Set<QName> _pidsToExclude;
public RuntimeDataCleanupRunnable() {
}
@SuppressWarnings("unchecked")
public void restoreFromDetailsMap(Map<String, Object> details) {
_cleanupInfo = (CleanupInfo)details.get("cleanupInfo");
_transactionSize = (Integer)details.get("transactionSize");
_pid = (QName)details.get("pid");
_pidsToExclude = (Set<QName>)details.get("pidsToExclude");
}
public void storeToDetailsMap(Map<String, Object> details) {
// we don't serialize
}
public void setContexts(Contexts contexts) {
_contexts = contexts;
}
public void run() {
_log.info("CRON CLEAN.run().");
for( String filter : _cleanupInfo.getFilters() ) {
if( _pid != null ) {
filter += " pid=" + _pid;
} else if( _pidsToExclude != null ) {
StringBuffer pids = new StringBuffer();
for( QName pid : _pidsToExclude ) {
if( pids.length() > 0 ) {
pids.append("|");
}
pids.append(pid);
}
filter += " pid<>" + pids.toString();
}
if( filter.trim().length() > 0 ) {
_log.info("CRON CLEAN.run(" + filter + ")");
long numberOfDeletedInstances = 0;
do {
numberOfDeletedInstances = cleanInstances(filter, _cleanupInfo.getCategories(), _transactionSize);
} while( numberOfDeletedInstances == _transactionSize );
}
}
}
int cleanInstances(String filter, final Set<CLEANUP_CATEGORY> categories, int limit) {
_log.debug("CRON CLEAN using filter: " + filter + ", limit: " + limit);
final InstanceFilter instanceFilter = new InstanceFilter(filter, "", limit);
try {
if( _contexts.scheduler != null ) {
return _contexts.scheduler.execTransaction(new Callable<Integer>() {
public Integer call() throws Exception {
BpelDAOConnection con = _contexts.dao.getConnection();
if( con instanceof FilteredInstanceDeletable ) {
return ((FilteredInstanceDeletable)con).deleteInstances(instanceFilter, categories);
}
return 0;
}
});
} else {
return 0;
}
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException("Exception while listing instances: ", e);
}
}
}
|
package ch.elexis.core.ui.e4.jface.preference;
import java.io.File;
import java.io.IOException;
import org.eclipse.jface.preference.StringButtonFieldEditor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import ch.elexis.core.services.IVirtualFilesystemService;
import ch.elexis.core.services.IVirtualFilesystemService.IVirtualFilesystemHandle;
import ch.elexis.core.services.holder.VirtualFilesystemServiceHolder;
/**
* An editor for types compatible with the {@link IVirtualFilesystemService}. Will hide a password
* on showing the entry.
*
*/
public class URIFieldEditor extends StringButtonFieldEditor {
/**
* Initial path for the Browse dialog.
*/
private File filterPath = null;
/**
* Creates a new directory field editor
*/
protected URIFieldEditor(){}
/**
* Creates a directory field editor.
*
* @param name
* the name of the preference this field editor works on
* @param labelText
* the label text of the field editor
* @param parent
* the parent of the field editor's control
*/
public URIFieldEditor(String name, String labelText, Composite parent){
init(name, labelText);
setErrorMessage(JFaceResources.getString("DirectoryFieldEditor.errorMessage"));//$NON-NLS-1$
setChangeButtonText(JFaceResources.getString("openBrowse"));//$NON-NLS-1$
setValidateStrategy(VALIDATE_ON_FOCUS_LOST);
createControl(parent);
}
@Override
protected String changePressed(){
File f = new File(getTextControl().getText());
if (!f.exists()) {
f = null;
}
File d = getDirectory(f);
if (d == null) {
return null;
}
return d.getAbsolutePath();
}
@Override
protected boolean doCheckState(){
String uri = getTextControl().getText();
uri = uri.trim();
if (uri.length() == 0 && isEmptyStringAllowed()) {
return true;
}
if (uri.contains("*")) {
setErrorMessage("Passwort muss gesetzt sein");
return false;
}
try {
IVirtualFilesystemHandle vfsHandle = VirtualFilesystemServiceHolder.get().of(uri);
return vfsHandle.isDirectory() && vfsHandle.canWrite() && vfsHandle.canRead();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
@Override
protected void doLoad(){
if (getTextControl() != null) {
String value = getPreferenceStore().getString(getPreferenceName());
value = IVirtualFilesystemService.hidePasswordInUrlString(value);
getTextControl().setText(value);
oldValue = value;
}
}
/**
* Helper that opens the directory chooser dialog.
*
* @param startingDirectory
* The directory the dialog will open in.
* @return File File or <code>null</code>.
*
*/
private File getDirectory(File startingDirectory){
DirectoryDialog fileDialog = new DirectoryDialog(getShell(), SWT.OPEN | SWT.SHEET);
if (startingDirectory != null) {
fileDialog.setFilterPath(startingDirectory.getPath());
} else if (filterPath != null) {
fileDialog.setFilterPath(filterPath.getPath());
}
String dir = fileDialog.open();
if (dir != null) {
dir = dir.trim();
if (dir.length() > 0) {
return new File(dir);
}
}
return null;
}
/**
* Sets the initial path for the Browse dialog.
*
* @param path
* initial path for the Browse dialog
* @since 3.6
*/
public void setFilterPath(File path){
filterPath = path;
}
}
|
package gov.nih.nci.cagrid.syncgts.core;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.syncgts.bean.DateFilter;
import gov.nih.nci.cagrid.syncgts.bean.SyncReport;
import java.io.File;
import javax.xml.namespace.QName;
/**
* @author <A href="mailto:langella@bmi.osu.edu">Stephen Langella </A>
* @author <A href="mailto:oster@bmi.osu.edu">Scott Oster </A>
* @author <A href="mailto:hastings@bmi.osu.edu">Shannon Hastings </A>
* @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella
* Exp $
*/
public class HistoryManager {
private final static QName reportQN = new QName(SyncGTSDefault.SYNC_GTS_NAMESPACE, "SyncReport");
private final static int maxSyncReports = 1000;
public File addReport(SyncReport report) throws Exception {
File r = getFile(report.getTimestamp());
Utils.serializeDocument(r.getAbsolutePath(), report, reportQN);
return r;
}
public SyncReport getReport(String fileName) throws Exception {
return (SyncReport) Utils.deserializeDocument(fileName, SyncReport.class);
}
public SyncReport[] search(DateFilter start, DateFilter end) throws Exception {
SyncReport[] reports = new SyncReport[maxSyncReports];
int checkMax = 0;
int iterator = 0;
this.incrementDate(end);
while(!start.equals(end)){
File startDir = getDirectory(start);
if((startDir.exists())&&(startDir.isDirectory())){
String[] fileList = startDir.list();
checkMax = checkMax + fileList.length;
if(checkMax > maxSyncReports)
throw new Exception();
else {
for(int i = 0; i < fileList.length; i++)
{
reports[iterator] = this.getReport(startDir.getAbsolutePath() + File.separator + fileList[i]);
iterator++;
}
}
}
this.incrementDate(start);
}
SyncReport[] returnReports = new SyncReport[checkMax];
System.arraycopy(reports, 0, returnReports, 0, returnReports.length);
return returnReports;
}
private File getFile(String timestamp) {
File dir = getDirectory(timestamp);
return new File(dir.getAbsolutePath() + File.separator + timestamp + ".xml");
}
private File getHistoryDirectory() {
File dir = new File(SyncGTSDefault.getSyncGTSUserDir() + File.separator + "history");
dir.mkdirs();
return dir;
}
private File getDirectory(DateFilter f) {
File histDir = getHistoryDirectory();
String month;
String day;
if(f.getMonth()<10){
month = "0" + f.getMonth();
}
else
month = "" + f.getMonth();
if(f.getDay()<10){
day = "0" + f.getDay();
}
else
day = "" + f.getDay();
File dir = new File(histDir.getAbsolutePath() + File.separator + f.getYear() + File.separator + month
+ File.separator + day);
return dir;
}
private File getDirectory(String timestamp) {
String year = timestamp.substring(0, 4);
String month = timestamp.substring(4, 6);
String days = timestamp.substring(6, 8);
File histDir = getHistoryDirectory();
File dir = new File(histDir.getAbsolutePath() + File.separator + year + File.separator + month + File.separator
+ days);
dir.mkdirs();
return dir;
}
private void incrementDate(DateFilter f){
if(f.getDay() >= 31){
f.setDay(1);
if(f.getMonth() >= 12){
f.setMonth(1);
f.setYear(f.getYear()+1);
}
else{
f.setMonth(f.getMonth()+1);
}
}
else
f.setDay(f.getDay()+1);
}
public static void main(String[] args) {
HistoryManager hm = new HistoryManager();
DateFilter start = new DateFilter();
start.setYear(2006);
start.setMonth(5);
start.setDay(9);
DateFilter end = new DateFilter();
end.setYear(2006);
end.setMonth(5);
end.setDay(12);
try{
SyncReport[] reports = hm.search(start, end);
System.out.println(reports.length);
}catch(Exception e){
e.printStackTrace();
}
}
}
|
package io.spine.examples.todolist.client;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.util.Log;
import com.google.firebase.firestore.Blob;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;
import io.spine.protobuf.Messages;
import io.spine.type.TypeUrl;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.firebase.firestore.DocumentChange.Type.ADDED;
import static com.google.firebase.firestore.DocumentChange.Type.MODIFIED;
import static io.spine.util.Exceptions.illegalStateWithCauseOf;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static io.spine.util.Exceptions.newIllegalStateException;
import static java.lang.String.format;
/**
* The client of the Firebase subscription mirror for the Android app.
*
* <p>This class is the client of the Firebase subscription mirror. The mirror is one for all
* the bounded contexts in TodoList, thus this class is a singleton.
*
* <p>{@code FirebaseSubscriber} propagates the entity state updates posted by the mirror to
* the consumers within the Android application.
*
* <p>The client requires the Firebase App to be
* {@linkplain com.google.firebase.FirebaseApp#initializeApp initialized}.
*
* @author Dmytro Dashenkov
*/
public final class FirebaseSubscriber {
private static final String ID_KEY = "id";
private static final String BYTES_KEY = "bytes";
private static final String TAG = FirebaseSubscriber.class.getSimpleName();
private final FirebaseFirestore database = FirebaseFirestore.getInstance();
/** Prevent direct instantiation. */
private FirebaseSubscriber() {}
/**
* Subscribes to the entity states of the given type.
*
* <p>The method returns a {@link LiveData} of map (string ID -> entity state). The ID is
* the {@linkplain io.spine.Identifier#toString(Object) string representation} of
* the corresponding entity ID.
*
* <p>Currently, the element removal is not supported. If a {@link DocumentChange} of type other
* than {@link DocumentChange.Type#ADDED ADDED} or {@link DocumentChange.Type#MODIFIED MODIFIED}
* is encountered, an {@link UnsupportedOperationException} is thrown.
*
* @param targetType the class of the entity to subscribe to
* @param <T> the type of the entity to subscribe to
* @return an instance of {@link LiveData} for the observers to subscribe to
*/
public <T extends Message> LiveData<Map<String, T>> subscribeTo(Class<T> targetType) {
checkNotNull(targetType);
final CollectionReference targetCollection = collectionFor(targetType);
final MutableLiveData<Map<String, T>> result = new MutableLiveData<>();
targetCollection.addSnapshotListener((documentSnapshots, error) -> {
if (error != null) {
final String errorMsg = format(
"Error encountered while listening for the %s state updates.",
targetType
);
Log.e(TAG, errorMsg, error);
} else {
final Parser<T> parser = getParserFor(targetType);
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
deliverUpdate(change, result, parser);
}
}
});
return result;
}
@SuppressWarnings("UnnecessaryReturnStatement") // OK for a fast exit on invalid data.
public <T extends Message> LiveData<T> subscribeToSingle(Class<T> targetType) {
final MutableLiveData<T> liveData = new MutableLiveData<>();
final LiveData<Map<String, T>> allRecordsData = subscribeTo(targetType);
allRecordsData.observeForever(map -> {
if (map == null || map.isEmpty()) {
return;
} else if (map.size() > 1) {
throw newIllegalStateException("Type %s has multiple instances.", targetType);
} else {
final Map.Entry<?, T> singleEntry = map.entrySet()
.iterator()
.next();
final T singleData = singleEntry.getValue();
liveData.postValue(singleData);
}
});
return liveData;
}
private CollectionReference collectionFor(Class<? extends Message> type) {
final TypeUrl typeUrl = TypeUrl.of(type);
final String targetCollectionName = typeUrl.value()
.replace('/', '_');
final CollectionReference result = database.collection(targetCollectionName);
return result;
}
/**
* Delivers the entity state update represented by the given {@link DocumentChange} to
* the observers of the given {@link LiveData}.
*
* @param change the Firestore document change
* @param destination the {@link LiveData} publishing the update
* @param parser the {@link Parser} for the target entity state type
* @param <T> the entity state type
*/
private static <T extends Message>
void deliverUpdate(DocumentChange change,
MutableLiveData<Map<String, T>> destination,
Parser<T> parser) {
final DocumentChange.Type type = change.getType();
final Map<String, T> currentData = destination.getValue();
final Map<String, T> newData = currentData == null
? newHashMap()
: newHashMap(currentData);
final DocumentSnapshot doc = change.getDocument();
final String id = parseMessageId(doc);
final T newMessage = parseMessage(doc, parser);
if (type == ADDED || type == MODIFIED) {
newData.put(id, newMessage);
} else {
throw newIllegalArgumentException("Unexpected document change: %s", type.toString());
}
destination.postValue(newData);
}
private static <T extends Message> T parseMessage(DocumentSnapshot doc, Parser<T> parser) {
final Blob blob = doc.getBlob(BYTES_KEY);
final byte[] bytes = blob.toBytes();
try {
final T message = parser.parseFrom(bytes);
return message;
} catch (InvalidProtocolBufferException e) {
throw illegalStateWithCauseOf(e);
}
}
private static String parseMessageId(DocumentSnapshot doc) {
final String id = doc.getString(ID_KEY);
return id;
}
private static <T extends Message> Parser<T> getParserFor(Class<T> type) {
final T mockInstance = Messages.newInstance(type);
@SuppressWarnings("unchecked") final Parser<T> result = (Parser<T>) mockInstance.getParserForType();
return result;
}
/**
* Retrieves the singleton instance of {@code FirebaseSubscriber}.
*/
public static FirebaseSubscriber instance() {
return Singleton.INSTANCE.value;
}
private enum Singleton {
INSTANCE;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final FirebaseSubscriber value = new FirebaseSubscriber();
}
}
|
package org.jetel.connection.jdbc.specific.impl;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.connection.jdbc.CopySQLData;
import org.jetel.connection.jdbc.CopySQLData.CopyArray;
import org.jetel.connection.jdbc.CopySQLData.CopyBlob;
import org.jetel.connection.jdbc.CopySQLData.CopyBoolean;
import org.jetel.connection.jdbc.CopySQLData.CopyByte;
import org.jetel.connection.jdbc.CopySQLData.CopyDate;
import org.jetel.connection.jdbc.CopySQLData.CopyDecimal;
import org.jetel.connection.jdbc.CopySQLData.CopyInteger;
import org.jetel.connection.jdbc.CopySQLData.CopyLong;
import org.jetel.connection.jdbc.CopySQLData.CopyNumeric;
import org.jetel.connection.jdbc.CopySQLData.CopyString;
import org.jetel.connection.jdbc.CopySQLData.CopyTime;
import org.jetel.connection.jdbc.CopySQLData.CopyTimestamp;
import org.jetel.connection.jdbc.DBConnection;
import org.jetel.connection.jdbc.SQLCloverStatement.QueryType;
import org.jetel.connection.jdbc.SQLUtil;
import org.jetel.connection.jdbc.driver.JdbcDriver;
import org.jetel.connection.jdbc.specific.JdbcSpecific;
import org.jetel.data.DataRecord;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.graph.Node;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.string.StringUtils;
abstract public class AbstractJdbcSpecific implements JdbcSpecific {
private final static Log logger = LogFactory.getLog(AbstractJdbcSpecific.class);
/** the SQL comments pattern conforming to the SQL standard */
//&&[^-?=-] part added due to issue 3472
private static final Pattern COMMENTS_PATTERN = Pattern.compile("--[^\r\n&&[^-?=-]]*|/\\*.*?\\*/", Pattern.DOTALL);
private static final String TYPES_CLASS_NAME = "java.sql.Types";
private static final String RESULT_SET_PARAMETER_TYPE_FIELD = "OTHER";
private final static int DEFAULT_FETCH_SIZE = 50;
private AutoGeneratedKeysType autoGeneratedKeysType;
protected AbstractJdbcSpecific() {
this(AutoGeneratedKeysType.NONE);
}
public AbstractJdbcSpecific(AutoGeneratedKeysType autoGeneratedKeysType) {
this.autoGeneratedKeysType = autoGeneratedKeysType;
}
@Override
public ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata, Node node) {
return status;
}
@Override
public void closeResultSetBeforeCreatingNewOne(ResultSet resultSet) throws SQLException {
if (resultSet != null) {
// close the previous result set before creating new one
resultSet.close();
// note: according to documentation, resultSet that is already closed is a no-op, please test
}
}
@Override
public String getDbFieldPattern() {
//combination of alphanumeric chars with . and _ - can be quoted
//sequence between quote is regarded as group by @see java.util.Pattern
return "([\\p{Alnum}\\._]+)|([\"\'][\\p{Alnum}\\._ ]+[\"\'])";
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#createSQLConnection(org.jetel.connection.jdbc.DBConnection, org.jetel.connection.jdbc.specific.JdbcSpecific.OperationType)
*/
@Override
abstract public Connection createSQLConnection(DBConnection dbConnection, OperationType operationType) throws JetelException;
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#getAutoKeyType()
*/
@Override
public AutoGeneratedKeysType getAutoKeyType() {
return autoGeneratedKeysType;
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#optimizeResultSet(java.sql.ResultSet, org.jetel.connection.jdbc.specific.JdbcSpecific.OperationType)
*/
@Override
public void optimizeResultSet(ResultSet resultSet, OperationType operationType) {
switch (operationType){
case READ:
try {
resultSet.setFetchDirection(ResultSet.FETCH_FORWARD);
resultSet.setFetchSize(DEFAULT_FETCH_SIZE);
} catch(SQLException ex) {
//TODO: for now, do nothing
}
}
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#jetelType2sql(org.jetel.metadata.DataFieldMetadata)
*/
@Override
public int jetelType2sql(DataFieldMetadata field){
switch (field.getType()) {
case DataFieldMetadata.INTEGER_FIELD:
return Types.INTEGER;
case DataFieldMetadata.NUMERIC_FIELD:
return Types.FLOAT;
case DataFieldMetadata.STRING_FIELD:
return field.isFixed() ? Types.CHAR : Types.VARCHAR;
case DataFieldMetadata.DATE_FIELD:
boolean isDate = field.isDateFormat();
boolean isTime = field.isTimeFormat();
if (isDate && isTime || StringUtils.isEmpty(field.getFormatStr()))
return Types.TIMESTAMP;
if (isDate)
return Types.DATE;
if (isTime)
return Types.TIME;
return Types.TIMESTAMP;
case DataFieldMetadata.LONG_FIELD:
return Types.BIGINT;
case DataFieldMetadata.DECIMAL_FIELD:
return Types.DECIMAL;
case DataFieldMetadata.BYTE_FIELD:
case DataFieldMetadata.BYTE_FIELD_COMPRESSED:
if (!StringUtils.isEmpty(field.getFormatStr())
&& field.getFormatStr().equalsIgnoreCase(DataFieldMetadata.BLOB_FORMAT_STRING)) {
return Types.BLOB;
}
return field.isFixed() ? Types.BINARY : Types.VARBINARY;
case DataFieldMetadata.BOOLEAN_FIELD:
return Types.BOOLEAN;
default:
throw new IllegalArgumentException("Can't handle Clover's data type :"+field.getTypeAsString());
}
}
@Override
public String jetelType2sqlDDL(DataFieldMetadata field) {
int sqlType = jetelType2sql(field);
switch(sqlType) {
case Types.BINARY :
case Types.VARBINARY :
case Types.VARCHAR :
case Types.CHAR :
return sqlType2str(sqlType) + "(" + (field.isFixed() ? String.valueOf(field.getSize()) : "80") + ")";
case Types.DECIMAL :
String base = sqlType2str(sqlType);
String prec = "";
if (field.getProperty("length") != null) {
if (field.getProperty("scale") != null) {
prec = "(" + field.getProperty("length") + "," + field.getProperty("scale") + ")";
} else {
prec = "(" + field.getProperty("length") + ",0)";
}
}
return base + prec;
default :
return sqlType2str(sqlType);
}
}
@Override
public char sqlType2jetel(int sqlType, int sqlPrecision) {
return sqlType2jetel(sqlType);
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#sqlType2jetel(int)
*/
@Override
public char sqlType2jetel(int sqlType) {
switch (sqlType) {
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
return DataFieldMetadata.INTEGER_FIELD;
case Types.BIGINT:
return DataFieldMetadata.LONG_FIELD;
case Types.DECIMAL:
case Types.NUMERIC:
return DataFieldMetadata.DECIMAL_FIELD;
case Types.DOUBLE:
case Types.FLOAT:
case Types.REAL:
return DataFieldMetadata.NUMERIC_FIELD;
case Types.CHAR:
case Types.LONGVARCHAR:
case Types.VARCHAR:
case Types.CLOB:
case Types.NCHAR:
case Types.NVARCHAR:
case Types.NCLOB:
return DataFieldMetadata.STRING_FIELD;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return DataFieldMetadata.DATE_FIELD;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
case Types.OTHER:
return DataFieldMetadata.BYTE_FIELD;
case Types.BOOLEAN:
return DataFieldMetadata.BOOLEAN_FIELD;
// proximity assignment
case Types.BIT:
case Types.NULL:
return DataFieldMetadata.STRING_FIELD;
case Types.STRUCT:
throw new IllegalArgumentException("Can't handle JDBC type STRUCT");
default:
throw new IllegalArgumentException("Can't handle JDBC.Type :"+sqlType);
}
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#createCopyObject(int, org.jetel.metadata.DataFieldMetadata, org.jetel.data.DataRecord, int, int)
*/
@Override
public CopySQLData createCopyObject(int sqlType, DataFieldMetadata fieldMetadata, DataRecord record, int fromIndex, int toIndex) {
String format = fieldMetadata.getFormat();
char jetelType = fieldMetadata.getType();
CopySQLData obj = null;
switch (sqlType) {
case Types.ARRAY:
obj = new CopyArray(record, fromIndex, toIndex);
break;
case Types.CHAR:
case Types.LONGVARCHAR:
case Types.VARCHAR:
obj = new CopyString(record, fromIndex, toIndex);
break;
case Types.INTEGER:
case Types.SMALLINT:
if (jetelType == DataFieldMetadata.BOOLEAN_FIELD) {
obj = new CopyBoolean(record, fromIndex, toIndex);
} else {
obj = new CopyInteger(record, fromIndex, toIndex);
}
break;
case Types.BIGINT:
obj = new CopyLong(record,fromIndex,toIndex);
break;
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.REAL:
// fix for copying when target is numeric and
// clover source is integer - no precision can be
// lost so we can use CopyInteger
if (jetelType == DataFieldMetadata.INTEGER_FIELD) {
obj = new CopyInteger(record, fromIndex, toIndex);
} else if (jetelType == DataFieldMetadata.LONG_FIELD) {
obj = new CopyLong(record, fromIndex, toIndex);
} else if(jetelType == DataFieldMetadata.NUMERIC_FIELD) {
obj = new CopyNumeric(record, fromIndex, toIndex);
} else {
obj = new CopyDecimal(record, fromIndex, toIndex);
}
break;
case Types.NUMERIC:
// Oracle doesn't have boolean type, data type SMALLINT is the same as NUMBER(38);
// see issue #3815
if (jetelType == DataFieldMetadata.BOOLEAN_FIELD) {
obj = new CopyBoolean(record, fromIndex, toIndex);
}else if (jetelType == DataFieldMetadata.INTEGER_FIELD) {
obj = new CopyInteger(record, fromIndex, toIndex);
} else if (jetelType == DataFieldMetadata.LONG_FIELD) {
obj = new CopyLong(record, fromIndex, toIndex);
} else if(jetelType == DataFieldMetadata.NUMERIC_FIELD) {
obj = new CopyNumeric(record, fromIndex, toIndex);
} else {
obj = new CopyDecimal(record, fromIndex, toIndex);
}
break;
case Types.DATE:
if (StringUtils.isEmpty(format)) {
obj = new CopyDate(record, fromIndex, toIndex);
break;
}
case Types.TIME:
if (StringUtils.isEmpty(format)) {
obj = new CopyTime(record, fromIndex, toIndex);
break;
}
case Types.TIMESTAMP:
if (StringUtils.isEmpty(format)) {
obj = new CopyTimestamp(record, fromIndex, toIndex);
break;
}
boolean isDate = fieldMetadata.isDateFormat();
boolean isTime = fieldMetadata.isTimeFormat();
if (isDate && isTime) {
obj = new CopyTimestamp(record, fromIndex, toIndex);
}else if (isDate) {
obj = new CopyDate(record, fromIndex, toIndex);
}else if (isTime){
obj = new CopyTime(record, fromIndex, toIndex);
}else {
obj = new CopyTimestamp(record, fromIndex, toIndex);
}
break;
case Types.BOOLEAN:
case Types.BIT:
if (jetelType == DataFieldMetadata.BOOLEAN_FIELD) {
obj = new CopyBoolean(record, fromIndex, toIndex);
break;
}
logger.warn("Metadata mismatch; type:" + jetelType + " SQLType:" + sqlType + " - using CopyString object.");
obj = new CopyString(record, fromIndex, toIndex);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
if (!StringUtils.isEmpty(format) && format.equalsIgnoreCase(SQLUtil.BLOB_FORMAT_STRING)) {
obj = new CopyBlob(record, fromIndex, toIndex);
break;
}
if (!StringUtils.isEmpty(format) && !format.equalsIgnoreCase(SQLUtil.BINARY_FORMAT_STRING)){
logger.warn("Unknown format " + StringUtils.quote(format) + " - using CopyByte object.");
}
obj = new CopyByte(record, fromIndex, toIndex);
break;
// when Types.OTHER or unknown, try to copy it as STRING
// this works for most of the NCHAR/NVARCHAR types on Oracle, MSSQL, etc.
default:
//case Types.OTHER:// When other, try to copy it as STRING - should work for NCHAR/NVARCHAR
obj = new CopyString(record, fromIndex, toIndex);
break;
//default:
// throw new RuntimeException("SQL data type not supported: " + SQLType);
}
obj.setSqlType(sqlType);
return obj;
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#getResultSetParameterTypeField()
*/
@Override
public String getResultSetParameterTypeField() {
return RESULT_SET_PARAMETER_TYPE_FIELD;
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#getTypesClassName()
*/
@Override
public String getTypesClassName() {
return TYPES_CLASS_NAME;
}
@Override
public Pattern getCommentsPattern() {
return COMMENTS_PATTERN;
}
@Override
public String sqlType2str(int sqlType) {
return SQLUtil.sqlType2str(sqlType);
}
@Override
public String quoteIdentifier(String identifier) {
return identifier;
}
@Override
public String quoteString(String string) {
return string;
}
@Override
public String getValidateQuery(String query, QueryType queryType, boolean optimizeSelectQuery) throws SQLException {
String q = null;
String where = "WHERE";
int indx;
switch(queryType) {
case INSERT:
throw new SQLException("INSERT query cannot be validated");
case UPDATE:
case DELETE:
q = query.toUpperCase();
indx = q.indexOf(where);
if (indx >= 0){
q = q.substring(0, indx + where.length()) + " 0=1 and " + q.substring(indx + where.length());
}else{
q += " where 0=1";
}
break;
case SELECT:
query = SQLUtil.removeUnnamedFields(query, this);
if (optimizeSelectQuery) {
q = "SELECT wrapper_table.* FROM (" + query + ") wrapper_table where 1=0";
} else {
q = query;
}
break;
}
return q;
}
/**
* Default behavior for literal detection
*/
@Override
public boolean isLiteral(String s) {
if (s == null) {
return true;
}
s = s.trim();
// numbers are literals
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
}
try {
Double.parseDouble(s);
return true;
} catch (NumberFormatException e) {
}
return s.startsWith("'");
}
/**
* A static method that retrieves schemas from dbMeta objects.
* Returns it as arraylist of strings in the format either <schema> or <catalog>.<schema>
* e.g.:
* mytable
* dbo.anothertable
*
* @param dbMeta
* @return
* @throws SQLException
*/
protected static ArrayList<String> getMetaSchemas(DatabaseMetaData dbMeta) throws SQLException {
ArrayList<String> ret = new ArrayList<String>();
ResultSet result = dbMeta.getSchemas();
String tmp;
while (result.next()) {
tmp = "";
try {
if (result.getString(2) != null) {
tmp = result.getString(2) + dbMeta.getCatalogSeparator();
}
} catch (Exception e) {
// -pnajvar
// this is here deliberately
// some dbms don't provide second column and that is not wrong, just have to ignore
}
tmp += result.getString(1);
ret.add(tmp);
}
result.close();
return ret;
}
protected static ArrayList<String> getMetaCatalogs(DatabaseMetaData dbMeta) throws SQLException {
ArrayList<String> ret = new ArrayList<String>();
ResultSet result = dbMeta.getCatalogs();
String tmp;
while (result.next()) {
tmp = result.getString(1);
ret.add(tmp);
}
result.close();
return ret;
}
@Override
public ArrayList<String> getSchemas(java.sql.Connection connection)
throws SQLException {
ArrayList<String> tmp;
ArrayList<String> schemas = new ArrayList<String>();
DatabaseMetaData dbMeta = connection.getMetaData();
// add schemas
tmp = getMetaSchemas(dbMeta);
if (tmp != null) {
schemas.addAll(tmp);
}
// add catalogs
tmp = getMetaCatalogs(dbMeta);
if (tmp != null) {
schemas.addAll(tmp);
}
return schemas;
}
@Override
public ResultSet getTables(java.sql.Connection connection, String dbName) throws SQLException {
// by default, database `dbName` is considered a schema, sometimes it needs to be considered
// as a catalog
return connection.getMetaData().getTables(dbName, null, "%", new String[] {"TABLE", "VIEW" }/*tableTypes*/); //fix by kokon - show only tables and views
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#getColumns(java.sql.Connection, java.lang.String, java.lang.String)
*/
@Override
public ResultSetMetaData getColumns(Connection connection, String schema, String table) throws SQLException {
String sqlQuery = compileSelectQuery4Table(schema, table) + " where 0=1";
ResultSet resultSet = connection.createStatement().executeQuery(sqlQuery);
return resultSet.getMetaData();
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.JdbcSpecific#compileSelectQuery4Table(java.lang.String, java.lang.String)
*/
@Override
public String compileSelectQuery4Table(String schema, String table) {
if (isSchemaRequired() && !StringUtils.isEmpty(schema)) {
return "select * from " + quoteIdentifier(schema) + "." + quoteIdentifier(table);
} else {
return "select * from " + quoteIdentifier(table);
}
}
@Override
public Set<ResultSet> getColumns(java.sql.Connection connection) throws SQLException {
Set<ResultSet> resultSets = new HashSet<ResultSet>();
try {
resultSets.add(connection.getMetaData().getColumns(null, null, null, "%"));
} catch (SQLException e) {
}
return resultSets;
}
@Override
public boolean isSchemaRequired() {
return false;
}
@Override
public String getTablePrefix(String schema, String owner,
boolean quoteIdentifiers) {
return quoteIdentifiers ? quoteIdentifier(schema) : schema;
}
@Override
public boolean isJetelTypeConvertible2sql(int sqlType, DataFieldMetadata field) {
int jetelTypeToSql = jetelType2sql(field);
if (jetelTypeToSql == Types.VARCHAR && (sqlType == Types.CHAR || sqlType == Types.CLOB)) {
return true;
}
return sqlType == jetelTypeToSql;
}
@Override
public boolean isSqlTypeConvertible2jetel(int sqlType, DataFieldMetadata field) {
return sqlType2jetel(sqlType) == field.getType();
}
@Override
public boolean supportsGetGeneratedKeys(DatabaseMetaData metadata) throws SQLException {
try {
boolean result = metadata.supportsGetGeneratedKeys();
return result;
}
catch (Exception e) {
if (e instanceof SQLException) throw (SQLException)e;
return false;
}
}
@Override
public List<Integer> getFieldTypes(ResultSetMetaData resultSetMetadata, DataRecordMetadata cloverMetadata) throws SQLException {
return SQLUtil.getFieldTypes(resultSetMetadata);
}
@Override
public int getSqlTypeByTypeName(String sqlTypeName) {
return Types.CLOB;
}
@Override
public boolean useSavepoints() {
return false;
}
@Override
public void unloadDriver(JdbcDriver driver) {
// do nothing by default
}
@Override
public ResultSet wrapResultSet(ResultSet resultSet) {
return resultSet;
}
}
|
package edu.duke.cabig.c3pr.service.impl;
import edu.duke.cabig.c3pr.dao.ResearchStaffDao;
import edu.duke.cabig.c3pr.domain.*;
import edu.duke.cabig.c3pr.exception.C3PRBaseException;
import edu.duke.cabig.c3pr.service.PersonnelService;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.acegi.csm.authorization.CSMObjectIdGenerator;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.dao.GroupSearchCriteria;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import org.apache.log4j.Logger;
import org.springframework.mail.MailException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PersonnelServiceImpl implements PersonnelService {
private ResearchStaffDao dao;
private UserProvisioningManager userProvisioningManager;
private CSMObjectIdGenerator siteObjectIdGenerator;
private Logger log = Logger.getLogger(PersonnelServiceImpl.class);
private void save(C3PRUser c3prUser, gov.nih.nci.security.authorization.domainobjects.User csmUser)
throws C3PRBaseException, MailException {
try {
if (csmUser == null) {
csmUser = new gov.nih.nci.security.authorization.domainobjects.User();
populateCSMUser(c3prUser, csmUser);
userProvisioningManager.createUser(csmUser);
} else {
populateCSMUser(c3prUser, csmUser);
userProvisioningManager.modifyUser(csmUser);
}
log.debug("Saving c3pr user");
dao.save(c3prUser);
c3prUser.setLoginId(csmUser.getUserId().toString());
for (C3PRUserGroupType group : c3prUser.getGroups()) {
assignUserToGroup(csmUser, group.getCode());
}
} catch (CSTransactionException e) {
throw new C3PRBaseException("Could not create user", e);
}
}
public void save(Investigator inv) throws C3PRBaseException {
log.debug("Saving Investigator");
dao.save(inv);
}
public void save(ResearchStaff staff) throws C3PRBaseException {
save(staff, null);
try {
User csmUser = getCSMUser(staff);
csmUser.setOrganization(staff.getHealthcareSite().getNciInstituteCode());
assignUserToGroup(csmUser, siteObjectIdGenerator.generateId(staff.getHealthcareSite()));
log.debug("Successfully assigned user to organization group" + siteObjectIdGenerator.generateId(staff.getHealthcareSite()));
} catch (CSObjectNotFoundException e) {
new C3PRBaseException("Could not assign user to organization group.");
}
}
public void merge(Investigator user) throws C3PRBaseException {
dao.save((C3PRUser) user);
}
public void merge(ResearchStaff staff) throws C3PRBaseException {
try {
User csmUser = getCSMUser(staff);
save(staff, csmUser);
} catch (CSObjectNotFoundException e) {
new C3PRBaseException("Could not save Research staff" + e.getMessage());
}
}
private void assignUserToGroup(User csmUser, String groupName) throws C3PRBaseException {
Set<String> groups = new HashSet<String>();
try {
Set<Group> existingSet = userProvisioningManager.getGroups(csmUser.getUserId().toString());
for (Group existingGroup : existingSet) {
groups.add(existingGroup.getGroupId().toString());
}
groups.add(getGroupIdByName(groupName));
userProvisioningManager.assignGroupsToUser(csmUser.getUserId().toString(), groups.toArray(new String[groups.size()]));
} catch (Exception e) {
throw new C3PRBaseException("Could not add user to group", e);
}
}
private User getCSMUser(C3PRUser user) throws CSObjectNotFoundException {
return userProvisioningManager.getUserById(user.getLoginId());
}
public List<C3PRUserGroupType> getGroups(C3PRUser user) throws C3PRBaseException {
List<C3PRUserGroupType> groups = new ArrayList<C3PRUserGroupType>();
try {
Set<Group> csmGroups = userProvisioningManager.getGroups(user.getLoginId().toString());
for (Group csmGroup : csmGroups) {
if(C3PRUserGroupType.getByCode(csmGroup.getGroupName()) != null){
groups.add(C3PRUserGroupType.getByCode(csmGroup.getGroupName()));
}
}
} catch (Exception e) {
log.warn("Error getting groups from CSM for user " + user.getFullName());
}
return groups;
}
private String getGroupIdByName(String groupName) {
Group search = new Group();
search.setGroupName(groupName);
GroupSearchCriteria sc = new GroupSearchCriteria(search);
Group returnGroup = (Group) userProvisioningManager.getObjects(sc).get(0);
return returnGroup.getGroupId().toString();
}
private void populateCSMUser(C3PRUser c3prUser, gov.nih.nci.security.authorization.domainobjects.User csmUser) {
csmUser.setFirstName(c3prUser.getFirstName());
csmUser.setLastName(c3prUser.getLastName());
csmUser.setPassword(c3prUser.getLastName());
for (ContactMechanism cm : c3prUser.getContactMechanisms()) {
if (cm.getType().equals(ContactMechanismType.EMAIL)) {
csmUser.setLoginName(cm.getValue());
csmUser.setEmailId(cm.getValue());
}
}
}
//spring settters
public UserProvisioningManager getUserProvisioningManager() {
return userProvisioningManager;
}
public void setUserProvisioningManager(UserProvisioningManager userProvisioningManager) {
this.userProvisioningManager = userProvisioningManager;
}
public ResearchStaffDao getDao() {
return dao;
}
public void setDao(ResearchStaffDao dao) {
this.dao = dao;
}
public CSMObjectIdGenerator getSiteObjectIdGenerator() {
return siteObjectIdGenerator;
}
public void setSiteObjectIdGenerator(CSMObjectIdGenerator siteObjectIdGenerator) {
this.siteObjectIdGenerator = siteObjectIdGenerator;
}
}
|
package com.yahoo.vespa.config.server.model;
import com.yahoo.cloud.config.LbServicesConfig;
import com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications.Endpoints;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.api.ApplicationClusterEndpoint;
import com.yahoo.config.model.api.ApplicationInfo;
import com.yahoo.config.model.api.ContainerEndpoint;
import com.yahoo.config.model.api.Model;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.provision.InMemoryProvisioner;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.model.VespaModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import static com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications.Endpoints.RoutingMethod.Enum.sharedLayer4;
import static com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications.Endpoints.Scope.Enum.application;
import static com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications.Endpoints.Scope.Enum.global;
import static com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications.Endpoints.Scope.Enum.zone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
/**
* @author Ulf Lilleengen
*/
@RunWith(Parameterized.class)
public class LbServicesProducerTest {
private static final Set<ContainerEndpoint> endpoints = Set.of(
new ContainerEndpoint("mydisc", ApplicationClusterEndpoint.Scope.global, List.of("rotation-1", "rotation-2")),
new ContainerEndpoint("mydisc", ApplicationClusterEndpoint.Scope.application, List.of("app-endpoint"))
);
private static final List<String> zoneDnsSuffixes = List.of(".endpoint1.suffix", ".endpoint2.suffix");
private final InMemoryFlagSource flagSource = new InMemoryFlagSource();
private final boolean useGlobalServiceId;
@Parameterized.Parameters
public static Object[] useGlobalServiceId() {
return new Object[] { true, false };
}
public LbServicesProducerTest(boolean useGlobalServiceId) {
this.useGlobalServiceId = useGlobalServiceId;
}
@Test
public void testDeterministicGetConfig() {
Map<TenantName, Set<ApplicationInfo>> testModel = createTestModel(new DeployState.Builder().endpoints(endpoints));
LbServicesConfig last = null;
for (int i = 0; i < 100; i++) {
testModel = randomizeApplications(testModel, i);
LbServicesConfig config = getLbServicesConfig(Zone.defaultZone(), testModel);
if (last != null) {
assertConfig(last, config);
}
last = config;
}
}
@Test
public void testConfigActiveRotation() {
{
RegionName regionName = RegionName.from("us-east-1");
LbServicesConfig conf = createModelAndGetLbServicesConfig(regionName);
assertTrue(conf.tenants("foo").applications("foo:prod:" + regionName.value() + ":default").activeRotation());
}
{
RegionName regionName = RegionName.from("us-east-2");
LbServicesConfig conf = createModelAndGetLbServicesConfig(regionName);
assertFalse(conf.tenants("foo").applications("foo:prod:" + regionName.value() + ":default").activeRotation());
}
}
private LbServicesConfig createModelAndGetLbServicesConfig(RegionName regionName) {
Zone zone = new Zone(Environment.prod, regionName);
Map<TenantName, Set<ApplicationInfo>> testModel = createTestModel(new DeployState.Builder().zone(zone));
return getLbServicesConfig(new Zone(Environment.prod, regionName), testModel);
}
private LbServicesConfig getLbServicesConfig(Zone zone, Map<TenantName, Set<ApplicationInfo>> testModel) {
LbServicesProducer producer = new LbServicesProducer(testModel, zone, flagSource);
LbServicesConfig.Builder builder = new LbServicesConfig.Builder();
producer.getConfig(builder);
return new LbServicesConfig(builder);
}
@Test
public void testConfigAliasesWithEndpoints() {
assumeFalse(useGlobalServiceId);
Map<TenantName, Set<ApplicationInfo>> testModel = createTestModel(new DeployState.Builder()
.endpoints(endpoints)
.properties(new TestProperties().setHostedVespa(true)));
RegionName regionName = RegionName.from("us-east-1");
LbServicesConfig config = getLbServicesConfig(new Zone(Environment.prod, regionName), testModel);
List<Endpoints> endpointList = config.tenants("foo").applications("foo:prod:" + regionName.value() + ":default").endpoints();
// Expect 2 zone endpoints (2 suffixes), 2 global endpoints and 1 application endpoint
assertEquals(5, endpointList.size());
List<Endpoints> zoneEndpoints = endpointList.stream().filter(e -> e.scope() == zone).collect(Collectors.toList());
assertEquals(2, zoneEndpoints.size());
assertTrue(zoneEndpoints.stream()
.filter(e -> e.routingMethod() == sharedLayer4)
.map(Endpoints::dnsName).collect(Collectors.toList())
.containsAll(List.of("mydisc.foo.foo.endpoint1.suffix", "mydisc.foo.foo.endpoint2.suffix")));
assertContainsEndpoint(zoneEndpoints, "mydisc.foo.foo.endpoint1.suffix", "mydisc", zone, sharedLayer4, 1, List.of("foo.foo.yahoo.com"));
assertContainsEndpoint(zoneEndpoints, "mydisc.foo.foo.endpoint2.suffix", "mydisc", zone, sharedLayer4, 1, List.of("foo.foo.yahoo.com"));
List<Endpoints> globalEndpoints = endpointList.stream().filter(e -> e.scope() == global).collect(Collectors.toList());
assertEquals(2, globalEndpoints.size());
assertTrue(globalEndpoints.stream().map(Endpoints::dnsName).collect(Collectors.toList()).containsAll(List.of("rotation-1", "rotation-2")));
assertContainsEndpoint(globalEndpoints, "rotation-1", "mydisc", global, sharedLayer4, 1, List.of("foo.foo.yahoo.com"));
assertContainsEndpoint(globalEndpoints, "rotation-2", "mydisc", global, sharedLayer4, 1, List.of("foo.foo.yahoo.com"));
List<Endpoints> applicationEndpoints = endpointList.stream().filter(e -> e.scope() == application).collect(Collectors.toList());
assertEquals(1, applicationEndpoints.size());
assertTrue(applicationEndpoints.stream().map(Endpoints::dnsName).collect(Collectors.toList()).contains("app-endpoint"));
assertContainsEndpoint(applicationEndpoints, "app-endpoint", "mydisc", application, sharedLayer4, 1, List.of("foo.foo.yahoo.com"));
}
@Test
public void testRoutingConfigForTesterApplication() {
assumeFalse(useGlobalServiceId);
Map<TenantName, Set<ApplicationInfo>> testModel = createTestModel(new DeployState.Builder());
// No config for tester application
assertNull(getLbServicesConfig(Zone.defaultZone(), testModel)
.tenants("foo")
.applications("baz:prod:default:custom-t"));
}
private void assertContainsEndpoint(List<Endpoints> endpoints, String dnsName, String clusterId, Endpoints.Scope.Enum scope, Endpoints.RoutingMethod.Enum routingMethod, int weight, List<String> hosts) {
assertTrue(endpoints.contains(new Endpoints.Builder()
.dnsName(dnsName)
.clusterId(clusterId)
.scope(scope)
.routingMethod(routingMethod)
.weight(weight)
.hosts(hosts)
.build()));
}
private Map<TenantName, Set<ApplicationInfo>> randomizeApplications(Map<TenantName, Set<ApplicationInfo>> testModel, int seed) {
Map<TenantName, Set<ApplicationInfo>> randomizedApplications = new LinkedHashMap<>();
List<TenantName> keys = new ArrayList<>(testModel.keySet());
Collections.shuffle(keys, new Random(seed));
for (TenantName key : keys) {
randomizedApplications.put(key, testModel.get(key));
}
return randomizedApplications;
}
private Map<TenantName, Set<ApplicationInfo>> createTestModel(DeployState.Builder deployStateBuilder) {
Map<TenantName, Set<ApplicationInfo>> tMap = new LinkedHashMap<>();
TenantName foo = TenantName.from("foo");
TenantName bar = TenantName.from("bar");
TenantName baz = TenantName.from("baz");
tMap.put(foo, createTestApplications(foo, deployStateBuilder));
tMap.put(bar, createTestApplications(bar, deployStateBuilder));
tMap.put(baz, createTestApplications(baz, deployStateBuilder));
return tMap;
}
private Set<ApplicationInfo> createTestApplications(TenantName tenant, DeployState.Builder deployStateBuilder) {
ApplicationId fooApp = new ApplicationId.Builder().tenant(tenant).applicationName("foo").build();
ApplicationId barApp = new ApplicationId.Builder().tenant(tenant).applicationName("bar").build();
ApplicationId bazApp = new ApplicationId.Builder().tenant(tenant).applicationName("baz").instanceName("custom-t").build(); // tester app
return new LinkedHashSet<>(createApplication(List.of(fooApp, barApp, bazApp), deployStateBuilder));
}
private Set<ApplicationInfo> createApplication(List<ApplicationId> appIds, DeployState.Builder deployStateBuilder) {
Set<ApplicationInfo> applicationInfoSet = new HashSet<>();
List<String> hostnames = new ArrayList<>();
appIds.forEach(appId -> {
deployStateBuilder.properties(getTestproperties(appId));
hostnames.add(appId.tenant() + "." + appId.application() + ".yahoo.com");
hostnames.add(appId.tenant().value() + "." + appId.application().value() + "2.yahoo.com");
try {
InMemoryProvisioner provisioner = new InMemoryProvisioner(true, false, hostnames);
deployStateBuilder.modelHostProvisioner(provisioner);
applicationInfoSet.add(new ApplicationInfo(appId, 3, createVespaModel(createApplicationPackage(), deployStateBuilder)));
} catch (IOException | SAXException e) {
throw new RuntimeException(e);
}
});
return applicationInfoSet;
}
private ApplicationPackage createApplicationPackage() {
String services = "<services>" +
"<admin version='4.0'><logservers> <nodes count='1' /> </logservers></admin>" +
" <container id='mydisc' version='1.0'>" +
" <aliases>" +
" <endpoint-alias>foo2.bar2.com</endpoint-alias>" +
" <service-alias>service1</service-alias>" +
" <endpoint-alias>foo1.bar1.com</endpoint-alias>" +
" </aliases>" +
" <nodes count='1' />" +
" <search/>" +
" </container>" +
"</services>";
String deploymentInfo;
if (useGlobalServiceId) {
deploymentInfo ="<?xml version='1.0' encoding='UTF-8'?>" +
"<deployment version='1.0'>" +
" <test />" +
" <prod global-service-id='mydisc'>" +
" <region active='true'>us-east-1</region>" +
" <region active='false'>us-east-2</region>" +
" </prod>" +
"</deployment>";
} else {
deploymentInfo ="<?xml version='1.0' encoding='UTF-8'?>" +
"<deployment version='1.0'>" +
" <test />" +
" <prod>" +
" <region active='true'>us-east-1</region>" +
" <region active='false'>us-east-2</region>" +
" </prod>" +
" <endpoints>" +
" <endpoint container-id='mydisc' />" +
" </endpoints>" +
"</deployment>";
}
return new MockApplicationPackage.Builder().withServices(services).withDeploymentSpec(deploymentInfo).build();
}
private Model createVespaModel(ApplicationPackage applicationPackage, DeployState.Builder deployStateBuilder) throws IOException, SAXException {
return new VespaModel(new NullConfigModelRegistry(), deployStateBuilder.applicationPackage(applicationPackage).build());
}
private void assertConfig(LbServicesConfig expected, LbServicesConfig actual) {
assertFalse(expected.toString().isEmpty());
assertFalse(actual.toString().isEmpty());
assertEquals(actual.toString(), expected.toString());
assertEquals(ConfigPayload.fromInstance(expected).toString(true), ConfigPayload.fromInstance(actual).toString(true));
}
private TestProperties getTestproperties(ApplicationId applicationId) {
return new TestProperties()
.setHostedVespa(true)
.setZoneDnsSuffixes(zoneDnsSuffixes)
.setApplicationId(applicationId);
}
}
|
package org.terracotta.consensus;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.terracotta.consensus.entity.CoordinationServerEntityService;
import org.terracotta.consensus.entity.client.ClientCoordinationEntityService;
import org.terracotta.passthrough.PassthroughServer;
/**
*
* @author cdennis
*/
public final class TestUtils {
private TestUtils() {
//singleton
}
public static PassthroughServer createServer() {
PassthroughServer server = new PassthroughServer();
server.registerServerEntityService(new CoordinationServerEntityService());
server.registerClientEntityService(new ClientCoordinationEntityService());
server.start(true, false);
return server;
}
public static <T> Future<T> inOtherThread(Callable<T> task) {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
return executor.submit(task);
} finally {
executor.shutdown();
}
}
}
|
package it.unibz.inf.ontop.iq.type.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import it.unibz.inf.ontop.dbschema.Attribute;
import it.unibz.inf.ontop.dbschema.RelationDefinition;
import it.unibz.inf.ontop.exception.NonUniqueTermTypeException;
import it.unibz.inf.ontop.iq.IQTree;
import it.unibz.inf.ontop.iq.LeafIQTree;
import it.unibz.inf.ontop.iq.node.*;
import it.unibz.inf.ontop.iq.visit.IQVisitor;
import it.unibz.inf.ontop.model.atom.DataAtom;
import it.unibz.inf.ontop.model.atom.RelationPredicate;
import it.unibz.inf.ontop.model.term.ImmutableTerm;
import it.unibz.inf.ontop.model.term.NonVariableTerm;
import it.unibz.inf.ontop.model.term.Variable;
import it.unibz.inf.ontop.model.term.VariableOrGroundTerm;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TermTypeInference;
import it.unibz.inf.ontop.iq.type.UniqueTermTypeExtractor;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import java.util.Optional;
import java.util.stream.IntStream;
public class BasicUniqueTermTypeExtractor implements UniqueTermTypeExtractor {
@Inject
private BasicUniqueTermTypeExtractor() {
}
@Override
public Optional<TermType> extractUniqueTermType(ImmutableTerm term, IQTree subTree) {
return (term instanceof Variable)
? extractTypeFromVariable((Variable)term, subTree)
: extractType((NonVariableTerm) term, subTree);
}
private Optional<TermType> extractTypeFromVariable(Variable variable, IQTree subTree) {
return subTree.acceptVisitor(new TermTypeVariableVisitor(variable, this));
}
private Optional<TermType> extractType(NonVariableTerm nonVariableTerm, IQTree subTree) {
return nonVariableTerm.inferType()
.flatMap(i -> i.getTermType()
.map(Optional::of)
// Continues on a type of a variable defined in the sub-tree
.orElseGet(() -> i.getVariable()
.flatMap(v -> extractTypeFromVariable(v, subTree))));
}
protected static class TermTypeVariableVisitor implements IQVisitor<Optional<TermType>> {
protected final Variable variable;
protected final UniqueTermTypeExtractor typeExtractor;
protected TermTypeVariableVisitor(Variable variable, UniqueTermTypeExtractor typeExtractor) {
this.variable = variable;
this.typeExtractor = typeExtractor;
}
@Override
public Optional<TermType> visitIntensionalData(IntensionalDataNode dataNode) {
return Optional.empty();
}
@Override
public Optional<TermType> visitExtensionalData(ExtensionalDataNode dataNode) {
DataAtom<RelationPredicate> projectionAtom = dataNode.getProjectionAtom();
RelationDefinition relationDefinition = projectionAtom.getPredicate().getRelationDefinition();
ImmutableList<? extends VariableOrGroundTerm> arguments = projectionAtom.getArguments();
return IntStream.range(0, arguments.size())
.filter(i -> arguments.get(i).equals(variable))
.boxed()
.map(i -> relationDefinition.getAttribute(i + 1))
.map(Attribute::getTermType)
.filter(Optional::isPresent)
.map(o -> (TermType) o.get())
.findAny();
}
@Override
public Optional<TermType> visitEmpty(EmptyNode node) {
return Optional.empty();
}
@Override
public Optional<TermType> visitTrue(TrueNode node) {
return Optional.empty();
}
@Override
public Optional<TermType> visitNative(NativeNode nativeNode) {
return Optional.empty();
}
@Override
public Optional<TermType> visitNonStandardLeafNode(LeafIQTree leafNode) {
return Optional.empty();
}
@Override
public Optional<TermType> visitConstruction(ConstructionNode rootNode, IQTree child) {
return typeExtractor.extractUniqueTermType(rootNode.getSubstitution().apply(variable), child);
}
@Override
public Optional<TermType> visitFilter(FilterNode rootNode, IQTree child) {
return child.acceptVisitor(this);
}
@Override
public Optional<TermType> visitDistinct(DistinctNode rootNode, IQTree child) {
return child.acceptVisitor(this); }
@Override
public Optional<TermType> visitSlice(SliceNode sliceNode, IQTree child) {
return child.acceptVisitor(this); }
@Override
public Optional<TermType> visitOrderBy(OrderByNode rootNode, IQTree child) {
return child.acceptVisitor(this); }
@Override
public Optional<TermType> visitNonStandardUnaryNode(UnaryOperatorNode rootNode, IQTree child) {
return Optional.empty();
}
/**
* Only consider the right child for right-specific variables
*/
@Override
public Optional<TermType> visitLeftJoin(LeftJoinNode rootNode, IQTree leftChild, IQTree rightChild) {
if (leftChild.getVariables().contains(variable)) {
return leftChild.acceptVisitor(this);
}
else if (rightChild.getVariables().contains(variable)) {
return rightChild.acceptVisitor(this);
}
else
return Optional.empty();
}
@Override
public Optional<TermType> visitNonStandardBinaryNonCommutativeNode(BinaryNonCommutativeOperatorNode rootNode,
IQTree leftChild, IQTree rightChild) {
return Optional.empty();
}
/**
* Returns the first type found for a variable.
*
* If multiple types could have been found -> not matching -> will be later eliminated
*
*/
@Override
public Optional<TermType> visitInnerJoin(InnerJoinNode rootNode, ImmutableList<IQTree> children) {
return children.stream()
.map(c -> c.acceptVisitor(this))
.filter(Optional::isPresent)
.findAny()
.orElse(Optional.empty());
}
@Override
public Optional<TermType> visitUnion(UnionNode rootNode, ImmutableList<IQTree> children) {
ImmutableSet<TermType> termTypes = children.stream()
.map(c -> c.acceptVisitor(this))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableCollectors.toSet());
if (termTypes.size() > 1)
throw new NonUniqueTermTypeException(String.format("Multiple term types found for %s: %s",
variable, termTypes));
return termTypes.stream()
.findAny();
}
@Override
public Optional<TermType> visitNonStandardNaryNode(NaryOperatorNode rootNode, ImmutableList<IQTree> children) {
return Optional.empty();
}
}
}
|
package org.onetwo.common.hibernate;
import java.sql.Clob;
import java.util.Arrays;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.transform.AliasedTupleSubsetResultTransformer;
import org.onetwo.common.spring.SpringUtils;
import org.onetwo.common.utils.Assert;
import org.onetwo.common.utils.ReflectUtils;
import org.onetwo.common.utils.StringUtils;
import org.onetwo.common.utils.convert.Types;
import org.springframework.beans.BeanWrapper;
public class RowToBeanTransformer extends AliasedTupleSubsetResultTransformer {
private static final long serialVersionUID = -3068449276325782557L;
private final Class<?> resultClass;
private boolean isInitialized;
private String[] aliases;
private String[] propNames;
private boolean checkAlias;
public RowToBeanTransformer(Class<?> resultClass) {
this(resultClass, true);
}
public RowToBeanTransformer(Class<?> resultClass, boolean checkAlias) {
if ( resultClass == null ) {
throw new IllegalArgumentException( "resultClass cannot be null" );
}
isInitialized = false;
this.resultClass = resultClass;
this.checkAlias = checkAlias;
}
/**
* {@inheritDoc}
*/
public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
return false;
}
public Object transformTuple(Object[] tuple, String[] aliases) {
Object result;
try {
if ( ! isInitialized ) {
initialize( aliases );
}
else {
if(checkAlias)
check( aliases );
}
result = resultClass.newInstance();
BeanWrapper bw = SpringUtils.newBeanWrapper(result);
Object val;
String propName = "";
for ( int i = 0; i < aliases.length; i++ ) {
propName = propNames[i];
/*if(!bw.isWritableProperty(propName))
continue;*/
if(propName==null)
continue;
val = tuple[i];
Class<?> propertyType = bw.getPropertyType(propName);
// if(propertyType!=null && !propertyType.isInstance(val))
if(propertyType!=null && !Clob.class.isInstance(val))
val = Types.convertValue(val, propertyType);
/*if(val==null){
Class<?> propertyType = bw.getPropertyType(propNames[i]);
if(propertyType!=null && propertyType.isPrimitive())
continue;
}*/
bw.setPropertyValue(propName, val);
}
}
catch ( InstantiationException e ) {
throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
}
catch ( IllegalAccessException e ) {
throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
}
return result;
}
private void initialize(String[] aliases) {
Assert.notEmpty(aliases, "aliases is emtpy!");
this.aliases = new String[ aliases.length ];
this.propNames = new String[ aliases.length ];
List<String> resultPropNames = ReflectUtils.desribPropertiesName(resultClass);
for ( int i = 0; i < aliases.length; i++ ) {
String alias = aliases[ i ];
if ( alias != null ) {
this.aliases[i] = alias;
String propName = StringUtils.toPropertyName(alias);
if(resultPropNames.contains(propName)){
this.propNames[i] = propName;
}
}
}
isInitialized = true;
}
private void check(String[] aliases) {
if ( ! Arrays.equals( aliases, this.aliases ) ) {
throw new IllegalStateException(
"aliases are different from what is cached; aliases=" + Arrays.asList( aliases ) +
" cached=" + Arrays.asList( this.aliases ) );
}
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
RowToBeanTransformer that = ( RowToBeanTransformer ) o;
if ( ! resultClass.equals( that.resultClass ) ) {
return false;
}
if ( ! Arrays.equals( aliases, that.aliases ) ) {
return false;
}
return true;
}
public int hashCode() {
int result = resultClass.hashCode();
result = 31 * result + ( aliases != null ? Arrays.hashCode( aliases ) : 0 );
return result;
}
public void setCheckAlias(boolean checkAlias) {
this.checkAlias = checkAlias;
}
}
|
package de.peeeq.wurstio.jassinterpreter;
import com.google.common.collect.Maps;
import de.peeeq.wurstscript.WLogger;
import de.peeeq.wurstscript.intermediatelang.*;
import de.peeeq.wurstscript.intermediatelang.interpreter.NativesProvider;
import de.peeeq.wurstscript.jassinterpreter.TestFailException;
import de.peeeq.wurstscript.jassinterpreter.TestSuccessException;
import java.util.Map;
import java.util.Random;
/**
* provides native functions which are invoked via reflection a function should
* only take and return ILconsts
* <p>
* remember that all functions must be
*/
@SuppressWarnings("ucd") // ignore unused code detector warnings, because this class uses reflection
public class NativeFunctionsIO extends ReflectionBasedNativeProvider implements NativesProvider {
private Random r = new Random(0);
@Native
public void testSuccess() {
throw TestSuccessException.instance;
}
public void testFail(ILconstString msg) {
throw new TestFailException(msg.getVal());
}
public void BJDebugMsg(ILconstString msg) {
outStream.println(msg.getVal());
}
public void println(ILconstString msg) {
outStream.println(msg.getVal());
}
public void $debugPrint(ILconstString msg) {
outStream.println(msg.getVal());
throw new DebugPrintError(msg.getVal());
}
public ILconstInt ModuloInteger(ILconstInt a, ILconstInt b) {
return new ILconstInt(a.getVal() % b.getVal());
}
public ILconstReal ModuloReal(ILconstReal a, ILconstReal b) {
return new ILconstReal(a.getVal() % b.getVal());
}
@Native
public ILconstString I2S(ILconstInt i) {
return new ILconstString("" + i.getVal());
}
@Native
public ILconstString R2S(ILconstReal r) {
return new ILconstString("" + r.getVal());
}
public ILconstInt R2I(ILconstReal i) {
return new ILconstInt((int) i.getVal());
}
public ILconstReal I2R(ILconstInt i) {
return new ILconstReal(i.getVal());
}
@Native
public ILconstInt StringHash(ILconstString s) {
// TODO can we use same string hash function as used in wc3?
WLogger.info("stringhash of <" + s.getVal() + "> = " + s.getVal().hashCode());
return new ILconstInt(s.getVal().hashCode());
}
@Native
public ILconstNull Player(ILconstInt p) {
return ILconstNull.instance();
}
@Native
public ILconstInt GetPlayerId(ILconstNull p) {
return ILconstInt.create(0);
}
public IlConstHandle InitHashtable() {
return new IlConstHandle(getRandomName("ht"), Maps.newLinkedHashMap());
}
public void SaveInteger(IlConstHandle ht, ILconstInt key1, ILconstInt key2, ILconstInt value) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.computeIfAbsent(key1.getVal(), k -> Maps.newLinkedHashMap());
map2.put(key2.getVal(), value);
}
public ILconstInt LoadInteger(IlConstHandle ht, ILconstInt key1, ILconstInt key2) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.get(key1.getVal());
if (map2 != null) {
Object value = map2.get(key2.getVal());
if (value instanceof ILconstInt) {
return (ILconstInt) value;
}
}
return ILconstInt.create(0);
}
public ILconstInt RemoveSavedInteger(IlConstHandle ht, ILconstInt key1, ILconstInt key2) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.get(key1.getVal());
if (map2 != null) {
map2.remove(key2.getVal());
}
return ILconstInt.create(0);
}
public void SaveStr(IlConstHandle ht, ILconstInt key1, ILconstInt key2, ILconstString value) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.computeIfAbsent(key1.getVal(), k -> Maps.newLinkedHashMap());
map2.put(key2.getVal(), value);
WLogger.info("savestr of key1: " + key1.getVal() + ", key2: " + key2.getVal() + ", val: " + value.getVal());
}
public ILconstString LoadStr(IlConstHandle ht, ILconstInt key1, ILconstInt key2) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.get(key1.getVal());
if (map2 != null) {
Object value = map2.get(key2.getVal());
if (value instanceof ILconstString) {
return (ILconstString) value;
}
}
return new ILconstString("");
}
public ILconstString RemoveSavedString(IlConstHandle ht, ILconstInt key1, ILconstInt key2) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.get(key1.getVal());
if (map2 != null) {
map2.remove(key2.getVal());
}
return new ILconstString("");
}
public ILconstBool HaveSavedString(IlConstHandle ht, ILconstInt key1, ILconstInt key2) {
@SuppressWarnings("unchecked")
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
Map<Integer, Object> map2 = map.get(key1.getVal());
if (map2 != null) {
return ILconstBool.instance(map2.containsKey(key2.getVal()));
}
return ILconstBool.FALSE;
}
public ILconstInt FlushChildHashtable(IlConstHandle ht, ILconstInt parentKey) {
Map<Integer, Map<Integer, Object>> map = (Map<Integer, Map<Integer, Object>>) ht.getObj();
map.remove(parentKey.getVal());
return ILconstInt.create(0);
}
public ILconstReal SquareRoot(ILconstReal r) {
return new ILconstReal(Math.sqrt(r.getVal()));
}
public ILconstReal Sin(ILconstReal r) {
return new ILconstReal(Math.sin(r.getVal()));
}
public ILconstReal Cos(ILconstReal r) {
return new ILconstReal(Math.cos(r.getVal()));
}
public ILconstReal Tan(ILconstReal r) {
return new ILconstReal(Math.tan(r.getVal()));
}
public ILconstReal ATan(ILconstReal r) {
return new ILconstReal(Math.atan(r.getVal()));
}
public ILconstReal Atan2(ILconstReal y, ILconstReal x) {
return new ILconstReal(Math.atan2(y.getVal(), x.getVal()));
}
public IlConstHandle GetLocalPlayer() {
return new IlConstHandle("Local Player", "local player");
}
private String getRandomName(String string) {
return string + new Random().nextInt(100);
}
public void DisplayTimedTextToPlayer(Object player, ILconstReal x, ILconstReal y, ILconstReal duration,
ILconstString msg) {
outStream.println(msg.getVal());
}
public ILconstInt StringLength(ILconstString string) {
return new ILconstInt(string.getVal().length());
}
public ILconstString SubString(ILconstString string, ILconstInt start, ILconstInt end) {
return new ILconstString(string.getVal().substring(start.getVal(), end.getVal()));
}
public ILconstString StringCase(ILconstString string, ILconstBool upperCase) {
return new ILconstString(
upperCase.getVal() ?
string.getVal().toUpperCase()
: string.getVal().toLowerCase());
}
public void testPrint(ILconstString msg) {
outStream.println(msg.getVal());
}
public ILconstReal GetRandomReal(ILconstReal a, ILconstReal b) {
return new ILconstReal(a.getVal() + r.nextFloat() * (b.getVal() - a.getVal()));
}
public ILconstInt GetRandomInt(ILconstInt a, ILconstInt b) {
return new ILconstInt(a.getVal() + r.nextInt(1 + b.getVal() - a.getVal()));
}
}
|
//$HeadURL$
package org.deegree.services.controller.wfs;
import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX;
import static org.deegree.gml.GMLVersion.GML_31;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.deegree.commons.utils.QNameUtils;
import org.deegree.cs.CRS;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.feature.persistence.FeatureStore;
import org.deegree.feature.persistence.query.Query;
import org.deegree.feature.types.FeatureType;
import org.deegree.feature.types.property.PropertyType;
import org.deegree.filter.Filter;
import org.deegree.filter.Filters;
import org.deegree.filter.IdFilter;
import org.deegree.filter.OperatorFilter;
import org.deegree.filter.expression.PropertyName;
import org.deegree.filter.sort.SortProperty;
import org.deegree.filter.spatial.BBOX;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.Geometry;
import org.deegree.geometry.GeometryFactory;
import org.deegree.geometry.GeometryTransformer;
import org.deegree.gml.GMLVersion;
import org.deegree.protocol.wfs.getfeature.BBoxQuery;
import org.deegree.protocol.wfs.getfeature.FeatureIdQuery;
import org.deegree.protocol.wfs.getfeature.FilterQuery;
import org.deegree.protocol.wfs.getfeature.GetFeature;
import org.deegree.protocol.wfs.getfeature.TypeName;
import org.deegree.protocol.wfs.getfeature.XLinkPropertyName;
import org.deegree.services.controller.ows.OWSException;
import org.deegree.services.wfs.WFService;
import org.jaxen.NamespaceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Responsible for validating the queries contained in {@link GetFeature} requests and generating a corresponding
* sequence of feature store queries.
* <p>
* Also performs some normalizing on the values of {@link PropertyName}s. TODO describe strategy
* </p>
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
class GetFeatureAnalyzer {
private final GeometryFactory geomFac = new GeometryFactory();
private static final Logger LOG = LoggerFactory.getLogger( GetFeatureAnalyzer.class );
private final WFService service;
private final GMLVersion outputFormat;
private final Set<FeatureType> requestedFts = new HashSet<FeatureType>();
private final Map<Query, org.deegree.protocol.wfs.getfeature.Query> queryToWFSQuery = new HashMap<Query, org.deegree.protocol.wfs.getfeature.Query>();
private final Map<FeatureStore, List<Query>> fsToQueries = new LinkedHashMap<FeatureStore, List<Query>>();
private PropertyName[] requestedProps = null;
private XLinkPropertyName[] xlinkProps = null;
private CRS requestedCrs;
private boolean allFtsPossible;
private final boolean checkAreaOfUse;
/**
* Creates a new {@link GetFeatureAnalyzer}.
*
* @param request
* get feature request to be performed, must not be <code>null</code>
* @param service
* {@link WFService} to be used, must not be <code>null</code>
* @param outputFormat
* requested GML version, must not be <code>null</code>
* @param checkInputDomain
* true, if geometries in query constraints should be checked against validity domain of the SRS (needed
* for CITE 1.1.0 compliance)
* @throws OWSException
* if the request cannot be performed, e.g. because it queries feature types that are not served
*/
GetFeatureAnalyzer( GetFeature request, WFService service, GMLVersion outputFormat, boolean checkInputDomain )
throws OWSException {
this.service = service;
this.outputFormat = outputFormat;
this.checkAreaOfUse = checkInputDomain;
// generate validated feature store queries
org.deegree.protocol.wfs.getfeature.Query[] wfsQueries = request.getQueries();
Query[] queries = new Query[wfsQueries.length];
if ( queries.length == 0 ) {
// TODO perform the check here?
String msg = "Either the typeName parameter must be present or the query must provide feature ids.";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "typeName" );
}
for ( int i = 0; i < wfsQueries.length; i++ ) {
org.deegree.protocol.wfs.getfeature.Query wfsQuery = wfsQueries[i];
Query query = validateQuery( wfsQuery );
queries[i] = query;
queryToWFSQuery.put( query, wfsQuery );
// TODO what about queries with different SRS?
if ( wfsQuery.getSrsName() != null ) {
requestedCrs = wfsQuery.getSrsName();
}
}
// associate queries with feature stores
for ( Query query : queries ) {
if ( query.getTypeNames().length == 0 ) {
for ( FeatureStore fs : service.getStores() ) {
List<Query> fsQueries = fsToQueries.get( fs );
if ( fsQueries == null ) {
fsQueries = new ArrayList<Query>();
fsToQueries.put( fs, fsQueries );
}
fsQueries.add( query );
}
} else {
FeatureStore fs = service.getStore( query.getTypeNames()[0].getFeatureTypeName() );
List<Query> fsQueries = fsToQueries.get( fs );
if ( fsQueries == null ) {
fsQueries = new ArrayList<Query>();
fsToQueries.put( fs, fsQueries );
}
fsQueries.add( query );
}
}
// TODO cope with more queries than one
if ( wfsQueries.length == 1 ) {
if ( wfsQueries[0] instanceof FilterQuery ) {
FilterQuery featureQuery = ( (FilterQuery) wfsQueries[0] );
if ( featureQuery.getPropertyNames() != null ) {
this.requestedProps = featureQuery.getPropertyNames();
}
if ( featureQuery.getXLinkPropertyNames() != null && featureQuery.getXLinkPropertyNames().length > 0 ) {
this.xlinkProps = featureQuery.getXLinkPropertyNames();
}
} else if ( wfsQueries[0] instanceof BBoxQuery ) {
BBoxQuery bboxQuery = ( (BBoxQuery) wfsQueries[0] );
if ( bboxQuery.getPropertyNames() != null && bboxQuery.getPropertyNames().length > 0 ) {
// TODO cope with arrays with more than one entry
this.requestedProps = bboxQuery.getPropertyNames()[0];
}
if ( bboxQuery.getXLinkPropertyNames() != null && bboxQuery.getXLinkPropertyNames().length > 0 ) {
// TODO cope with arrays with more than one entry
this.xlinkProps = bboxQuery.getXLinkPropertyNames()[0];
}
} else if ( wfsQueries[0] instanceof FeatureIdQuery ) {
FeatureIdQuery idQuery = ( (FeatureIdQuery) wfsQueries[0] );
if ( idQuery.getPropertyNames() != null && idQuery.getPropertyNames().length > 0 ) {
// TODO cope with arrays with more than one entry
this.requestedProps = idQuery.getPropertyNames()[0];
}
if ( idQuery.getXLinkPropertyNames() != null && idQuery.getXLinkPropertyNames().length > 0 ) {
// TODO cope with arrays with more than one entry
this.xlinkProps = idQuery.getXLinkPropertyNames()[0];
}
}
}
}
/**
* Returns all {@link FeatureType}s that may be returned in the response to the request.
*
* @return list of requested feature types, or <code>null</code> if any of the feature types served by the WFS could
* be returned (happens only for KVP-request with feature ids and without typenames)
*/
Collection<FeatureType> getFeatureTypes() {
return allFtsPossible ? null : requestedFts;
}
/**
* Returns the feature store queries that have to performed for this request.
*
* @return the feature store queries that have to performed, never <code>null</code>
*/
Map<FeatureStore, List<Query>> getQueries() {
return fsToQueries;
}
/**
* Returns the crs that the returned geometries should have.
*
* TODO what about multiple queries with different CRS
*
* @return the crs, or <code>null</code> (use native crs)
*/
CRS getRequestedCRS() {
return requestedCrs;
}
/**
* Returns the features properties to be included in the output.
*
* TODO what about multiple queries that specify different sets of properties
*
* @return features properties to be include or <code>null</code> (include all properties)
*/
PropertyName[] getRequestedProps() {
return requestedProps;
}
/**
* Returns the specific XLink-behaviour for features properties.
*
* TODO what about multiple queries that specify different sets of properties
*
* @return specific XLink-behaviour or <code>null</code> (no specific behaviour)
*/
XLinkPropertyName[] getXLinkProps() {
return xlinkProps;
}
/**
* Builds a feature store {@link Query} from the given WFS query and checks if the feature type / property name
* references in the given {@link Query} are resolvable against the served application schema.
* <p>
* Incorrectly or un-qualified feature type or property names are repaired. These often stem from WFS 1.0.0
* KVP-requests (which doesn't have a namespace parameter) or broken clients.
* </p>
*
* @param wfsQuery
* query to be validated, must not be <code>null</code>
* @return the feature store query, using only correctly fully qualified feature / property names
* @throws OWSException
* if an unresolvable feature type / property name is used
*/
private Query validateQuery( org.deegree.protocol.wfs.getfeature.Query wfsQuery )
throws OWSException {
// requalify query typenames and keep track of them
TypeName[] wfsTypeNames = wfsQuery.getTypeNames();
TypeName[] typeNames = new TypeName[wfsTypeNames.length];
FeatureStore commonFs = null;
for ( int i = 0; i < wfsTypeNames.length; i++ ) {
String alias = wfsTypeNames[i].getAlias();
FeatureType ft = service.lookupFeatureType( wfsTypeNames[i].getFeatureTypeName() );
if ( ft == null ) {
String msg = "Feature type with name '" + wfsTypeNames[i].getFeatureTypeName()
+ "' is not served by this WFS.";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "typeName" );
}
FeatureStore fs = service.getStore( ft.getName() );
if ( commonFs != null ) {
if ( fs != commonFs ) {
String msg = "Requested join of feature types from different feature stores. This is not supported.";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "typeName" );
}
} else {
commonFs = fs;
}
requestedFts.add( ft );
QName ftName = ft.getName();
typeNames[i] = new TypeName( ftName, alias );
}
if ( wfsTypeNames.length == 0 ) {
allFtsPossible = true;
}
// check requested / filter property names and geometries
Filter filter = null;
if ( wfsQuery instanceof FilterQuery ) {
FilterQuery fQuery = ( (FilterQuery) wfsQuery );
if ( fQuery.getPropertyNames() != null ) {
for ( PropertyName propName : fQuery.getPropertyNames() ) {
validatePropertyName( propName, typeNames );
}
}
if ( fQuery.getXLinkPropertyNames() != null ) {
for ( XLinkPropertyName xlinkPropName : fQuery.getXLinkPropertyNames() ) {
validatePropertyName( xlinkPropName.getPropertyName(), typeNames );
}
}
if ( fQuery.getFilter() != null ) {
for ( PropertyName pt : Filters.getPropertyNames( fQuery.getFilter() ) ) {
validatePropertyName( pt, typeNames );
}
if ( checkAreaOfUse ) {
for ( Geometry geom : Filters.getGeometries( fQuery.getFilter() ) ) {
validateGeometryConstraint( geom, wfsQuery.getSrsName() );
}
}
}
filter = fQuery.getFilter();
} else if ( wfsQuery instanceof BBoxQuery ) {
BBoxQuery bboxQuery = (BBoxQuery) wfsQuery;
PropertyName[][] propNames = bboxQuery.getPropertyNames();
if ( propNames != null ) {
for ( PropertyName[] propertyNames : propNames ) {
for ( PropertyName propertyName : propertyNames ) {
validatePropertyName( propertyName, typeNames );
}
}
}
XLinkPropertyName[][] xlinkPropNames = bboxQuery.getXLinkPropertyNames();
if ( xlinkPropNames != null ) {
for ( XLinkPropertyName[] propertyNames : xlinkPropNames ) {
for ( XLinkPropertyName propertyName : propertyNames ) {
validatePropertyName( propertyName.getPropertyName(), typeNames );
}
}
}
validateGeometryConstraint( ( (BBoxQuery) wfsQuery ).getBBox(), wfsQuery.getSrsName() );
Envelope bbox = bboxQuery.getBBox();
BBOX bboxOperator = new BBOX( bbox );
filter = new OperatorFilter( bboxOperator );
} else if ( wfsQuery instanceof FeatureIdQuery ) {
FeatureIdQuery fidQuery = (FeatureIdQuery) wfsQuery;
PropertyName[][] propNames = fidQuery.getPropertyNames();
if ( propNames != null ) {
for ( PropertyName[] propertyNames : propNames ) {
for ( PropertyName propertyName : propertyNames ) {
validatePropertyName( propertyName, typeNames );
}
}
}
XLinkPropertyName[][] xlinkPropNames = fidQuery.getXLinkPropertyNames();
if ( xlinkPropNames != null ) {
for ( XLinkPropertyName[] propertyNames : xlinkPropNames ) {
for ( XLinkPropertyName propertyName : propertyNames ) {
validatePropertyName( propertyName.getPropertyName(), typeNames );
}
}
}
filter = new IdFilter( fidQuery.getFeatureIds() );
}
if ( wfsTypeNames.length == 0 && ( filter == null || !( filter instanceof IdFilter ) ) ) {
String msg = "Either the typeName parameter must be present or the query must provide feature ids.";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "typeName" );
}
SortProperty[] sortProps = wfsQuery.getSortBy();
if ( sortProps != null ) {
for ( SortProperty sortProperty : sortProps ) {
validatePropertyName( sortProperty.getSortProperty(), typeNames );
}
}
return new Query( typeNames, filter, wfsQuery.getFeatureVersion(), wfsQuery.getSrsName(), sortProps );
}
private void validatePropertyName( PropertyName propName, TypeName[] typeNames )
throws OWSException {
// no check possible if feature type is unknown
if ( typeNames.length > 0 ) {
if ( propName.isSimple() ) {
if ( !isPrefixedAndBound( propName ) ) {
repairSimpleUnqualified( propName, typeNames[0] );
}
// check that the propName is indeed valid as belonging to serviced features
QName name = getPropertyNameAsQName( propName );
if ( name != null ) {
if ( typeNames.length == 1 ) {
FeatureType ft = service.lookupFeatureType( typeNames[0].getFeatureTypeName() );
if ( ft.getPropertyDeclaration( name, outputFormat ) == null ) {
String msg = "Specified PropertyName '" + propName.getPropertyName() + "' (='" + name
+ "') does not exist for feature type '" + ft.getName() + "'.";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "PropertyName" );
}
}
// TODO really skip this check for join queries?
}
} else {
// TODO property name may be an XPath and use aliases...
}
}
}
/**
* Returns whether the propName has to be considered for re-qualification.
*
* @param propName
* @return
*/
private boolean isPrefixedAndBound( PropertyName propName ) {
QName name = propName.getAsQName();
return !name.getPrefix().equals( DEFAULT_NS_PREFIX )
&& !name.getNamespaceURI().equals( XMLConstants.NULL_NS_URI );
}
/**
* Repairs a {@link PropertyName} that contains the local name of a {@link FeatureType}'s property or a prefixed
* name, but without a correct namespace binding.
* <p>
* This types of propertynames especially occurs in WFS 1.0.0 requests.
* </p>
*
* @param propName
* property name to be repaired, must be "simple", i.e. contain only of a QName
* @param typeName
* feature type specification from the query, must not be <code>null</code>
*/
private void repairSimpleUnqualified( PropertyName propName, TypeName typeName ) {
FeatureType ft = service.lookupFeatureType( typeName.getFeatureTypeName() );
List<QName> propNames = new ArrayList<QName>();
// TODO which GML version
for ( PropertyType pt : ft.getPropertyDeclarations( GML_31 ) ) {
propNames.add( pt.getName() );
}
QName match = QNameUtils.findBestMatch( propName.getAsQName(), propNames );
if ( !match.equals( propName.getAsQName() ) ) {
LOG.warn( "Repairing unqualified PropertyName: " + QNameUtils.toString( propName.getAsQName() ) + " -> "
+ QNameUtils.toString( match ) );
// vague match
String text = match.getLocalPart();
if ( !match.getPrefix().equals( DEFAULT_NS_PREFIX ) ) {
text = match.getPrefix() + ":" + match.getLocalPart();
}
org.deegree.commons.xml.NamespaceContext nsContext = new org.deegree.commons.xml.NamespaceContext();
nsContext.addNamespace( match.getPrefix(), match.getNamespaceURI() );
propName.set( text, nsContext );
}
}
// TODO do this properly
private QName getPropertyNameAsQName( PropertyName propName ) {
QName name = null;
NamespaceContext nsContext = propName.getNsContext();
String s = propName.getPropertyName();
int colonIdx = s.indexOf( ':' );
if ( !s.contains( "/" ) && colonIdx != -1 ) {
if ( Character.isLetterOrDigit( s.charAt( 0 ) ) && Character.isLetterOrDigit( s.charAt( s.length() - 1 ) ) ) {
String prefix = s.substring( 0, colonIdx );
String localName = s.substring( colonIdx + 1, s.length() );
String nsUri = null;
if ( nsContext != null ) {
nsUri = nsContext.translateNamespacePrefixToUri( prefix );
} else {
nsUri = service.getPrefixToNs().get( prefix );
if ( nsUri == null ) {
nsUri = XMLConstants.NULL_NS_URI;
}
}
name = new QName( nsUri, localName, prefix );
}
} else {
if ( !s.contains( "/" ) && !s.isEmpty() && Character.isLetterOrDigit( s.charAt( 0 ) )
&& Character.isLetterOrDigit( s.charAt( s.length() - 1 ) ) ) {
name = new QName( s );
}
}
return name;
}
private void validateGeometryConstraint( Geometry geom, CRS queriedCrs )
throws OWSException {
// check if geometry's bbox is inside the domain of its CRS
Envelope bbox = geom.getEnvelope();
if ( bbox.getCoordinateSystem() != null ) {
// check if geometry's bbox is valid with respect to the CRS domain
try {
double[] b = bbox.getCoordinateSystem().getAreaOfUse();
Envelope domainOfValidity = geomFac.createEnvelope( b[0], b[1], b[2], b[3], CRS.EPSG_4326 );
domainOfValidity = transform( domainOfValidity, bbox.getCoordinateSystem() );
if ( !bbox.isWithin( domainOfValidity ) ) {
String msg = "Invalid geometry constraint in filter. The envelope of the geometry is not within the domain of validity ('"
+ domainOfValidity + "') of its CRS ('" + bbox.getCoordinateSystem().getName() + "').";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "filter" );
}
} catch ( UnknownCRSException e ) {
// could not validate constraint, but let's assume it's met
} catch ( IllegalArgumentException e ) {
// could not validate constraint, but let's assume it's met
} catch ( TransformationException e ) {
// could not validate constraint, but let's assume it's met
}
}
// check if geometry's bbox is inside the validity domain of the queried CRS
if ( queriedCrs != null ) {
try {
double[] b = queriedCrs.getAreaOfUse();
Envelope domainOfValidity = geomFac.createEnvelope( b[0], b[1], b[2], b[3], CRS.EPSG_4326 );
domainOfValidity = transform( domainOfValidity, queriedCrs );
Envelope bboxTransformed = transform( bbox, queriedCrs );
if ( !bboxTransformed.isWithin( domainOfValidity ) ) {
String msg = "Invalid geometry constraint in filter. The envelope of the geometry is not within the domain of validity ('"
+ domainOfValidity + "') of the queried CRS ('" + queriedCrs.getName() + "').";
throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "filter" );
}
} catch ( UnknownCRSException e ) {
// could not validate constraint, but let's assume it's met
} catch ( IllegalArgumentException e ) {
// could not validate constraint, but let's assume it's met
} catch ( TransformationException e ) {
// could not validate constraint, but let's assume it's met
}
}
}
private Envelope transform( Envelope bbox, CRS targetCrs )
throws IllegalArgumentException, TransformationException, UnknownCRSException {
if ( bbox.getEnvelope().equals( targetCrs ) ) {
return bbox;
}
GeometryTransformer transformer = new GeometryTransformer( targetCrs.getWrappedCRS() );
return (Envelope) transformer.transform( bbox );
}
}
|
package org.owasp.dependencycheck.data.update;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.owasp.dependencycheck.data.UpdateException;
import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.data.nvdcve.NvdCve12Handler;
import org.owasp.dependencycheck.data.nvdcve.NvdCve20Handler;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.xml.sax.SAXException;
/**
* A callable task that will process a given set of NVD CVE xml files and update
* the Cve Database accordingly.
*
* @author Jeremy Long (jeremy.long@owasp.org)
*/
public class ProcessTask implements Callable<ProcessTask> {
/**
* A field to store any update exceptions that occur during the "call".
*/
private UpdateException exception = null;
/**
* Get the value of exception.
*
* @return the value of exception
*/
public UpdateException getException() {
return exception;
}
/**
* Set the value of exception.
*
* @param exception new value of exception
*/
public void setException(UpdateException exception) {
this.exception = exception;
}
/**
* A reference to the CveDB.
*/
private final CveDB cveDB;
/**
* A reference to the callable download task.
*/
private final CallableDownloadTask filePair;
/**
* A reference to the properties.
*/
private final DataStoreMetaInfo properties;
public ProcessTask(final CveDB cveDB, final DataStoreMetaInfo properties, final CallableDownloadTask filePair) {
this.cveDB = cveDB;
this.filePair = filePair;
this.properties = properties;
}
@Override
public ProcessTask call() throws Exception {
try {
processFiles();
} catch (UpdateException ex) {
this.exception = ex;
}
return this;
}
/**
* Imports the NVD CVE XML File into the Lucene Index.
*
* @param file the file containing the NVD CVE XML
* @param oldVersion contains the file containing the NVD CVE XML 1.2
* @throws ParserConfigurationException is thrown if there is a parser
* configuration exception
* @throws SAXException is thrown if there is a SAXException
* @throws IOException is thrown if there is a IO Exception
* @throws SQLException is thrown if there is a SQL exception
* @throws DatabaseException is thrown if there is a database exception
* @throws ClassNotFoundException thrown if the h2 database driver cannot be
* loaded
*/
protected void importXML(File file, File oldVersion) throws ParserConfigurationException,
SAXException, IOException, SQLException, DatabaseException, ClassNotFoundException {
final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser saxParser = factory.newSAXParser();
final NvdCve12Handler cve12Handler = new NvdCve12Handler();
saxParser.parse(oldVersion, cve12Handler);
final Map<String, List<VulnerableSoftware>> prevVersionVulnMap = cve12Handler.getVulnerabilities();
final NvdCve20Handler cve20Handler = new NvdCve20Handler();
cve20Handler.setCveDB(cveDB);
cve20Handler.setPrevVersionVulnMap(prevVersionVulnMap);
saxParser.parse(file, cve20Handler);
}
private void processFiles() throws UpdateException {
String msg = String.format("Processing Started for NVD CVE - %s", filePair.getNvdCveInfo().getId());
Logger.getLogger(StandardUpdate.class.getName()).log(Level.INFO, msg);
try {
importXML(filePair.getFirst(), filePair.getSecond());
cveDB.commit();
properties.save(filePair.getNvdCveInfo());
} catch (FileNotFoundException ex) {
throw new UpdateException(ex);
} catch (ParserConfigurationException ex) {
throw new UpdateException(ex);
} catch (SAXException ex) {
throw new UpdateException(ex);
} catch (IOException ex) {
throw new UpdateException(ex);
} catch (SQLException ex) {
throw new UpdateException(ex);
} catch (DatabaseException ex) {
throw new UpdateException(ex);
} catch (ClassNotFoundException ex) {
throw new UpdateException(ex);
} finally {
filePair.cleanup();
}
msg = String.format("Processing Complete for NVD CVE - %s", filePair.getNvdCveInfo().getId());
Logger.getLogger(StandardUpdate.class.getName()).log(Level.INFO, msg);
}
}
|
package org.owasp.dependencycheck.data.cpe;
import org.owasp.dependencycheck.data.cpe.IndexEntry;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Assert;
/**
*
* @author Jeremy Long (jeremy.long@owasp.org)
*/
public class IndexEntryTest extends TestCase {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of setName method, of class IndexEntry.
*
* @throws Exception is thrown when an exception occurs.
*/
@Test
public void testSetName() throws Exception {
String name = "cpe:/a:apache:struts:1.1:rc2";
IndexEntry instance = new IndexEntry();
instance.parseName(name);
Assert.assertEquals("apache", instance.getVendor());
Assert.assertEquals("struts", instance.getProduct());
}
}
|
package com.xpn.xwiki.it.selenium;
import junit.framework.Test;
import com.xpn.xwiki.it.selenium.framework.AbstractXWikiTestCase;
import com.xpn.xwiki.it.selenium.framework.AlbatrossSkinExecutor;
import com.xpn.xwiki.it.selenium.framework.XWikiTestSuite;
/**
* Tests the wiki editor.
*
* @version $Id: $
*/
public class WikiEditorTest extends AbstractXWikiTestCase
{
public static Test suite()
{
XWikiTestSuite suite = new XWikiTestSuite("Tests the wiki editor");
suite.addTestSuite(WikiEditorTest.class, AlbatrossSkinExecutor.class);
return suite;
}
@Override
protected void setUp() throws Exception
{
super.setUp();
loginAsAdmin();
}
public void testEmptyLineAndSpaceCharactersBeforeSectionTitleIsNotRemoved()
{
open("/xwiki/bin/edit/Test/WikiEdit?editor=wiki");
setFieldValue("content", "\n 1.1 Section\n\ntext");
clickEditSaveAndView();
open("/xwiki/bin/edit/Test/WikiEdit?editor=wiki");
assertEquals("\n 1.1 Section\n\ntext", getFieldValue("content"));
}
public void testBoldButton()
{
open("/xwiki/bin/edit/Test/WikiBoldButton?editor=wiki");
setFieldValue("content", "Here follows a bold text: ");
clickWikiBoldButton();
assertEquals("Failed to append bold marker", "Here follows a bold text: *Text in Bold*",
getFieldValue("content"));
setFieldValue("content", "Here follows a bold text: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "26");
clickWikiBoldButton();
assertEquals("Failed to insert bold marker",
"Here follows a bold text: *Text in Bold*\nAnd some content after...", getFieldValue("content"));
// TODO: We need to find out how to make a text selection in Selenium
}
public void testItalicsButton()
{
open("/xwiki/bin/edit/Test/WikiItalicsButton?editor=wiki");
setFieldValue("content", "Here follows an italics text: ");
clickWikiItalicsButton();
assertEquals("Failed to append italics marker", "Here follows an italics text: ~~Text in Italics~~",
getFieldValue("content"));
setFieldValue("content", "Here follows an italics text: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "30");
clickWikiItalicsButton();
assertEquals("Failed to insert italics marker",
"Here follows an italics text: ~~Text in Italics~~\nAnd some content after...", getFieldValue("content"));
// TODO: We need to find out how to make a text selection in Selenium
}
public void testUnderlineButton()
{
open("/xwiki/bin/edit/Test/WikiUnderlineButton?editor=wiki");
setFieldValue("content", "Here follows an underlined text: ");
clickWikiUnderlineButton();
assertEquals("Failed to append underline marker", "Here follows an underlined text: __Text in Underline__",
getFieldValue("content"));
setFieldValue("content", "Here follows an underlined text: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "33");
clickWikiUnderlineButton();
assertEquals("Failed to insert underline marker",
"Here follows an underlined text: __Text in Underline__\nAnd some content after...",
getFieldValue("content"));
// TODO: We need to find out how to make a text selection in Selenium
}
public void testLinkButton()
{
open("/xwiki/bin/edit/Test/WikiLinkButton?editor=wiki");
setFieldValue("content", "Here follows a link: ");
clickWikiLinkButton();
assertEquals("Failed to append link marker", "Here follows a link: [Link Example]", getFieldValue("content"));
setFieldValue("content", "Here follows a link: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "21");
clickWikiLinkButton();
assertEquals("Failed to insert link marker", "Here follows a link: [Link Example]\nAnd some content after...",
getFieldValue("content"));
// TODO: We need to find out how to make a text selection in Selenium
}
public void testHRButton()
{
open("/xwiki/bin/edit/Test/WikiHRButton?editor=wiki");
setFieldValue("content", "Here follows a ruler: ");
clickWikiHRButton();
assertEquals("Failed to append ruler marker", "Here follows a ruler: \n----\n", getFieldValue("content"));
setFieldValue("content", "Here follows a ruler: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "22");
clickWikiHRButton();
assertEquals("Failed to insert ruler marker", "Here follows a ruler: \n----\n\nAnd some content after...",
getFieldValue("content"));
}
public void testImageButton()
{
open("/xwiki/bin/edit/Test/WikiImageButton?editor=wiki");
setFieldValue("content", "Here follows an image: ");
clickWikiImageButton();
assertEquals("Failed to append image marker", "Here follows an image: {image:example.jpg}",
getFieldValue("content"));
setFieldValue("content", "Here follows an image: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "23");
clickWikiImageButton();
assertEquals("Failed to insert image marker",
"Here follows an image: {image:example.jpg}\nAnd some content after...", getFieldValue("content"));
// TODO: We need to find out how to make a text selection in Selenium
}
public void testSignatureButton()
{
open("/xwiki/bin/edit/Test/WikiSignatureButton?editor=wiki");
setFieldValue("content", "Here follows a signature: ");
clickWikiSignatureButton();
assertEquals("Failed to append signature marker", "Here follows a signature: #sign(\"XWiki.Admin\")sigtext",
getFieldValue("content"));
setFieldValue("content", "Here follows a signature: \nAnd some content after...");
getSelenium().setCursorPosition("id=content", "26");
clickWikiSignatureButton();
assertEquals("Failed to insert signature marker",
"Here follows a signature: #sign(\"XWiki.Admin\")sigtext\nAnd some content after...",
getFieldValue("content"));
// TODO: We need to find out how to make a text selection in Selenium
}
/**
* See XWIKI-1007
*/
public void testEmptyContent()
{
open("/xwiki/bin/edit/Test/EmptyWikiContent?editor=wiki");
setFieldValue("content", "this is some content");
clickEditSaveAndView();
assertFalse(getSelenium().isAlertPresent());
assertEquals(-1, getSelenium().getLocation().indexOf("/edit/"));
assertTextPresent("this is some content");
open("/xwiki/bin/edit/Test/EmptyWikiContent?editor=wiki");
setFieldValue("content", "");
clickEditSaveAndView();
assertFalse(getSelenium().isAlertPresent());
assertEquals(-1, getSelenium().getLocation().indexOf("/edit/"));
assertTextNotPresent("this is some content");
}
}
|
package com.xpn.xwiki.it.selenium;
import java.awt.event.KeyEvent;
import junit.framework.Test;
import com.xpn.xwiki.it.selenium.framework.AbstractWysiwygTestCase;
import com.xpn.xwiki.it.selenium.framework.AlbatrossSkinExecutor;
import com.xpn.xwiki.it.selenium.framework.XWikiTestSuite;
/**
* Tests for the custom list support, to handle and generate valid XHTML lists in the wysiwyg. At the moment, this class
* tests processing the rendered lists rather than creating new lists from the wysiwyg, to ensure that valid rendered
* lists are managed correctly.
*
* @version $Id$
*/
public class ListSupportTest extends AbstractWysiwygTestCase
{
public static Test suite()
{
XWikiTestSuite suite = new XWikiTestSuite("Tests valid XHTML list support in the wysiwyg editor.");
suite.addTestSuite(ListSupportTest.class, AlbatrossSkinExecutor.class);
return suite;
}
/**
* @see XWIKI-2734: Cannot edit the outer list item. The test is not deeply relevant as we are positioning the range
* programatically. The correct test would prove that the caret can be positioned there with the keys.
*/
public void testEmptyListItemsEditable()
{
setWikiContent("** rox");
// Check that a br is added in the parent list item so that it becomes editable
assertXHTML("<ul><li><br class=\"spacer\"><ul><li>rox</li></ul></li></ul>");
// Place the caret in the first list item
moveCaret("XWE.body.firstChild.firstChild", 0);
typeText("x");
assertXHTML("<ul><li>x<br class=\"spacer\"><ul><li>rox</li></ul></li></ul>");
}
/**
* Test the case when hitting enter in a list item before a sublist, that it creates an editable list item under.
* The test is not deeply relevant since we are positioning the range in the item under programatically. The correct
* test would prove that the caret can be positioned there with the keys.
*/
public void testEnterBeforeSublist()
{
setWikiContent("* x\n** rox");
moveCaret("XWE.body.firstChild.firstChild.firstChild", 1);
typeEnter();
// Check the created item is editable
assertXHTML("<ul><li>x</li><li><br class=\"spacer\"><ul><li>rox</li></ul></li></ul>");
moveCaret("XWE.body.firstChild.childNodes[1]", 0);
typeText("w");
assertXHTML("<ul><li>x</li><li>w<br class=\"spacer\"><ul><li>rox</li></ul></li></ul>");
}
/**
* Test the midas bug which causes the list items in a list to be replaced with an empty list and the caret to be
* left inside the ul, not editable.
*/
public void testEnterOnEntireList()
{
setWikiContent("* foo\n* bar");
// Set the selection around the list
select("XWE.body.firstChild.firstChild.firstChild", 0, "XWE.body.firstChild.lastChild.firstChild", 3);
typeEnter();
typeText("foobar");
assertXHTML("<p><br class=\"spacer\"></p>foobar");
}
/**
* Test delete works fine inside a list item, and before another element (such as bold).
*/
public void testDeleteInsideItem()
{
setWikiContent("* foo**bar**\n** far");
// Set the selection inside the foo text
moveCaret("XWE.body.firstChild.firstChild.firstChild", 1);
typeDelete();
assertXHTML("<ul><li>fo<strong>bar</strong><ul><li>far</li></ul></li></ul>");
// set the selection just before the bold text but inside the text before
moveCaret("XWE.body.firstChild.firstChild.firstChild", 2);
typeDelete();
assertXHTML("<ul><li>fo<strong>ar</strong><ul><li>far</li></ul></li></ul>");
}
/**
* Test backspace works fine inside a list item, and after another element (such as italic).
*/
public void testBackspaceInsideItem()
{
setWikiContent("* foo\n** b//arf//ar");
// Set the selection in the "ar" text in the second list item
moveCaret("XWE.body.firstChild.firstChild.lastChild.firstChild.lastChild", 1);
typeBackspace();
assertXHTML("<ul><li>foo<ul><li>b<em>arf</em>r</li></ul></li></ul>");
// delete again, now it should delete inside the em
typeBackspace();
assertXHTML("<ul><li>foo<ul><li>b<em>ar</em>r</li></ul></li></ul>");
}
/**
* Test that the delete at the end of the list works fine
*/
public void testDeleteInSameList()
{
setWikiContent("* foo\n* bar");
// Set the selection at the end of the first item
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foobar</li></ul>");
}
/**
* Test that the backspace at the beginning of the second item in a list moves the items together in the first list
* item.
*/
public void testBackspaceInSameList()
{
setWikiContent("* foo\n* bar");
// Set the selection at the end of the first item
moveCaret("XWE.body.firstChild.lastChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foobar</li></ul>");
}
/**
* Test that delete at the end of a list preserves browser default behaviour: for firefox is to join the two lists.
*/
public void testDeleteInDifferentLists()
{
setWikiContent("* foo\n\n* bar");
// Set the selection at the end of the first item
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foo</li><li>bar</li></ul>");
}
/**
* Test that backspace at the beginning of a list preserves browser default behaviour: for firefox is to join the
* two lists.
*/
public void testBackspaceInDifferentLists()
{
setWikiContent("* foo\n\n* bar");
// Set the selection at the end of the first item
moveCaret("XWE.body.lastChild.firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foo</li><li>bar</li></ul>");
}
/**
* Test that backspace at the beginning of a list after another list in an embedded document (two lists on the
* second level) preserves default behaviour: for firefox is to join the two lists.
*/
public void testBackspaceInEmbeddedDocumentDifferentLists()
{
setWikiContent("* foo\n* bar (((\n* foo 2\n1. bar 2)))");
moveCaret("XWE.body.firstChild.childNodes[1].childNodes[1].childNodes[1].firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foo</li><li>bar<div><ul><li>foo 2</li><li>bar 2</li></ul></div></li></ul>");
}
/**
* Test that delete at the end of a list before another list in an embedded document (two lists on the second level)
* preserves default behaviour: for firefox is to join the two lists.
*/
public void testDeleteInEmbeddedDocumentDifferentLists()
{
setWikiContent("* foo\n* bar (((\n1. foo 2\n* bar 2)))");
moveCaret("XWE.body.firstChild.childNodes[1].childNodes[1].firstChild.firstChild.firstChild", 5);
typeDelete();
assertXHTML("<ul><li>foo</li><li>bar<div><ol><li>foo 2</li><li>bar 2</li></ol></div></li></ul>");
}
public void testBackspaceInEmbeddedDocumentList()
{
setWikiContent("* foo(((bar\n* foar)))");
moveCaret("XWE.body.firstChild.firstChild.childNodes[1].childNodes[1].firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foo<div><p>barfoar</p></div></li></ul>");
}
public void testDeleteInEmbeddedDocumentList()
{
setWikiContent("* foo(((* bar\n\nfoar)))");
moveCaret("XWE.body.firstChild.firstChild.childNodes[1].firstChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foo<div><ul><li>barfoar</li></ul></div></li></ul>");
}
/**
* Tests that the delete moves the first item on another level in the item in which is executed.
*/
public void testDeleteBeforeSublist()
{
// 1/ with only one item -> the sublist should be removed
setWikiContent("* foo\n** bar\n");
// Set the selection at the end of the first item
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foobar</li></ul>");
// 2/ with more than one item -> only the first item should be moved to the list above
setWikiContent("* foo\n** bar\n** far");
// Set the selection at the end of the first item
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foobar<ul><li>far</li></ul></li></ul>");
}
/**
* Test that backspace at the beginning of an item in a sublist moves the item in the list item before, on a lower
* list level.
*/
public void testBackspaceBeginSublist()
{
// 1/ with only one item -> the sublist should be deleted
setWikiContent("* foo\n** bar\n");
// Set the selection at beginning of the first item in sublist
moveCaret("XWE.body.firstChild.firstChild.lastChild.firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foobar</li></ul>");
// 2/ with more than one item -> only the first item should be moved to the list above
setWikiContent("* foo\n** bar\n** far");
// Set the selection at beginning of the first item in sublist
moveCaret("XWE.body.firstChild.firstChild.lastChild.firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foobar<ul><li>far</li></ul></li></ul>");
}
/**
* Test that deleting at the end of a list item with a sublist with another sublist inside, moves the first sublist
* and the elements on level 3 are moved to level 2.
*/
public void testDeleteDecreasesLevelWithEmptyItem()
{
setWikiContent("* foo\n*** bar\n");
// Set the selection at beginning of the first item in sublist
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foo<br class=\"spacer\"><ul><li>bar</li></ul></li></ul>");
}
/**
* Test that hitting backspace at the beginning of a list item with a sublist moves this element in its parent list
* item and decreases the level of the subitems.
*/
public void testBackspaceDecreasesLevelWithEmptyItem()
{
setWikiContent("* foo\n*** bar\n");
// Set the selection at beginning of the first item in sublist
moveCaret("XWE.body.firstChild.firstChild.lastChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foo<br class=\"spacer\"><ul><li>bar</li></ul></li></ul>");
}
/**
* Test delete at the end of a sublist item on a higher level moves the list item on the lower level inside it.
*
* @see XWIKI-3114: Backspace is ignored at the beginning of a list item if the previous list item is on a lower
* level.
*/
public void testDeleteBeforePreviousLevelItem()
{
setWikiContent("* foo\n** bar\n* bar minus one");
// Set the selection at the end of "bar"
moveCaret("XWE.body.firstChild.firstChild.lastChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>foo<ul><li>barbar minus one</li></ul></li></ul>");
}
/**
* Test backspace at the beginning of a sublist item before a sublist moves the item on the lower level to the item
* on the higher level.
*
* @see XWIKI-3114: Backspace is ignored at the beginning of a list item if the previous list item is on a lower
* level.
*/
public void testBackspaceAfterPreviousLevelItem()
{
setWikiContent("* foo\n** bar\n* bar minus one");
// Set the selection at the end of "bar"
moveCaret("XWE.body.firstChild.lastChild.firstChild", 0);
typeBackspace();
assertXHTML("<ul><li>foo<ul><li>barbar minus one</li></ul></li></ul>");
}
/**
* Test deleting the last piece of text inside a list item with sublists, keeps the remaining list item empty but
* editable. The test is weak, since we position the range programatically. The true test should try to navigate to
* the list item.
*/
public void testDeleteAllTextInListItem()
{
setWikiContent("* foo\n* b\n** ar");
// Set the selection at the beginning of the text in the second list item
moveCaret("XWE.body.firstChild.lastChild.firstChild", 0);
typeDelete();
// test that the list structure is correct: two items one with a sublist
assertXHTML("<ul><li>foo</li><li><br class=\"spacer\"><ul><li>ar</li></ul></li></ul>");
// type in the empty list item
moveCaret("XWE.body.firstChild.lastChild", 0);
typeText("bar");
assertXHTML("<ul><li>foo</li><li>bar<br class=\"spacer\"><ul><li>ar</li></ul></li></ul>");
// now delete, to test that it jumps the <br>
typeDelete();
assertXHTML("<ul><li>foo</li><li>barar</li></ul>");
}
/**
* Test backspacing the last piece of text inside a list item with sublists, keeps the remaining list item empty but
* editable. The test is weak, since we position the range programatically. The true test should try to navigate to
* the list item.
*/
public void testBackspaceAllTextInListItem()
{
setWikiContent("* foo\n* b\n** ar");
// Set the selection at the end of the text in the second list item
moveCaret("XWE.body.firstChild.lastChild.firstChild", 1);
typeBackspace();
// test that the list structure is correct: two items one with a sublist
assertXHTML("<ul><li>foo</li><li><br class=\"spacer\"><ul><li>ar</li></ul></li></ul>");
// type in the empty list item
moveCaret("XWE.body.firstChild.lastChild", 0);
typeText("bar");
assertXHTML("<ul><li>foo</li><li>bar<br class=\"spacer\"><ul><li>ar</li></ul></li></ul>");
// Put the caret at the beginning of the sublist
moveCaret("XWE.body.firstChild.lastChild.lastChild.firstChild.firstChild", 0);
// now backspace, to test that it jumps the <br>
typeBackspace();
assertXHTML("<ul><li>foo</li><li>barar</li></ul>");
}
/**
* Test delete before text outside lists.
*/
public void testDeleteBeforeParagraph()
{
setWikiContent("* one\n* two\n\nFoobar");
// Set the selection at the end of the "two" list item
moveCaret("XWE.body.firstChild.lastChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>one</li><li>twoFoobar</li></ul>");
// now run the case with delete in a sublist
setWikiContent("* one\n** two\n\nFoobar");
// Set the selection at the end of the "two" list item
moveCaret("XWE.body.firstChild.firstChild.lastChild.firstChild.firstChild", 3);
typeDelete();
assertXHTML("<ul><li>one<ul><li>twoFoobar</li></ul></li></ul>");
}
/**
* Test backspace at the beginning of list item, after text outside lists.
*/
public void testBackspaceAfterParagraph()
{
setWikiContent("Foobar\n\n* one\n* two");
// Set the selection at the beginning of the "one" list item
moveCaret("XWE.body.lastChild.firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<p>Foobarone</p><ul><li>two</li></ul>");
// Now test the case when the list has a sublist, in which case FF keeps the sublist parent, as empty and
// editable
// Note that this behaves differently on Internet Explorer, unwrapping the sublist
setWikiContent("Foobar\n\n* one\n** two");
// Set the selection at the beginning of the "one" list item
moveCaret("XWE.body.lastChild.firstChild.firstChild", 0);
typeBackspace();
assertXHTML("<p>Foobarone</p><ul><li><br class=\"spacer\"><ul><li>two</li></ul></li></ul>");
}
/**
* Test deleting the whole selection on a list, on multiple list levels keeps the list valid. Test that the parents
* of the indented list items that stay are editable.
*/
public void testDeleteSelectionPreserveSublists()
{
setWikiContent("* one\n** two\n** three\n*** four\n*** five");
// Set the selection starting in the one element and ending in the four element
select("XWE.body.firstChild.firstChild.firstChild", 2,
"XWE.body.firstChild.firstChild.lastChild.lastChild.lastChild.firstChild.firstChild", 2);
typeDelete();
assertXHTML("<ul><li>on<ul><li><br class=\"spacer\"><ul><li>ur</li><li>five</li></ul></li></ul></li></ul>");
}
/**
* Test deleting the whole selection on a list, on multiple list levels deletes all the fully enclosed list items
* and lists, and keeps the result in a single list item if the selection ends are on the same list level.
*/
public void testDeleteSelectionDeletesEnclosedSublists()
{
setWikiContent("* one\n** two\n** three\n*** four\n** five\n* six");
// Set the selection starting in the one element and ending in the six element
select("XWE.body.firstChild.firstChild.firstChild", 2, "XWE.body.firstChild.lastChild.firstChild", 1);
typeDelete();
assertXHTML("<ul><li>onix</li></ul>");
}
/**
* Test creating a list with two items and indenting the second item. The indented item should be a sublist of the
* first item and the resulted HTML should be valid.
*/
public void testIndentNoSublist()
{
clickUnorderedListButton();
typeText("foo");
typeEnter();
typeText("bar");
assertXHTML("<ul><li>foo</li><li>bar<br class=\"spacer\"></li></ul>");
clickIndentButton();
assertXHTML("<ul><li>foo<ul><li>bar<br class=\"spacer\"></li></ul></li></ul>");
// test that the indented item cannot be indented once more
assertFalse(isIndentButtonEnabled());
moveCaret("XWE.body.firstChild.firstChild.childNodes[1].firstChild.firstChild", 0);
typeTab();
// check that nothing happened
assertXHTML("<ul><li>foo<ul><li>bar<br class=\"spacer\"></li></ul></li></ul>");
assertWiki("* foo\n** bar");
}
/**
* Test that indenting an item to the second level under a list item with a list already on the second level unifies
* the two lists.
*/
public void testIndentUnderSublist()
{
clickUnorderedListButton();
typeTextThenEnter("one");
typeTextThenEnter("two");
typeTab();
typeTextThenEnter("two plus one");
typeShiftTab();
typeText("three");
clickIndentButton();
assertXHTML("<ul><li>one</li><li>two<ul><li>two plus one</li>"
+ "<li>three<br class=\"spacer\"></li></ul></li></ul>");
assertWiki("* one\n* two\n** two plus one\n** three");
}
/**
* Test indenting (using the tab key) an item with a sublist, that the child sublist is indented with its parent.
*
* @see XWIKI-3118: Indenting a list item with a sublist works incorrectly.
* @see XWIKI-3117: Shift + Tab does works incorrect on an item that contains a sublist.
*/
public void testIndentOutdentWithSublist()
{
clickUnorderedListButton();
typeText("foo");
typeEnter();
typeText("bar");
clickIndentButton();
// move to the end of the foo element, hit enter, tab and type. Should create a new list item, parent of the bar
// sublist, tab should indent and type should add content
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeText("one");
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
typeEnter();
assertXHTML("<ul><li>foo</li><li>one<ul><li>bar<br class=\"spacer\"></li></ul></li></ul>");
// check that the list item is indentable, the list plugin is correctly recognizing lists (XWIKI-3061)
assertTrue(isIndentButtonEnabled());
clickIndentButton();
assertXHTML("<ul><li>foo<ul><li>one<ul><li>bar<br class=\"spacer\"></li></ul></li></ul></li></ul>");
assertWiki("* foo\n** one\n*** bar");
// select second element "one"
select("XWE.body.firstChild.firstChild.childNodes[1].firstChild.firstChild", 0,
"XWE.body.firstChild.firstChild.childNodes[1].firstChild.firstChild", 3);
// check that the list item is outdentable, the list plugin is correctly recognizing lists (XWIKI-3061)
assertTrue(isOutdentButtonEnabled());
clickOutdentButton();
assertXHTML("<ul><li>foo</li><li>one<ul><li>bar</li></ul></li></ul>");
moveCaret("XWE.body.firstChild.childNodes[1].childNodes[1].firstChild.firstChild", 0);
clickOutdentButton();
assertXHTML("<ul><li>foo</li><li>one</li><li>bar</li></ul>");
assertWiki("* foo\n* one\n* bar");
}
/**
* Test outdenting an item on the first level in a list: it should split the list in two and put the content of the
* unindented item in between.
*/
public void testOutdentOnFirstLevel()
{
clickUnorderedListButton();
typeTextThenEnter("one");
typeTextThenEnter("two");
typeTab();
typeTextThenEnter("two plus one");
typeShiftTab();
typeText("three");
// move caret at the beginning of the "two" item
moveCaret("XWE.body.firstChild.childNodes[1].firstChild", 0);
typeShiftTab();
assertXHTML("<ul><li>one</li></ul>two<ul><li>two plus one</li></ul>"
+ "<ul><li>three<br class=\"spacer\"></li></ul>");
assertWiki("* one\n\ntwo\n\n* two plus one\n\n* three");
}
/**
* Test outdenting an item on the second level inside a list item which also contains content after the sublist
* correctly moves the content in the outdented list item.
*/
public void testOutdentWithContentAfter()
{
setContent("<ul><li>one<br />before<ul><li>two</li><li>three</li><li>four</li></ul>after</li></ul>");
moveCaret("XWE.body.firstChild.firstChild.childNodes[3].childNodes[1].firstChild", 0);
assertTrue(isOutdentButtonEnabled());
clickOutdentButton();
assertXHTML("<ul><li>one<br>before<ul><li>two</li></ul></li><li>three<ul><li>four</li></ul>"
+ "after</li></ul>");
}
public void testDotAtEndDoesNotDelete()
{
setWikiContent("* foo\n* bar");
// Set the selection at the end of the first item
moveCaret("XWE.body.firstChild.firstChild.firstChild", 3);
// type the dot native, to make sure it goes through the browser's key handling code
getSelenium().keyPressNative(Integer.toString(KeyEvent.VK_PERIOD));
assertXHTML("<ul><li>foo.</li><li>bar</li></ul>");
}
/**
* @see XWIKI-3447: List detection is reversed
*/
public void testListDetection()
{
setWikiContent("before\n\n" + "* unordered list item\n*1. ordered sub-list item\n\n"
+ "1. ordered list item\n1*. unordered sub-list item");
// Outside lists
moveCaret("XWE.body.firstChild.firstChild", 3);
assertFalse(isOrderedListDetected());
assertFalse(isUnorderedListDetected());
// Inside unordered list item
moveCaret("XWE.body.childNodes[1].firstChild.firstChild", 4);
assertFalse(isOrderedListDetected());
assertTrue(isUnorderedListDetected());
// Inside ordered sub-list item
moveCaret("XWE.body.childNodes[1].firstChild.lastChild.firstChild.firstChild", 7);
assertTrue(isOrderedListDetected());
assertTrue(isUnorderedListDetected());
// Inside ordered list item
moveCaret("XWE.body.childNodes[2].firstChild.firstChild", 10);
assertTrue(isOrderedListDetected());
assertFalse(isUnorderedListDetected());
// Inside unordered sub-list item
moveCaret("XWE.body.childNodes[2].firstChild.lastChild.firstChild.firstChild", 9);
assertTrue(isOrderedListDetected());
assertTrue(isUnorderedListDetected());
}
/**
* @see XWIKI-3773: Adding and editing lists in table cells.
*/
public void testCreateListInTableCell()
{
insertTable();
typeText("a");
clickUnorderedListButton();
typeEnter();
typeText("b");
assertWiki("|=(((* a\n* b)))|= \n| | ");
}
/**
* Test indenting a list fragment by selecting all the items and hitting the indent button.
*/
public void testIndentListFragment()
{
setWikiContent("* one\n* two\n* three\n* three point one\n* three point two\n* three point three\n* four");
select("XWE.body.firstChild.childNodes[3].firstChild", 0, "XWE.body.firstChild.childNodes[5].firstChild", 17);
assertTrue(isIndentButtonEnabled());
clickIndentButton();
assertWiki("* one\n* two\n* three\n** three point one\n** three point two\n** three point three\n* four");
}
/**
* Test the usual use case about only indenting the parent one level further, without its sublist. This cannot be
* done in one because it is not a correct indent, from a semantic pov, but most users expect it to happen. The
* correct steps are to indent the parent and then outindent the sublist, which is the case tested by this function.
*/
public void testIndentParentWithNoSublist()
{
setWikiContent("* one\n* two\n* three\n** three point one\n** three point two\n** three point three\n* four");
select("XWE.body.firstChild.childNodes[2].firstChild", 0, "XWE.body.firstChild.childNodes[2].firstChild", 5);
assertTrue(isIndentButtonEnabled());
clickIndentButton();
select("XWE.body.firstChild.childNodes[1].childNodes[1].firstChild.childNodes[1].firstChild.firstChild", 0,
"XWE.body.firstChild.childNodes[1].childNodes[1].firstChild.childNodes[1].childNodes[2].firstChild", 17);
assertTrue(isOutdentButtonEnabled());
clickOutdentButton();
assertWiki("* one\n* two\n** three\n** three point one\n** three point two\n** three point three\n* four");
}
/**
* Tests indenting two items, amongst which one with a sublist and then outending the item with the sublist.
*/
public void testIndentItemWithSublistAndOutdent()
{
setWikiContent("* one\n* two\n* three\n** foo\n** bar\n* four\n* four\n* five");
select("XWE.body.firstChild.childNodes[2].firstChild", 0, "XWE.body.firstChild.childNodes[3].firstChild", 4);
assertTrue(isIndentButtonEnabled());
clickIndentButton();
assertWiki("* one\n* two\n** three\n*** foo\n*** bar\n** four\n* four\n* five");
select("XWE.body.firstChild.childNodes[1].childNodes[1].firstChild.firstChild", 0,
"XWE.body.firstChild.childNodes[1].childNodes[1].firstChild.childNodes[1].childNodes[1].firstChild", 3);
assertTrue(isOutdentButtonEnabled());
clickOutdentButton();
assertWiki("* one\n* two\n* three\n** foo\n** bar\n** four\n* four\n* five");
}
/**
* Tests a few indent and outdent operations on a list inside an embedded document (in this case, a table cell),
* preceded by another list in the previous table cell.
*/
public void testIndentOutdentInTableCell()
{
setWikiContent("|(((* item 1\n* item 2)))|(((* one\n** one plus one\n** one plus two\n* two\n* three)))\n| | ");
select(
"XWE.body.firstChild.firstChild.firstChild.childNodes[1].firstChild.firstChild.firstChild.childNodes[1]."
+ "childNodes[1].firstChild", 0,
"XWE.body.firstChild.firstChild.firstChild.childNodes[1].firstChild.firstChild.childNodes[1]."
+ "firstChild", 3);
assertTrue(isIndentButtonEnabled());
clickIndentButton();
assertWiki("|(((* item 1\n* item 2)))|(((* one\n** one plus one\n*** one plus two\n** two\n* three)))\n| | ");
select(
"XWE.body.firstChild.firstChild.firstChild.childNodes[1].firstChild.firstChild.firstChild.childNodes[1]."
+ "childNodes[1].firstChild", 0,
"XWE.body.firstChild.firstChild.firstChild.childNodes[1].firstChild.firstChild.childNodes[1]."
+ "firstChild", 5);
assertTrue(isOutdentButtonEnabled());
clickOutdentButton();
assertWiki("|(((* item 1\n* item 2)))|(((* one\n** one plus one\n*** one plus two\n* two\n\nthree)))\n| | ");
}
/**
* @return {@code true} if the current selection is inside an ordered list, {@code false} otherwise
*/
public boolean isOrderedListDetected()
{
return isToggleButtonDown("Ordered list");
}
/**
* @return {@code true} if the current selection is inside an unordered list, {@code false} otherwise
*/
public boolean isUnorderedListDetected()
{
return isToggleButtonDown("Unordered list");
}
}
|
package com.github.mcollovati.vaadin.exampleapp;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.github.mcollovati.vaadin.exampleapp.samples.MainScreen;
import com.github.mcollovati.vaadin.exampleapp.samples.authentication.AccessControl;
import com.github.mcollovati.vaadin.exampleapp.samples.authentication.BasicAccessControl;
import com.github.mcollovati.vaadin.exampleapp.samples.authentication.LoginScreen;
import com.github.mcollovati.vaadin.exampleapp.samples.authentication.LoginScreen.LoginListener;
import com.github.mcollovati.vertx.vaadin.VaadinVerticle;
import com.github.mcollovati.vertx.vaadin.communication.SockJSPushConnection;
import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Viewport;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
/**
* Main UI class of the application that shows either the login screen or the
* main view of the application depending on whether a user is signed in.
*
* The @Viewport annotation configures the viewport meta tags appropriately on
* mobile devices. Instead of device based scaling (default), using responsive
* layouts.
*/
@Viewport("user-scalable=no,initial-scale=1.0")
@Theme("mytheme")
@Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset")
@Push
public class MyUI extends UI {
private AccessControl accessControl = new BasicAccessControl();
private transient ScheduledExecutorService scheduledExecutorService;
@Override
protected void init(VaadinRequest vaadinRequest) {
setPushConnection(new SockJSPushConnection(this));
Responsive.makeResponsive(this);
setLocale(vaadinRequest.getLocale());
getPage().setTitle("My");
if (!accessControl.isUserSignedIn()) {
setContent(new LoginScreen(accessControl, new LoginListener() {
@Override
public void loginSuccessful() {
showMainView();
}
}));
} else {
showMainView();
}
}
@Override
public void attach() {
super.attach();
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.schedule(
() -> access(() -> getPage().setTitle("Changed"))
, 5, TimeUnit.SECONDS);
}
@Override
public void detach() {
super.detach();
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdown();
}
}
protected void showMainView() {
addStyleName(ValoTheme.UI_WITH_MENU);
setContent(new MainScreen(MyUI.this));
getNavigator().navigateTo(getNavigator().getState());
}
public AccessControl getAccessControl() {
return accessControl;
}
public static MyUI get() {
return (MyUI) UI.getCurrent();
}
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class ExampleUIVerticle extends VaadinVerticle {
}
}
|
/* This class is part of the XP framework's EAS connectivity
*
* $Id$
*/
package net.xp_framework.easc.protocol.standard;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
import net.xp_framework.easc.server.Handler;
import net.xp_framework.easc.protocol.standard.MessageType;
import net.xp_framework.easc.util.ByteCountedString;
import net.xp_framework.easc.server.Delegate;
import net.xp_framework.easc.protocol.standard.Header;
import net.xp_framework.easc.server.ServerContext;
import static net.xp_framework.easc.protocol.standard.Header.DEFAULT_MAGIC_NUMBER;
public class ServerHandler implements Handler {
// Set up serializer mappings
static {
Serializer.registerExceptionName(javax.naming.NameNotFoundException.class, "naming/NameNotFound");
Serializer.registerExceptionName(java.lang.reflect.InvocationTargetException.class, "invoke/Exception");
}
/**
* Write response
*
* @access protected
* @param java.io.DataOutputStream out
* @param net.xp_framework.easc.protocol.standard.MessageType type
* @param java.lang.String buffer the encoded data
*/
protected void writeResponse(DataOutputStream out, MessageType type, String buffer) throws IOException {
ByteCountedString bytes= new ByteCountedString(buffer);
// Write header
new Header(
DEFAULT_MAGIC_NUMBER,
(byte)1,
(byte)0,
type,
false,
bytes.length()
).writeTo(out);
// Write data and flush
bytes.writeTo(out);
out.flush();
}
/**
* Handle client connection
*
* @access public
* @param java.io.DataInputStream in
* @param java.io.DataOutputStream out
* @param net.xp_framework.easc.server.ServerContext ctx
*/
public void handle(DataInputStream in, DataOutputStream out, final ServerContext ctx) throws IOException {
Serializer.registerMapping(Proxy.class, new Invokeable<String, Proxy>() {
public String invoke(Proxy p) throws Exception {
ctx.objects.put(p.hashCode(), p);
return "I:" + p.hashCode() + ":{" + Serializer.representationOf(
p.getClass().getInterfaces()[0].getName()
) + "}";
}
});
while (true) {
Header requestHeader= Header.readFrom(in);
// Verify magic number
if (DEFAULT_MAGIC_NUMBER != requestHeader.getMagicNumber()) {
this.writeResponse(out, MessageType.Error, "Magic number mismatch");
break;
}
// Execute using delegate
Object result= null;
MessageType response= null;
String buffer= null;
try {
result= requestHeader.getMessageType().delegateFrom(in, ctx).invoke(ctx);
response= MessageType.Value;
buffer= Serializer.representationOf(result);
} catch (Throwable t) {
t.printStackTrace();
try {
buffer= Serializer.representationOf(t);
response= MessageType.Exception;
} catch (Exception e) {
buffer= e.getMessage();
response= MessageType.Error;
}
}
// Write result
this.writeResponse(out, response, buffer);
}
// Close streams
in.close();
out.close();
}
}
|
package uk.ac.ebi.quickgo.geneproduct.model;
import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductFields;
import uk.ac.ebi.quickgo.rest.controller.request.ArrayPattern;
import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import io.swagger.annotations.ApiModelProperty;
import java.util.*;
import java.util.stream.Stream;
import javax.validation.constraints.*;
import static javax.validation.constraints.Pattern.Flag.CASE_INSENSITIVE;
import static uk.ac.ebi.quickgo.rest.search.DefaultSearchQueryTemplate.DEFAULT_PAGE_NUMBER;
/**
* A data structure used to store the input parameters a client can submit to the Ontology search enpoint
*
* Once the comma separated values have been set, then turn then into an object (SimpleFilter) that
* encapsulates the list and solr field name to use for that argument.
*/
public class GeneProductRequest {
static final int MIN_PAGE_NUMBER = 1;
static final int DEFAULT_ENTRIES_PER_PAGE = 25;
static final int MIN_ENTRIES_PER_PAGE = 0;
static final int MAX_ENTRIES_PER_PAGE = 100;
private static final String[] TARGET_FIELDS = new String[]{GeneProductFields.Searchable.TYPE,
GeneProductFields.Searchable.TAXON_ID};
@ApiModelProperty(value = "Indicates whether the result set should be highlighted")
private boolean highlighting = false;
@ApiModelProperty(value = "Page number of the result set to display.",
allowableValues = "range[" + MIN_PAGE_NUMBER + ", max_result_page_size]",
required = true)
private int page = DEFAULT_PAGE_NUMBER;
@ApiModelProperty(value = "Number of results per page.",
allowableValues = "range[" + MIN_ENTRIES_PER_PAGE + "," + MAX_ENTRIES_PER_PAGE + "]",
required = true)
private int limit = DEFAULT_ENTRIES_PER_PAGE;
@ApiModelProperty(value = "Fields to generate facets from", example = "taxonId, type")
private String[] facets;
@ApiModelProperty(value = "The query used to filter the gene products", example = "kinase", required = true)
private String query;
/*
The filter fields are only declared here, because there is a bug in springfox that doesn't read annotations on
setters
*/
@ApiModelProperty(value = "Further filters the results of the main query based on values chosen from " +
"the taxonomy identifier field", example = "9606")
private String[] taxonId;
@ApiModelProperty(value = "Further filters the results of the main query based on a value chosen from " +
"the type field", allowableValues = "protein,miRNA,complexes", example = "protein")
private String type;
private Map<String, String[]> filterMap = new HashMap<>();
@Min(value = MIN_PAGE_NUMBER, message = "Page number cannot be less than 1")
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
@Min(value = MIN_ENTRIES_PER_PAGE, message = "Number of results per page cannot be less than 0")
@Max(value = MAX_ENTRIES_PER_PAGE,
message = "Number of results per page cannot be greater than " + MAX_ENTRIES_PER_PAGE)
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
@NotNull(message = "Query cannot be null")
@Size(min = 1, message = "Query cannot be empty")
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public boolean isHighlighting() {
return highlighting;
}
public void setHighlighting(boolean useHighlighting) {
this.highlighting = useHighlighting;
}
public String[] getFacet() {
return facets;
}
public void setFacet(String[] facets) {
this.facets = facets;
}
@ArrayPattern(regexp = "[0-9]+", paramName = "taxonId")
public String[] getTaxonId() {
return filterMap.get(GeneProductFields.TAXON_ID);
}
public void setTaxonId(String... taxonIds) {
if (taxonIds != null) {
filterMap.put(GeneProductFields.TAXON_ID, taxonIds);
}
}
@Pattern(regexp = "protein|miRNA|complexes", flags = CASE_INSENSITIVE,
message = "Provided type is invalid: ${validatedValue}")
public String getType() {
return filterMap.get(GeneProductFields.Searchable.TYPE) == null ? null :
filterMap.get(GeneProductFields.Searchable.TYPE)[0];
}
public void setType(String filterByType) {
if (filterByType != null) {
filterMap.put(GeneProductFields.Searchable.TYPE, new String[]{filterByType});
}
}
public QuickGOQuery createQuery() {
return QuickGOQuery.createQuery(query);
}
public List<FilterRequest> createFilterRequests() {
List<FilterRequest> filterRequests = new ArrayList<>();
Stream.of(TARGET_FIELDS)
.map(this::createFilter)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(filterRequests::add);
return filterRequests;
}
private Optional<FilterRequest> createFilter(String key) {
Optional<FilterRequest> request;
if (filterMap.containsKey(key)) {
FilterRequest.Builder requestBuilder = FilterRequest.newBuilder();
requestBuilder.addProperty(key, filterMap.get(key));
request = Optional.of(requestBuilder.build());
} else {
request = Optional.empty();
}
return request;
}
}
|
package fr.mmarie.core.jira;
import com.google.common.collect.ImmutableList;
import fr.mmarie.api.jira.Comment;
import fr.mmarie.api.jira.Transition;
import fr.mmarie.api.jira.input.TransitionInput;
import fr.mmarie.api.jira.response.TransitionResponse;
import org.assertj.core.data.MapEntry;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class JiraServiceTest {
public static final int PORT = 1520;
public JiraConfiguration jiraConfiguration = new JiraConfiguration("username",
"password",
String.format("http://localhost:%d", PORT),
ImmutableList.of(new TransitionConfiguration("Close", ImmutableList.of("close", "fix")),
new TransitionConfiguration("Start Progress", ImmutableList.of("starts", "starting"))));
public JiraService jiraService;
@Before
public void setUp() throws Exception {
jiraService = new JiraService(jiraConfiguration);
}
@Test
public void extractIssuesFromMessageWithoutIssue() throws Exception {
String message = "test: no issue";
final List<String> issues = jiraService.extractIssuesFromMessage(message);
assertThat(issues)
.hasSize(0);
}
@Test
public void extractIssuesFromMessageWithOneIssue() throws Exception {
String message = "test(#TEST-1): single issue";
final List<String> issues = jiraService.extractIssuesFromMessage(message);
assertThat(issues)
.hasSize(1)
.containsExactly("TEST-1");
}
@Test
public void extractIssuesFromMessageWithMoreThanOneIssue() throws Exception {
String message = "test(#TEST-1): issue related to #TEST-15289";
final List<String> issues = jiraService.extractIssuesFromMessage(message);
assertThat(issues)
.hasSize(2)
.containsExactly("TEST-1", "TEST-15289");
}
@Test
public void extractMatchingTransitionsFromMessageWithoutTransition() throws Exception {
String message = "test: no issue";
final Map<String, String> matchingTransitions = jiraService.extractMatchingTransitionsFromMessage(message);
assertThat(matchingTransitions)
.isEmpty();
}
@Test
public void extractMatchingTransitionsFromMessageWithOneTransition() throws Exception {
String message = "test: close #TEST-15289";
final Map<String, String> matchingTransitions = jiraService.extractMatchingTransitionsFromMessage(message);
assertThat(matchingTransitions)
.hasSize(1);
assertThat(matchingTransitions)
.containsOnly(MapEntry.entry("TEST-15289", "Close"));
}
@Test
public void extractMatchingTransitionsFromMessageCaseInsensitive() throws Exception {
String message = "test: FIX #TEST-15289";
final Map<String, String> matchingTransitions = jiraService.extractMatchingTransitionsFromMessage(message);
assertThat(matchingTransitions)
.hasSize(1);
assertThat(matchingTransitions)
.containsOnly(MapEntry.entry("TEST-15289", "Close"));
}
@Test
public void extractMatchingTransitionsFromMessageWithTwoTransitionResturnTheFirstOne() throws Exception {
String message = "test: Close #TEST-15289 and FIX #TEST-52";
final Map<String, String> matchingTransitions = jiraService.extractMatchingTransitionsFromMessage(message);
assertThat(matchingTransitions)
.hasSize(2);
assertThat(matchingTransitions)
.containsOnly(MapEntry.entry("TEST-15289", "Close"), MapEntry.entry("TEST-52", "Close"));
}
@Test
public void performTransitionWithoutKeyword() throws Exception {
jiraService = spy(jiraService);
String message = "dummy";
String issue = "TESGITLAB-1";
doReturn(Optional.empty()).when(jiraService).extractMatchingTransitionsFromMessage(message, issue);
jiraService.performTransition(message, issue, "Hello");
verify(jiraService, times(1)).extractMatchingTransitionsFromMessage(message, issue);
verify(jiraService, times(0)).transitionOnIssue(eq(issue), any(TransitionInput.class));
}
@Test
public void performTransitionWithAnUnknownTransition() throws Exception {
jiraService = spy(jiraService);
String issue = "TESGITLAB-1";
String message = "dummy closes #" + issue;
String transitionName = "close";
doReturn(Optional.of(transitionName)).when(jiraService).extractMatchingTransitionsFromMessage(message, issue);
doReturn(Optional.empty()).when(jiraService).getTransition(issue, transitionName);
jiraService.performTransition(message, issue, "Hello");
verify(jiraService, times(1)).extractMatchingTransitionsFromMessage(message, issue);
verify(jiraService, times(0)).transitionOnIssue(eq(issue), any(TransitionInput.class));
}
@Test
public void performTransitionWithARightTransition() throws Exception {
jiraService = spy(jiraService);
ArgumentCaptor<TransitionInput> transitionInputArgumentCaptor = ArgumentCaptor.forClass(TransitionInput.class);
String issue = "TESGITLAB-1";
String message = "dummy closes #" + issue;
String transitionName = "close";
doReturn(Optional.of(transitionName)).when(jiraService).extractMatchingTransitionsFromMessage(message, issue);
Transition transition = new Transition(15L, "Close");
doReturn(Optional.of(transition)).when(jiraService).getTransition(issue, transitionName);
jiraService.performTransition(message, issue, "Hello " + JiraService.TRANSITION_HOLDER);
verify(jiraService, times(1)).extractMatchingTransitionsFromMessage(message, issue);
verify(jiraService, times(1)).transitionOnIssue(eq(issue), transitionInputArgumentCaptor.capture());
TransitionInput transitionInput = transitionInputArgumentCaptor.getValue();
assertThat(transitionInput.getTransition()).isEqualTo(transition);
assertThat(transitionInput.getUpdate().getComments().size()).isEqualTo(1);
assertThat(transitionInput.getUpdate().getComments().get(0).getComment())
.isEqualTo(new Comment("Hello " + transitionName));
}
@Test
public void performTransitionWithMultipleTransitions() throws Exception {
jiraService = spy(jiraService);
ArgumentCaptor<TransitionInput> transitionInputArgumentCaptor = ArgumentCaptor.forClass(TransitionInput.class);
String issue = "TESGITLAB-1";
Transition startProgressTransition = new Transition(2L, "Start Progress");
Transition closeTransition = new Transition(1L, "Close");
doReturn(new TransitionResponse(ImmutableList.of(closeTransition, startProgressTransition)))
.when(jiraService).getTransitionsOfIssue(issue);
String message = "dummy starts #" + issue;
String transitionName = "Start Progress";
doReturn(Optional.of(transitionName)).when(jiraService).extractMatchingTransitionsFromMessage(message, issue);
jiraService.performTransition(message, issue, "Hello " + JiraService.TRANSITION_HOLDER);
verify(jiraService, times(1)).extractMatchingTransitionsFromMessage(message, issue);
verify(jiraService, times(1)).transitionOnIssue(eq(issue), transitionInputArgumentCaptor.capture());
TransitionInput transitionInput = transitionInputArgumentCaptor.getValue();
assertThat(transitionInput.getTransition()).isEqualTo(startProgressTransition);
assertThat(transitionInput.getUpdate().getComments().size()).isEqualTo(1);
assertThat(transitionInput.getUpdate().getComments().get(0).getComment())
.isEqualTo(new Comment("Hello " + transitionName));
}
}
|
package com.fivehundredpx.greedolayout;
import java.util.ArrayList;
import java.util.List;
public class GreedoLayoutSizeCalculator {
public interface SizeCalculatorDelegate {
double aspectRatioForIndex(int index);
}
private static final int DEFAULT_MAX_ROW_HEIGHT = 600;
private int mMaxRowHeight = DEFAULT_MAX_ROW_HEIGHT;
private static final int INVALID_CONTENT_WIDTH = -1;
private int mContentWidth = INVALID_CONTENT_WIDTH;
// When in fixed height mode and the item's width is less than this percentage, don't try to
// fit the item, overflow it to the next row and grow the existing items.
private static final double VALID_ITEM_SLACK_THRESHOLD = 2.0 / 3.0;
private boolean mIsFixedHeight = false;
private SizeCalculatorDelegate mSizeCalculatorDelegate;
private List<Size> mSizeForChildAtPosition;
private List<Integer> mFirstChildPositionForRow;
private List<Integer> mRowForChildPosition;
public GreedoLayoutSizeCalculator(SizeCalculatorDelegate sizeCalculatorDelegate) {
mSizeCalculatorDelegate = sizeCalculatorDelegate;
mSizeForChildAtPosition = new ArrayList<>();
mFirstChildPositionForRow = new ArrayList<>();
mRowForChildPosition = new ArrayList<>();
}
public void setContentWidth(int contentWidth) {
if (mContentWidth != contentWidth) {
mContentWidth = contentWidth;
reset();
}
}
public void setMaxRowHeight(int maxRowHeight) {
if (mMaxRowHeight != maxRowHeight) {
mMaxRowHeight = maxRowHeight;
reset();
}
}
public void setFixedHeight(boolean fixedHeight) {
if (mIsFixedHeight != fixedHeight) {
mIsFixedHeight = fixedHeight;
reset();
}
}
public Size sizeForChildAtPosition(int position) {
if (position >= mSizeForChildAtPosition.size()) {
computeChildSizesUpToPosition(position);
}
return mSizeForChildAtPosition.get(position);
}
public int getFirstChildPositionForRow(int row) {
if (row >= mFirstChildPositionForRow.size()) {
computeFirstChildPositionsUpToRow(row);
}
return mFirstChildPositionForRow.get(row);
}
public int getRowForChildPosition(int position) {
if (position >= mRowForChildPosition.size()) {
computeChildSizesUpToPosition(position);
}
return mRowForChildPosition.get(position);
}
public void reset() {
mSizeForChildAtPosition.clear();
mFirstChildPositionForRow.clear();
mRowForChildPosition.clear();
}
private void computeFirstChildPositionsUpToRow(int row) {
// TODO: Rewrite this? Looks dangerous but in reality should be fine. I'd like something
// less alarming though.
while (row >= mFirstChildPositionForRow.size()) {
computeChildSizesUpToPosition(mSizeForChildAtPosition.size() + 1);
}
}
private void computeChildSizesUpToPosition(int lastPosition) {
if (mContentWidth == INVALID_CONTENT_WIDTH) {
throw new RuntimeException("Invalid content width. Did you forget to set it?");
}
if (mSizeCalculatorDelegate == null) {
throw new RuntimeException("Size calculator delegate is missing. Did you forget to set it?");
}
int firstUncomputedChildPosition = mSizeForChildAtPosition.size();
int row = mRowForChildPosition.size() > 0
? mRowForChildPosition.get(mRowForChildPosition.size() - 1) + 1 : 0;
double currentRowAspectRatio = 0.0;
List<Double> itemAspectRatios = new ArrayList<>();
int currentRowHeight = mIsFixedHeight ? mMaxRowHeight : Integer.MAX_VALUE;
int currentRowWidth = 0;
int pos = firstUncomputedChildPosition;
while (pos < lastPosition || (mIsFixedHeight ? currentRowWidth <= mContentWidth : currentRowHeight > mMaxRowHeight)) {
double posAspectRatio = mSizeCalculatorDelegate.aspectRatioForIndex(pos);
currentRowAspectRatio += posAspectRatio;
itemAspectRatios.add(posAspectRatio);
currentRowWidth = calculateWidth(currentRowHeight, currentRowAspectRatio);
if (!mIsFixedHeight) {
currentRowHeight = calculateHeight(mContentWidth, currentRowAspectRatio);
}
boolean isRowFull = mIsFixedHeight ? currentRowWidth > mContentWidth : currentRowHeight <= mMaxRowHeight;
if (isRowFull) {
int rowChildCount = itemAspectRatios.size();
mFirstChildPositionForRow.add(pos - rowChildCount + 1);
int[] itemSlacks = new int[rowChildCount];
if (mIsFixedHeight) {
itemSlacks = distributeRowSlack(currentRowWidth, rowChildCount, itemAspectRatios);
if (!hasValidItemSlacks(itemSlacks, itemAspectRatios)) {
int lastItemWidth = calculateWidth(currentRowHeight,
itemAspectRatios.get(itemAspectRatios.size() - 1));
currentRowWidth -= lastItemWidth;
rowChildCount -= 1;
itemAspectRatios.remove(itemAspectRatios.size() - 1);
itemSlacks = distributeRowSlack(currentRowWidth, rowChildCount, itemAspectRatios);
}
}
int availableSpace = mContentWidth;
for (int i = 0; i < rowChildCount; i++) {
int itemWidth = calculateWidth(currentRowHeight, itemAspectRatios.get(i)) - itemSlacks[i];
itemWidth = Math.min(availableSpace, itemWidth);
mSizeForChildAtPosition.add(new Size(itemWidth, currentRowHeight));
mRowForChildPosition.add(row);
availableSpace -= itemWidth;
}
itemAspectRatios.clear();
currentRowAspectRatio = 0.0;
row++;
}
pos++;
}
}
private int[] distributeRowSlack(int rowWidth, int rowChildCount, List<Double> itemAspectRatios) {
return distributeRowSlack(rowWidth - mContentWidth, rowWidth, rowChildCount, itemAspectRatios);
}
private int[] distributeRowSlack(int rowSlack, int rowWidth, int rowChildCount, List<Double> itemAspectRatios) {
int itemSlacks[] = new int[rowChildCount];
for (int i = 0; i < rowChildCount; i++) {
double itemWidth = mMaxRowHeight * itemAspectRatios.get(i);
itemSlacks[i] = (int) (rowSlack * (itemWidth / rowWidth));
}
return itemSlacks;
}
private boolean hasValidItemSlacks(int[] itemSlacks, List<Double> itemAspectRatios) {
for (int i = 0; i < itemSlacks.length; i++) {
int itemWidth = (int) (itemAspectRatios.get(i) * mMaxRowHeight);
if (!isValidItemSlack(itemSlacks[i], itemWidth)) {
return false;
}
}
return true;
}
private boolean isValidItemSlack(int itemSlack, int itemWidth) {
return (itemWidth - itemSlack) / (double) itemWidth > VALID_ITEM_SLACK_THRESHOLD;
}
private int calculateWidth(int itemHeight, double aspectRatio) {
return (int) Math.ceil(itemHeight * aspectRatio);
}
private int calculateHeight(int itemWidth, double aspectRatio) {
return (int) Math.ceil(itemWidth / aspectRatio);
}
}
|
package com.streamsets.pipeline.stage.destination.hdfs;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.streamsets.pipeline.api.Batch;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.base.OnRecordErrorException;
import com.streamsets.pipeline.api.base.RecordTarget;
import com.streamsets.pipeline.api.el.ELEval;
import com.streamsets.pipeline.api.el.ELEvalException;
import com.streamsets.pipeline.api.el.ELVars;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.config.CsvHeader;
import com.streamsets.pipeline.config.CsvMode;
import com.streamsets.pipeline.config.DataFormat;
import com.streamsets.pipeline.config.JsonMode;
import com.streamsets.pipeline.lib.el.RecordEL;
import com.streamsets.pipeline.lib.el.TimeEL;
import com.streamsets.pipeline.lib.generator.DataGeneratorFactory;
import com.streamsets.pipeline.lib.generator.DataGeneratorFactoryBuilder;
import com.streamsets.pipeline.lib.generator.delimited.DelimitedDataGeneratorFactory;
import com.streamsets.pipeline.lib.generator.text.TextDataGeneratorFactory;
import com.streamsets.pipeline.stage.destination.hdfs.writer.ActiveRecordWriters;
import com.streamsets.pipeline.stage.destination.hdfs.writer.RecordWriter;
import com.streamsets.pipeline.stage.destination.hdfs.writer.RecordWriterManager;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.security.UserGroupInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.PrivilegedExceptionAction;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
public class HdfsTarget extends RecordTarget {
private final static Logger LOG = LoggerFactory.getLogger(HdfsTarget.class);
private final static int MEGA_BYTE = 1024 * 1024;
private final String hdfsUri;
private final boolean hdfsKerberos;
private final String kerberosPrincipal;
private final String kerberosKeytab;
private final String hadoopConfDir;
private final Map<String, String> hdfsConfigs;
private String uniquePrefix;
private final String dirPathTemplate;
private final String timeZoneID;
private final String timeDriver;
private final long maxRecordsPerFile;
private final long maxFileSizeMBs;
private final CompressionMode compression;
private final String otherCompression;
private final HdfsFileType fileType;
private final String keyEl;
private final HdfsSequenceFileCompressionType seqFileCompressionType;
private final String lateRecordsLimit;
private final LateRecordsAction lateRecordsAction;
private final String lateRecordsDirPathTemplate;
private final DataFormat dataFormat;
private final CsvMode csvFileFormat;
private final CsvHeader csvHeader;
private final boolean csvReplaceNewLines;
private final JsonMode jsonMode;
private final String textFieldPath;
private final boolean textEmptyLineIfNull;
private String charset;
public HdfsTarget(String hdfsUri, boolean hdfsKerberos, String kerberosPrincipal, String kerberosKeytab,
String hadoopConfDir, Map<String, String> hdfsConfigs, String uniquePrefix, String dirPathTemplate,
String timeZoneID,
String timeDriver, long maxRecordsPerFile, long maxFileSize, CompressionMode compression, String otherCompression,
HdfsFileType fileType, String keyEl,
HdfsSequenceFileCompressionType seqFileCompressionType, String lateRecordsLimit,
LateRecordsAction lateRecordsAction, String lateRecordsDirPathTemplate,
DataFormat dataFormat, String charset, CsvMode csvFileFormat, CsvHeader csvHeader, boolean csvReplaceNewLines,
JsonMode jsonMode,
String textFieldPath, boolean textEmptyLineIfNull) {
this.hdfsUri = hdfsUri;
this.hdfsKerberos = hdfsKerberos;
this.kerberosPrincipal = kerberosPrincipal;
this.kerberosKeytab = kerberosKeytab;
this.hadoopConfDir = hadoopConfDir;
this.hdfsConfigs = hdfsConfigs;
this.uniquePrefix = uniquePrefix;
this.dirPathTemplate = dirPathTemplate;
this.timeZoneID = timeZoneID;
this.timeDriver = timeDriver;
this.maxRecordsPerFile = maxRecordsPerFile;
this.maxFileSizeMBs = maxFileSize;
this.compression = compression;
this.otherCompression = otherCompression;
this.fileType = fileType;
this.keyEl = keyEl;
this.seqFileCompressionType = seqFileCompressionType;
this.lateRecordsLimit = lateRecordsLimit;
this.lateRecordsAction = lateRecordsAction;
this.lateRecordsDirPathTemplate = lateRecordsDirPathTemplate;
this.dataFormat = dataFormat;
this.csvFileFormat = csvFileFormat;
this.csvHeader = csvHeader;
this.csvReplaceNewLines = csvReplaceNewLines;
this.jsonMode = jsonMode;
this.textFieldPath = textFieldPath;
this.textEmptyLineIfNull = textEmptyLineIfNull;
this.charset = charset;
}
private Configuration hdfsConfiguration;
private UserGroupInformation ugi;
private long lateRecordsLimitSecs;
private ActiveRecordWriters currentWriters;
private ActiveRecordWriters lateWriters;
private DataGeneratorFactory generatorFactory;
private ELEval timeDriverElEval;
private ELEval lateRecordsLimitEvaluator;
private Date batchTime;
private CompressionCodec compressionCodec;
@Override
protected List<ConfigIssue> validateConfigs() throws StageException {
List<ConfigIssue> issues = super.validateConfigs();
boolean validHadoopFsUri = validateHadoopFS(issues);
try {
lateRecordsLimitEvaluator = getContext().createELEval("lateRecordsLimit");
getContext().parseEL(lateRecordsLimit);
lateRecordsLimitSecs = lateRecordsLimitEvaluator.eval(getContext().createELVars(),
lateRecordsLimit, Long.class);
if (lateRecordsLimitSecs <= 0) {
issues.add(getContext().createConfigIssue(Groups.LATE_RECORDS.name(), "lateRecordsLimit", Errors.HADOOPFS_10));
}
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.LATE_RECORDS.name(), "lateRecordsLimit", Errors.HADOOPFS_06,
lateRecordsLimit, ex.getMessage(), ex));
}
if (maxFileSizeMBs < 0) {
issues.add(getContext().createConfigIssue(Groups.LATE_RECORDS.name(), "maxFileSize", Errors.HADOOPFS_08));
}
if (maxRecordsPerFile < 0) {
issues.add(getContext().createConfigIssue(Groups.LATE_RECORDS.name(), "maxRecordsPerFile", Errors.HADOOPFS_09));
}
if (uniquePrefix == null) {
uniquePrefix = "";
}
validateDataFormat(issues);
generatorFactory = createDataGeneratorFactory();
SequenceFile.CompressionType compressionType = (seqFileCompressionType != null)
? seqFileCompressionType.getType() : null;
try {
RecordWriterManager.validateDirPathTemplate1(getContext(), dirPathTemplate);
RecordWriterManager.validateDirPathTemplate2(getContext(), dirPathTemplate);
try {
switch (compression) {
case OTHER:
try {
Class klass = Thread.currentThread().getContextClassLoader().loadClass(otherCompression);
if (CompressionCodec.class.isAssignableFrom(klass)) {
compressionCodec = ((Class<? extends CompressionCodec> ) klass).newInstance();
} else {
throw new StageException(Errors.HADOOPFS_04, otherCompression);
}
} catch (Exception ex1) {
throw new StageException(Errors.HADOOPFS_05, otherCompression, ex1.getMessage(), ex1);
}
break;
case NONE:
break;
default:
compressionCodec = compression.getCodec().newInstance();
break;
}
if(validHadoopFsUri) {
RecordWriterManager mgr = new RecordWriterManager(new URI(hdfsUri), hdfsConfiguration, uniquePrefix,
dirPathTemplate, TimeZone.getTimeZone(timeZoneID), lateRecordsLimitSecs, maxFileSizeMBs * MEGA_BYTE,
maxRecordsPerFile, fileType, compressionCodec, compressionType, keyEl, generatorFactory, getContext());
currentWriters = new ActiveRecordWriters(mgr);
}
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.OUTPUT_FILES.name(), null, Errors.HADOOPFS_11, ex.getMessage(),
ex));
}
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.OUTPUT_FILES.name(), "dirPathTemplate", Errors.HADOOPFS_20,
ex.getMessage(), ex));
}
try {
if (lateRecordsDirPathTemplate != null && !lateRecordsDirPathTemplate.isEmpty()) {
RecordWriterManager.validateDirPathTemplate1(getContext(), lateRecordsDirPathTemplate);
RecordWriterManager.validateDirPathTemplate2(getContext(), lateRecordsDirPathTemplate);
if(validHadoopFsUri) {
try {
RecordWriterManager mgr = new RecordWriterManager(new URI(hdfsUri), hdfsConfiguration, uniquePrefix,
lateRecordsDirPathTemplate, TimeZone.getTimeZone(timeZoneID), lateRecordsLimitSecs,
maxFileSizeMBs * MEGA_BYTE, maxRecordsPerFile, fileType, compressionCodec, compressionType, keyEl,
generatorFactory, getContext());
lateWriters = new ActiveRecordWriters(mgr);
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.LATE_RECORDS.name(), null, Errors.HADOOPFS_17, ex.getMessage(), ex));
}
}
}
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.OUTPUT_FILES.name(), "lateRecordsDirPathTemplate",
Errors.HADOOPFS_21, ex.getMessage(), ex));
}
timeDriverElEval = getContext().createELEval("timeDriver");
try {
ELVars variables = getContext().createELVars();
RecordEL.setRecordInContext(variables, getContext().createRecord("validationConfigs"));
TimeEL.setTimeNowInContext(variables, new Date());
getContext().parseEL(timeDriver);
timeDriverElEval.eval(variables, timeDriver, Date.class);
} catch (ELEvalException ex) {
issues.add(getContext().createConfigIssue(Groups.OUTPUT_FILES.name(), "timeDriver", Errors.HADOOPFS_19,
ex.getMessage(), ex));
}
return issues;
}
Configuration getHadoopConfiguration(List<ConfigIssue> issues) {
Configuration conf = new Configuration();
if (hadoopConfDir != null && !hadoopConfDir.isEmpty()) {
File hadoopConfigDir = new File(getContext().getResourcesDirectory(), hadoopConfDir).getAbsoluteFile();
if (!hadoopConfigDir.exists()) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), "hadoopConfDir", Errors.HADOOPFS_25,
hadoopConfDir));
} else if (!hadoopConfigDir.isDirectory()) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), "hadoopConfDir", Errors.HADOOPFS_26,
hadoopConfDir));
} else {
File coreSite = new File(hadoopConfigDir, "core-site.xml");
if (coreSite.exists()) {
if (!coreSite.isFile()) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), "hadoopConfDir", Errors.HADOOPFS_27,
hadoopConfDir, "core-site.xml"));
}
conf.addResource(new Path(coreSite.getAbsolutePath()));
}
File hdfsSite = new File(hadoopConfigDir, "hdfs-site.xml");
if (hdfsSite.exists()) {
if (!hdfsSite.isFile()) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), "hadoopConfDir", Errors.HADOOPFS_27,
hadoopConfDir, "hdfs-site.xml"));
}
conf.addResource(new Path(hdfsSite.getAbsolutePath()));
}
}
}
for (Map.Entry<String, String> config : hdfsConfigs.entrySet()) {
conf.set(config.getKey(), config.getValue());
}
return conf;
}
private boolean validateHadoopFS(List<ConfigIssue> issues) {
boolean validHapoopFsUri = true;
if (hdfsUri.contains(":
try {
new URI(hdfsUri);
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_22, hdfsUri,
ex.getMessage(), ex));
validHapoopFsUri = false;
}
} else {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), "hdfsUri", Errors.HADOOPFS_18, hdfsUri));
validHapoopFsUri = false;
}
StringBuilder logMessage = new StringBuilder();
try {
hdfsConfiguration = getHadoopConfiguration(issues);
hdfsConfiguration.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY, hdfsUri);
if (hdfsKerberos) {
logMessage.append("Using Kerberos: ");
if (Boolean.getBoolean("sdc.transient-env")) {
Utils.checkState(getContext().isClusterMode(), "Transient environment implies cluster mode");
Utils.checkState(!getContext().isPreview(), "Transient environment implies pipeline is not in preview");
logMessage.append("via delegation token: " + System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
// use delegation token
UserGroupInformation.setConfiguration(hdfsConfiguration);
ugi = UserGroupInformation.getCurrentUser();
} else {
logMessage.append("via keytab");
hdfsConfiguration.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
UserGroupInformation.AuthenticationMethod.KERBEROS.name());
UserGroupInformation.setConfiguration(hdfsConfiguration);
ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(kerberosPrincipal, kerberosKeytab);
if (ugi.getAuthenticationMethod() != UserGroupInformation.AuthenticationMethod.KERBEROS) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), "hdfsKerberos", Errors.HADOOPFS_00,
ugi.getAuthenticationMethod(), UserGroupInformation.AuthenticationMethod.KERBEROS));
}
}
} else {
logMessage.append("Using Simple");
hdfsConfiguration.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
UserGroupInformation.AuthenticationMethod.SIMPLE.name());
ugi = UserGroupInformation.getLoginUser();
}
if (validHapoopFsUri) {
// we just login, the TGT won't expire yet, no need to relogin
ugi.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
try (FileSystem fs = getFileSystemForInitDestroy()) { //to trigger the close
}
return null;
}
});
}
} catch (Exception ex) {
issues.add(getContext().createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_01, hdfsUri,
ex.getMessage(), ex));
}
LOG.info("Authentication Config: " + logMessage);
return validHapoopFsUri;
}
@Override
protected void init() throws StageException {
super.init();
try {
FileSystem fs = getFileSystemForInitDestroy();
getCurrentWriters().commitOldFiles(fs);
if (getLateWriters() != null) {
getLateWriters().commitOldFiles(fs);
}
} catch (IOException ex) {
throw new StageException(Errors.HADOOPFS_23, ex.getMessage(), ex);
}
toHdfsRecordsCounter = getContext().createCounter("toHdfsRecords");
toHdfsRecordsMeter = getContext().createMeter("toHdfsRecords");
lateRecordsCounter = getContext().createCounter("lateRecords");
lateRecordsMeter = getContext().createMeter("lateRecords");
}
private FileSystem getFileSystemForInitDestroy() throws IOException {
try {
// we need to relogin if the TGT is expiring
ugi.checkTGTAndReloginFromKeytab();
return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
@Override
public FileSystem run() throws Exception {
return FileSystem.get(new URI(hdfsUri), hdfsConfiguration);
}
});
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
Configuration getHdfsConfiguration() {
return hdfsConfiguration;
}
CompressionCodec getCompressionCodec() throws StageException {
return compressionCodec;
}
// for testing only
long getLateRecordLimitSecs() {
return lateRecordsLimitSecs;
}
private void validateDataFormat(List<ConfigIssue> issues) {
switch (dataFormat) {
case TEXT:
case JSON:
case DELIMITED:
case SDC_JSON:
break;
default:
issues.add(getContext().createConfigIssue(Groups.OUTPUT_FILES.name(), "dataFormat", Errors.HADOOPFS_16,
dataFormat));
}
}
private DataGeneratorFactory createDataGeneratorFactory() {
DataGeneratorFactoryBuilder builder = new DataGeneratorFactoryBuilder(getContext(),
dataFormat.getGeneratorFormat());
if(charset == null || charset.trim().isEmpty()) {
charset = "UTF-8";
}
builder.setCharset(Charset.forName(charset));
switch(dataFormat) {
case JSON:
builder.setMode(jsonMode);
break;
case DELIMITED:
builder.setMode(csvFileFormat);
builder.setMode(csvHeader);
builder.setConfig(DelimitedDataGeneratorFactory.REPLACE_NEWLINES_KEY, csvReplaceNewLines);
break;
case TEXT:
builder.setConfig(TextDataGeneratorFactory.FIELD_PATH_KEY, textFieldPath);
builder.setConfig(TextDataGeneratorFactory.EMPTY_LINE_IF_NULL_KEY, textEmptyLineIfNull);
break;
case SDC_JSON:
break;
case XML:
default:
throw new IllegalStateException("It should not happen");
}
return builder.build();
}
@Override
public void destroy() {
try {
if (currentWriters != null) {
currentWriters.closeAll();
}
if (lateWriters != null) {
lateWriters.closeAll();
}
if (ugi != null) {
getFileSystemForInitDestroy().close();
}
} catch (IOException ex) {
LOG.warn("Error while closing HDFS FileSystem URI='{}': {}", hdfsUri, ex.getMessage(), ex);
}
super.destroy();
}
@Override
public void write(final Batch batch) throws StageException {
setBatchTime();
try {
// we need to relogin if the TGT is expiring
ugi.checkTGTAndReloginFromKeytab();
ugi.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
getCurrentWriters().purge();
if (getLateWriters() != null) {
getLateWriters().purge();
}
HdfsTarget.super.write(batch);
return null;
}
});
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
//visible for testing.
Date setBatchTime() {
batchTime = new Date();
return batchTime;
}
protected Date getBatchTime() {
return batchTime;
}
protected ActiveRecordWriters getCurrentWriters() {
return currentWriters;
}
protected ActiveRecordWriters getLateWriters() {
return lateWriters;
}
protected Date getRecordTime(Record record) throws ELEvalException {
ELVars variables = getContext().createELVars();
TimeEL.setTimeNowInContext(variables, getBatchTime());
RecordEL.setRecordInContext(variables, record);
return timeDriverElEval.eval(variables, timeDriver, Date.class);
}
private Counter toHdfsRecordsCounter;
private Meter toHdfsRecordsMeter;
private Counter lateRecordsCounter;
private Meter lateRecordsMeter;
@Override
protected void write(Record record) throws StageException {
try {
Date recordTime = getRecordTime(record);
RecordWriter writer = getCurrentWriters().get(getBatchTime(), recordTime, record);
if (writer != null) {
toHdfsRecordsCounter.inc();
toHdfsRecordsMeter.mark();
writer.write(record);
getCurrentWriters().release(writer);
} else {
lateRecordsCounter.inc();
lateRecordsMeter.mark();
switch (lateRecordsAction) {
case SEND_TO_ERROR:
getContext().toError(record, Errors.HADOOPFS_12, record.getHeader().getSourceId());
break;
case SEND_TO_LATE_RECORDS_FILE:
RecordWriter lateWriter = getLateWriters().get(getBatchTime(), getBatchTime(), record);
lateWriter.write(record);
getLateWriters().release(lateWriter);
break;
default:
throw new RuntimeException("It should never happen");
}
}
} catch (IOException ex) {
throw new StageException(Errors.HADOOPFS_14, record, ex.getMessage(), ex);
} catch (StageException ex) {
throw new OnRecordErrorException(Errors.HADOOPFS_14, record, ex.getMessage(), ex);
}
}
}
|
// package
package org.mskcc.cbio.importer.fetcher.internal;
// imports
import org.mskcc.cbio.importer.Config;
import org.mskcc.cbio.importer.Fetcher;
import org.mskcc.cbio.importer.FileUtils;
import org.mskcc.cbio.importer.DatabaseUtils;
import org.mskcc.cbio.importer.model.ImportDataRecord;
import org.mskcc.cbio.importer.model.ReferenceMetadata;
import org.mskcc.cbio.importer.model.DataSourcesMetadata;
import org.mskcc.cbio.importer.dao.ImportDataRecordDAO;
import org.foundation.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.xml.ws.fault.ServerSOAPFaultException;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Class which implements the fetcher interface.
*/
class FoundationFetcherImpl implements Fetcher {
// our logger
private static final Log LOG = LogFactory.getLog(FoundationFetcherImpl.class);
// foundation data file extension
private static final String FOUNDATION_FILE_EXTENSION = ".xml";
// not all fields in ImportDataRecord will be used
private static final String UNUSED_IMPORT_DATA_FIELD = "NA";
// ref to configuration
private Config config;
// ref to file utils
private FileUtils fileUtils;
// ref to import data
private ImportDataRecordDAO importDataRecordDAO;
// ref to database utils
private DatabaseUtils databaseUtils;
// download directories
private DataSourcesMetadata dataSourceMetadata;
/**
* Constructor.
*
* @param config Config
* @param fileUtils FileUtils
* @param databaseUtils DatabaseUtils
* @param importDataRecordDAO ImportDataRecordDAO;
*/
public FoundationFetcherImpl(Config config, FileUtils fileUtils,
DatabaseUtils databaseUtils, ImportDataRecordDAO importDataRecordDAO) {
// set members
this.config = config;
this.fileUtils = fileUtils;
this.databaseUtils = databaseUtils;
this.importDataRecordDAO = importDataRecordDAO;
}
/**
* Fetchers genomic data from an external datasource and
* places in database for processing.
*
* @param dataSource String
* @param desiredRunDate String
* @throws Exception
*/
@Override
public void fetch(String dataSource, String desiredRunDate) throws Exception {
if (LOG.isInfoEnabled()) {
LOG.info("fetch(), dateSource:runDate: " + dataSource + ":" + desiredRunDate);
}
// get our DataSourcesMetadata object
Collection<DataSourcesMetadata> dataSourcesMetadata = config.getDataSourcesMetadata(dataSource);
if (dataSourcesMetadata.isEmpty()) {
throw new IllegalArgumentException("cannot instantiate a proper DataSourcesMetadata object.");
}
this.dataSourceMetadata = dataSourcesMetadata.iterator().next();
if (LOG.isInfoEnabled()) {
LOG.info("fetch(), creating CaseInfoService endpoint.");
}
// TODO temporary test to bypass foundation service
// if (this.testXMLParsers())
// return;
CaseInfoService caseInfoService = new CaseInfoService();
ICaseInfoService foundationService = caseInfoService.getICaseInfoService();
NodeList cases = this.fetchCaseList(foundationService);
StringBuilder dataClinicalContent = new StringBuilder();
StringBuilder dataMutationsContent = new StringBuilder();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
for (int lc = 0; lc < cases.getLength(); lc++)
{
String caseRecord = this.fetchCaseRecord(cases.item(lc),
foundationService);
// TODO check for empty records instead of size comparison
if (caseRecord != null)
{
Document doc = dBuilder.parse(new InputSource(
new StringReader(foundationService.getCaseList())));
this.addClinicalData(doc, dataClinicalContent);
this.addMutationData(doc, dataMutationsContent);
// TODO CNA data?
}
// if (caseRecord != null && caseRecord.length() > 250) {
// File caseFile = fileUtils.createFileWithContents(dataSourceMetadata.getDownloadDirectory() +
// File.separator +
// fmiCaseID + FOUNDATION_FILE_EXTENSION, caseRecord);
// if (LOG.isInfoEnabled()) {
// LOG.info("fetch(), successfully fetched data for case: " + caseID + ", persisting...");
// ImportDataRecord importDataRecord = new ImportDataRecord(dataSource, dataSource, UNUSED_IMPORT_DATA_FIELD,
// UNUSED_IMPORT_DATA_FIELD, UNUSED_IMPORT_DATA_FIELD,
// caseFile.getCanonicalPath(), UNUSED_IMPORT_DATA_FIELD,
// fmiCaseID + FOUNDATION_FILE_EXTENSION);
// importDataRecordDAO.importDataRecord(importDataRecord);
}
// TODO write contents of the lists to corresponding files
this.generateClinicalFile(dataClinicalContent);
this.generateMutationFile(dataMutationsContent);
//this.generateCNAFile(); // TODO param? matrix?
}
// TODO temporary test function (remove when ready)
protected boolean testXMLParsers() throws Exception
{
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-16\"?><ClientCaseInfo xmlns=\"http://www" +
".foundationmedicine.com/entities\" xmlns:xsd=\"http:
"xmlns:xsi=\"http:
" case=\"S09-18586\"><variant-report disease-ontology=\"Soft tissue fibromatosis\" " +
"gender=\"male\" test-request=\"TRF001147\" study=\"CLINICAL\" pipeline-version=\"v1.2" +
".2\"><samples><sample name=\"TRF001147.02\" percent-tumor-nuclei=\"90\" " +
"/></samples><quality-control status=\"Pass\"><metrics><metric name=\"Median coverage\" " +
"value=\"1098\" criterion=\">=350\" status=\"Pass\" /><metric name=\"Coverage >100X\"" +
" value=\"100%\" criterion=\">=85%\" status=\"Pass\" /><metric name=\"Error\" value=\"0" +
".32%\" criterion=\"<1%\" status=\"Pass\" " +
"/></metrics></quality-control><short-variants><short-variant depth=\"1680\" gene=\"CTNNB1\" " +
"percent-reads=\"45.0\" position=\"chr3:41266124\" protein-effect=\"T41A\" status=\"known\" />" +
"</short-variants><copy-number-alterations /><rearrangements /></variant-report>" +
"</Case></Cases></ClientCaseInfo>";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xmlString)));
StringBuilder dataClinicalContent = new StringBuilder();
StringBuilder dataMutationsContent = new StringBuilder();
this.addClinicalData(doc, dataClinicalContent);
this.addMutationData(doc, dataMutationsContent);
this.generateClinicalFile(dataClinicalContent);
this.generateMutationFile(dataMutationsContent);
return true;
}
protected File generateClinicalFile(StringBuilder content) throws Exception
{
String header = "case_id\tgender\tfmi_case_id\tpipeline_ver\t" +
"tumor_nuclei_percent\tmedian cov\tcov>100x\terror_percent\n";
File clinicalFile = fileUtils.createFileWithContents(dataSourceMetadata.getDownloadDirectory() +
File.separator + "data_clinical.txt", header + content.toString());
return clinicalFile;
}
protected File generateMutationFile(StringBuilder content) throws Exception
{
String header = "hugo_symbol\tchromosome\tstart_position\tend_position\t" +
"strand\tvariant_classification\tmutation_status?\tamino_acid_change\t" +
"transcript\tt_ref_count\tt_alt_count\n";
File mafFile = fileUtils.createFileWithContents(dataSourceMetadata.getDownloadDirectory() +
File.separator + "data_mutations.txt", header + content.toString());
return mafFile;
}
protected void addClinicalData(Document caseDoc, StringBuilder content)
{
String fmiCaseID = "";
String caseID = "";
String gender = "";
String pipelineVer = "";
String percentTumorNuclei = "";
String medianCov = "";
String covGreaterThan100x = "";
String errorPercent = "";
Element caseNode = this.extractCaseNode(caseDoc);
if (caseNode == null)
{
return; // no case to process
}
fmiCaseID = caseNode.getAttribute("fmiCase");
caseID = caseNode.getAttribute("case");
Element variantReport = this.extractVariantReport(caseNode);
if (variantReport != null)
{
gender = variantReport.getAttribute("gender");
pipelineVer = variantReport.getAttribute("pipeline-version");
NodeList samples = variantReport.getElementsByTagName("sample");
Node sample = samples.item(0); // assuming there is only one sample
if (sample.getNodeType() == Node.ELEMENT_NODE)
{
percentTumorNuclei = ((Element)sample).getAttribute("percent-tumor-nuclei");
}
NodeList metrics = variantReport.getElementsByTagName("metric");
for (int i = 0; i < metrics.getLength(); i++)
{
Node metric = metrics.item(i);
if (metric.getNodeType() == Node.ELEMENT_NODE)
{
String name = ((Element)metric).getAttribute("name");
String value = ((Element)metric).getAttribute("value");
if (name.equalsIgnoreCase("median coverage"))
{
medianCov = value;
}
else if (name.equalsIgnoreCase("coverage >100x"))
{
covGreaterThan100x = value;
}
else if (name.equalsIgnoreCase("error"))
{
errorPercent = value;
}
}
}
}
// append the data as a single line
content.append(caseID);
content.append("\t");
content.append(gender);
content.append("\t");
content.append(fmiCaseID);
content.append("\t");
content.append(pipelineVer);
content.append("\t");
content.append(percentTumorNuclei);
content.append("\t");
content.append(medianCov);
content.append("\t");
content.append(covGreaterThan100x);
content.append("\t");
content.append(errorPercent);
content.append("\n");
}
protected void addMutationData(Document caseDoc, StringBuilder content)
{
String gene = "";
String chromosome = "";
String startPos = "";
String endPos = "";
String proteinEffect = "";
String status = "";
String transcript = "";
String strand = "";
String functionalEffect = "";
String tAltCount = "";
String tRefCount = "";
Element caseNode = this.extractCaseNode(caseDoc);
if (caseNode == null)
{
return; // no case to process
}
// TODO sample barcode?
//fmiCaseID = caseNode.getAttribute("fmiCase");
String caseID = caseNode.getAttribute("case");
Element variantReport = this.extractVariantReport(caseNode);
if (variantReport != null)
{
NodeList shortVariants = variantReport.getElementsByTagName("short-variant");
for (int i = 0; i < shortVariants.getLength(); i++)
{
Node shortVar = shortVariants.item(i);
if (shortVar.getNodeType() == Node.ELEMENT_NODE)
{
String depth = ((Element)shortVar).getAttribute("depth");
String percentReads = ((Element)shortVar).getAttribute("percent-reads");
String position = ((Element)shortVar).getAttribute("position");
gene = ((Element)shortVar).getAttribute("gene");
proteinEffect = ((Element)shortVar).getAttribute("protein-effect");
status = ((Element)shortVar).getAttribute("status");
transcript = ((Element)shortVar).getAttribute("transcript");
strand = ((Element)shortVar).getAttribute("strand");
functionalEffect = ((Element)shortVar).getAttribute("functional-effect");
// extract position information
String[] parts = position.split(":");
if (parts.length > 1)
{
chromosome = parts[0];
parts = parts[1].split("-");
if (parts.length > 0)
{
startPos = parts[0];
}
if (parts.length > 1)
{
endPos = parts[1];
}
}
// try to calculate allele counts
try {
long tumorAltCount = Math.round(Long.parseLong(depth) *
Double.parseDouble(percentReads) / 100);
long tumorRefCount = Long.parseLong(depth) - tumorAltCount;
tAltCount = Long.toString(tumorAltCount);
tRefCount = Long.toString(tumorRefCount);
} catch (NumberFormatException e) {
// empty or invalid depth & percent values
}
}
}
}
// append the data as a single line
content.append(gene); // hugo_symbol
content.append("\t");
content.append(chromosome);
content.append("\t");
content.append(startPos);
content.append("\t");
content.append(endPos);
content.append("\t");
content.append(strand);
content.append("\t");
content.append(functionalEffect); // variant_classification
content.append("\t");
content.append(status); // mutation status or validation status or smt else?
content.append("\t");
content.append(proteinEffect); // amino_acid_change
content.append("\t");
content.append(transcript);
content.append("\t");
content.append(tRefCount);
content.append("\t");
content.append(tAltCount);
content.append("\n");
}
protected Element extractCaseNode(Document caseDoc)
{
NodeList cases = caseDoc.getElementsByTagName("Case");
if (cases.getLength() == 0)
{
return null; // no case to process
}
// TODO process all cases, or just use the first one?
Node caseNode = cases.item(0);
if (caseNode.getNodeType() != Node.ELEMENT_NODE)
{
return null; // no case to process
}
return (Element)caseNode;
}
protected Element extractVariantReport(Element caseNode)
{
NodeList variantReports = caseNode.getElementsByTagName("variant-report");
Node variantReport = variantReports.item(0); // assuming there is only one variant report
if (variantReport.getNodeType() != Node.ELEMENT_NODE)
{
return null;
}
return (Element)variantReport;
}
protected String fetchCaseRecord(Node caseNode, ICaseInfoService foundationService)
{
String record = null;
if (caseNode.getNodeType() == Node.ELEMENT_NODE)
{
String fmiCaseID = ((Element)caseNode).getAttribute("fmiCase");
String caseID = ((Element)caseNode).getAttribute("case");
System.out.println(caseID);
if (LOG.isInfoEnabled()) {
LOG.info("fetch(), fetching case : " + caseID);
}
try {
record = foundationService.getCase(caseID);
} catch (ServerSOAPFaultException e) {
// we get here if record does not exist on server side (yet)
if (LOG.isInfoEnabled()) {
LOG.info("fetch(), Cannot fetch case record for case: " + caseID);
}
}
}
return record;
}
protected NodeList fetchCaseList(ICaseInfoService foundationService)
throws ParserConfigurationException, IOException, SAXException
{
if (LOG.isInfoEnabled()) {
LOG.info("fetch(), fetching case list.");
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(foundationService.getCaseList())));
return doc.getElementsByTagName("Case");
}
/**
* Fetchers reference data from an external datasource.
*
* @param referenceMetadata ReferenceMetadata
* @throws Exception
*/
@Override
public void fetchReferenceData(ReferenceMetadata referenceMetadata) throws Exception {
throw new UnsupportedOperationException();
}
}
|
package org.intermine.webservice.query.result;
import javax.servlet.http.HttpServletRequest;
/**
* Processes service request. Evaluates parameters and validates them and check if
* its combination is valid.
* @author Jakub Kulaviak
**/
public class QueryResultRequestParser extends WebServiceRequestParser
{
private static final String QUERY_PARAMETER = "query";
/** Compute total count parameter name. **/
public static final String COMPUTE_TOTAL_COUNT_PARAMETER = "tcount";
private HttpServletRequest request;
/**
* RequestProcessor constructor.
* @param request request
*/
public QueryResultRequestParser(HttpServletRequest request) {
this.request = request;
}
private String invalidParameterMsg(String name, String value) {
return "invalid " + name + " parameter: " + value;
}
/**
* Returns parsed parameters in parameter object - so this
* values can be easily get from this object.
* @return web service input
*/
public QueryResultInput getInput() {
QueryResultInput input = new QueryResultInput();
parseRequest(request, input);
return input;
}
private void parseRequest(HttpServletRequest request, QueryResultInput input) {
super.parseRequest(request, input);
String xmlQuery = request.getParameter(QUERY_PARAMETER);
if (xmlQuery == null || xmlQuery.equals("")) {
input.addError("invalid " + QUERY_PARAMETER + " parameter (empty or missing)");
} else {
input.setXml(xmlQuery);
}
String totalCount = request.getParameter(COMPUTE_TOTAL_COUNT_PARAMETER);
if (totalCount != null) {
input.setComputeTotalCount(true);
}
}
}
|
package com.ibm.streamsx.topology.internal.context.streams;
import static com.ibm.streamsx.topology.internal.context.remote.DeployKeys.deploy;
import static com.ibm.streamsx.topology.internal.context.remote.DeployKeys.keepArtifacts;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ibm.streamsx.rest.Instance;
import com.ibm.streamsx.rest.Job;
import com.ibm.streamsx.rest.Result;
import com.ibm.streamsx.topology.context.ContextProperties;
import com.ibm.streamsx.topology.context.remote.RemoteContext;
import com.ibm.streamsx.topology.internal.context.remote.SubmissionResultsKeys;
import com.ibm.streamsx.topology.internal.context.streamsrest.DistributedStreamsRestContext;
import com.ibm.streamsx.topology.internal.gson.GsonUtilities;
import com.ibm.streamsx.topology.internal.process.CompletedFuture;
import com.ibm.streamsx.topology.internal.streams.InvokeSubmit;
import com.ibm.streamsx.topology.internal.streams.Util;
public class DistributedStreamsContext extends
BundleUserStreamsContext<BigInteger> {
private final AtomicBoolean useRestApi = new AtomicBoolean();
private Instance instance;
public DistributedStreamsContext() {
super(false);
}
public boolean useRestApi() {
return useRestApi.get();
}
@Override
public Type getType() {
return Type.DISTRIBUTED;
}
private Instance getConfigInstance(AppEntity entity) {
Map<String,Object> config = entity.config;
if (config != null && config.containsKey(ContextProperties.STREAMS_INSTANCE)) {
Object instance = config.get(ContextProperties.STREAMS_INSTANCE);
if (instance instanceof Instance)
return (Instance) instance;
}
return null;
}
public synchronized Instance instance() throws IOException {
if (!useRestApi())
throw new IllegalStateException(/*internal error*/);
return instance;
}
private synchronized Instance createInstance(AppEntity entity) throws IOException {
if (!useRestApi())
throw new IllegalStateException(/*internal error*/);
Instance instance = getConfigInstance(entity);
if (instance == null) {
boolean verify = true;
if (deploy(entity.submission).has(ContextProperties.SSL_VERIFY))
verify = deploy(entity.submission).get(ContextProperties.SSL_VERIFY).getAsBoolean();
instance = Instance.ofEndpoint(
(String) null, (String) null, (String) null, (String) null,
verify);
}
return instance;
}
@Override
protected void preSubmit(AppEntity entity) {
if (getConfigInstance(entity) != null) {
// Allow the config to provide an instance.
useRestApi.set(true);
return;
}
try {
InvokeSubmit.checkPreconditions();
useRestApi.set(false);
} catch (IllegalStateException e) {
// See if the REST api is setup.
Util.getenv(Util.ICP4D_DEPLOYMENT_URL);
Util.getenv(Util.STREAMS_INSTANCE_ID);
Util.getenv(Util.STREAMS_PASSWORD);
useRestApi.set(true);
}
}
@Override
protected final Future<BigInteger> action(AppEntity entity) throws Exception {
if (useRemoteBuild(entity, e -> 7))
return fullRemoteAction(entity);
return super.action(entity);
}
/**
* Called to build and submit using REST.
* V5 path when remote build occurs due to being forced or
* non-matching operating system with instance.
*/
protected Future<BigInteger> fullRemoteAction(AppEntity entity) throws Exception {
DistributedStreamsRestContext rc = new DistributedStreamsRestContext();
rc.submit(entity.submission);
JsonObject results = GsonUtilities.objectCreate(entity.submission,
RemoteContext.SUBMISSION_RESULTS);
String id = GsonUtilities.jstring(results, "id");
instance = rc.instance();
return new CompletedFuture<>(new BigInteger(id));
}
/**
* V4 path with local build and job submission using streamtool.
*/
@Override
Future<BigInteger> invoke(AppEntity entity, File bundle) throws Exception {
try {
if (useRestApi()) {
final BigInteger jobId = invokeUsingRest(entity, bundle);
return new CompletedFuture<>(jobId);
}
InvokeSubmit submitjob = new InvokeSubmit(bundle);
final BigInteger jobId = submitjob.invoke(deploy(entity.submission), null, null);
final JsonObject submissionResult = GsonUtilities.objectCreate(entity.submission, RemoteContext.SUBMISSION_RESULTS);
submissionResult.addProperty(SubmissionResultsKeys.JOB_ID, jobId.toString());
submissionResult.addProperty(SubmissionResultsKeys.INSTANCE_ID, Util.getDefaultInstanceId());
return new CompletedFuture<>(jobId);
} finally {
if (!keepArtifacts(entity.submission))
bundle.delete();
}
}
/**
* V5 path when local build occurred,
* (V5 is always job submission using REST).
*/
protected BigInteger invokeUsingRest(AppEntity entity, File bundle) throws Exception {
instance = createInstance(entity);
Result<Job, JsonObject> result = instance.submitJob(bundle, deploy(entity.submission));
result.getRawResult().addProperty(SubmissionResultsKeys.INSTANCE_ID, instance.getId());
final JsonObject submissionResult = GsonUtilities.objectCreate(entity.submission, RemoteContext.SUBMISSION_RESULTS);
for (Entry<String, JsonElement> kv : result.getRawResult().entrySet())
submissionResult.add(kv.getKey(), kv.getValue());
return new BigInteger(result.getId());
}
}
|
package tigase.jaxmpp.j2se.connectors.socket;
import tigase.jaxmpp.core.client.BareJID;
import tigase.jaxmpp.core.client.PacketWriter;
import tigase.jaxmpp.core.client.SessionObject;
import tigase.jaxmpp.core.client.XmppModulesManager;
import tigase.jaxmpp.core.client.XmppSessionLogic;
import tigase.jaxmpp.core.client.exceptions.JaxmppException;
import tigase.jaxmpp.core.client.observer.Listener;
import tigase.jaxmpp.core.client.xml.XMLException;
import tigase.jaxmpp.core.client.xmpp.modules.ResourceBinderModule;
import tigase.jaxmpp.core.client.xmpp.modules.ResourceBinderModule.ResourceBindEvent;
import tigase.jaxmpp.core.client.xmpp.modules.SessionEstablishmentModule;
import tigase.jaxmpp.core.client.xmpp.modules.SessionEstablishmentModule.SessionEstablishmentEvent;
import tigase.jaxmpp.core.client.xmpp.modules.StreamFeaturesModule;
import tigase.jaxmpp.core.client.xmpp.modules.StreamFeaturesModule.StreamFeaturesReceivedEvent;
import tigase.jaxmpp.core.client.xmpp.modules.auth.AuthModule;
import tigase.jaxmpp.core.client.xmpp.modules.auth.NonSaslAuthModule;
import tigase.jaxmpp.core.client.xmpp.modules.auth.NonSaslAuthModule.NonSaslAuthEvent;
import tigase.jaxmpp.core.client.xmpp.modules.auth.SaslModule.SaslEvent;
import tigase.jaxmpp.core.client.xmpp.modules.presence.PresenceModule;
import tigase.jaxmpp.core.client.xmpp.modules.roster.RosterModule;
public class SocketXmppSessionLogic implements XmppSessionLogic {
private AuthModule authModule;
private final SocketConnector connector;
private StreamFeaturesModule featuresModule;
private final XmppModulesManager modulesManager;
private ResourceBinderModule resourceBinder;
private Listener<ResourceBindEvent> resourceBindListener;
private final Listener<AuthModule.AuthEvent> saslEventListener;
private Listener<SessionEstablishmentEvent> sessionEstablishmentListener;
private SessionEstablishmentModule sessionEstablishmentModule;
private SessionListener sessionListener;
private final SessionObject sessionObject;
private final Listener<StreamFeaturesReceivedEvent> streamFeaturesEventListener;
public SocketXmppSessionLogic(SocketConnector connector, XmppModulesManager modulesManager, SessionObject sessionObject,
PacketWriter writer) {
this.connector = connector;
this.modulesManager = modulesManager;
this.sessionObject = sessionObject;
this.streamFeaturesEventListener = new Listener<StreamFeaturesModule.StreamFeaturesReceivedEvent>() {
@Override
public void handleEvent(StreamFeaturesReceivedEvent be) throws JaxmppException {
try {
processStreamFeatures(be);
} catch (JaxmppException e) {
processException(e);
}
}
};
this.saslEventListener = new Listener<AuthModule.AuthEvent>() {
@Override
public void handleEvent(AuthModule.AuthEvent be) throws JaxmppException {
try {
if (be instanceof SaslEvent) {
processSaslEvent((SaslEvent) be);
} else if (be instanceof NonSaslAuthEvent) {
processNonSaslEvent((NonSaslAuthEvent) be);
}
} catch (JaxmppException e) {
processException(e);
}
}
};
this.resourceBindListener = new Listener<ResourceBindEvent>() {
@Override
public void handleEvent(ResourceBindEvent be) throws JaxmppException {
try {
processResourceBindEvent(be);
} catch (JaxmppException e) {
processException(e);
}
}
};
this.sessionEstablishmentListener = new Listener<SessionEstablishmentModule.SessionEstablishmentEvent>() {
@Override
public void handleEvent(SessionEstablishmentEvent be) throws JaxmppException {
sessionBindedAndEstablished();
}
};
}
@Override
public void beforeStart() throws JaxmppException {
if (sessionObject.getProperty(SessionObject.USER_BARE_JID) == null)
throw new JaxmppException("No user JID specified");
if (sessionObject.getProperty(SessionObject.SERVER_NAME) == null)
sessionObject.setProperty(SessionObject.SERVER_NAME,
((BareJID) sessionObject.getProperty(SessionObject.USER_BARE_JID)).getDomain());
}
@Override
public void bind(SessionListener sessionListener) throws JaxmppException {
this.sessionListener = sessionListener;
featuresModule = this.modulesManager.getModule(StreamFeaturesModule.class);
authModule = this.modulesManager.getModule(AuthModule.class);
resourceBinder = this.modulesManager.getModule(ResourceBinderModule.class);
this.sessionEstablishmentModule = this.modulesManager.getModule(SessionEstablishmentModule.class);
featuresModule.addListener(StreamFeaturesModule.StreamFeaturesReceived, streamFeaturesEventListener);
authModule.addListener(AuthModule.AuthSuccess, this.saslEventListener);
authModule.addListener(AuthModule.AuthFailed, this.saslEventListener);
resourceBinder.addListener(ResourceBinderModule.ResourceBindSuccess, resourceBindListener);
this.sessionEstablishmentModule.addListener(SessionEstablishmentModule.SessionEstablishmentSuccess,
this.sessionEstablishmentListener);
this.sessionEstablishmentModule.addListener(SessionEstablishmentModule.SessionEstablishmentError,
this.sessionEstablishmentListener);
}
protected void processException(JaxmppException e) throws JaxmppException {
if (sessionListener != null)
sessionListener.onException(e);
}
protected void processNonSaslEvent(final NonSaslAuthModule.NonSaslAuthEvent be) throws JaxmppException {
if (be.getType() == AuthModule.AuthFailed) {
throw new JaxmppException("Unauthorized with condition=" + be.getError());
} else if (be.getType() == AuthModule.AuthSuccess) {
connector.restartStream();
}
}
protected void processResourceBindEvent(ResourceBindEvent be) throws JaxmppException {
if (SessionEstablishmentModule.isSessionEstablishingAvailable(sessionObject)) {
modulesManager.getModule(SessionEstablishmentModule.class).establish();
} else
sessionBindedAndEstablished();
}
protected void processSaslEvent(SaslEvent be) throws JaxmppException {
if (be.getType() == AuthModule.AuthFailed) {
throw new JaxmppException("Unauthorized with condition=" + be.getError());
} else if (be.getType() == AuthModule.AuthSuccess) {
connector.restartStream();
}
}
protected void processStreamFeatures(StreamFeaturesReceivedEvent be) throws JaxmppException {
try {
final Boolean tlsDisabled = sessionObject.getProperty(SocketConnector.TLS_DISABLED_KEY);
final boolean authAvailable = AuthModule.isAuthAvailable(sessionObject);
final boolean tlsAvailable = SocketConnector.isTLSAvailable(sessionObject);
final boolean isAuthorized = sessionObject.getProperty(AuthModule.AUTHORIZED) == Boolean.TRUE;
final boolean isConnectionSecure = connector.isSecure();
if (!isConnectionSecure && tlsAvailable && (tlsDisabled == null || !tlsDisabled)) {
connector.startTLS();
} else if (!isAuthorized && authAvailable) {
authModule.login();
} else if (isAuthorized) {
resourceBinder.bind();
}
} catch (XMLException e) {
e.printStackTrace();
}
}
private void sessionBindedAndEstablished() throws JaxmppException {
try {
RosterModule roster = this.modulesManager.getModule(RosterModule.class);
if (roster != null) {
roster.rosterRequest();
}
PresenceModule presence = this.modulesManager.getModule(PresenceModule.class);
if (presence != null) {
presence.sendInitialPresence();
}
} catch (XMLException e) {
e.printStackTrace();
}
}
@Override
public void unbind() throws JaxmppException {
featuresModule.removeListener(StreamFeaturesModule.StreamFeaturesReceived, streamFeaturesEventListener);
authModule.removeListener(AuthModule.AuthSuccess, this.saslEventListener);
authModule.removeListener(AuthModule.AuthFailed, this.saslEventListener);
resourceBinder.removeListener(ResourceBinderModule.ResourceBindSuccess, resourceBindListener);
this.sessionEstablishmentModule.removeListener(SessionEstablishmentModule.SessionEstablishmentSuccess,
this.sessionEstablishmentListener);
this.sessionEstablishmentModule.removeListener(SessionEstablishmentModule.SessionEstablishmentError,
this.sessionEstablishmentListener);
}
}
|
package info.naiv.lab.java.jmt.template;
import info.naiv.lab.java.jmt.io.ResourceRepository;
import info.naiv.lab.java.jmt.io.SuffixAndExtensionFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.springframework.core.io.Resource;
/**
*
* @author enlo
* @param <TResult>
*/
public abstract class AbstractResourceTemplateLoader<TResult> extends AbstractTemplateLoader<TResult> {
@Getter
@Setter
private String extension = "txt";
/**
*
* @param name
* @param resource
* @param charset
* @return
* @throws IOException
*/
protected abstract Template<TResult> createTemplateFromResource(String name, Resource resource, Charset charset) throws IOException;
/**
*
* @param category
* @param name
* @param charset
* @return
* @throws IOException
*/
@Override
protected Template<TResult> doLoad(String category, String name, Charset charset) throws IOException {
SuffixAndExtensionFilter filter = new SuffixAndExtensionFilter(name, getSuffix(), getExtension(), true);
Resource res = getResourceRepository().getResource(category, filter);
if (res != null) {
String fullname = buildName(category, res.getFilename());
return createTemplateFromResource(fullname, res, charset);
}
else {
return null;
}
}
/**
*
* @param category
* @param charset
* @return
* @throws IOException
*/
@Override
protected Iterable<Template<TResult>> doLoadCategory(String category, Charset charset) throws IOException {
SuffixAndExtensionFilter filter = new SuffixAndExtensionFilter("[^.]+", getSuffix(), getExtension(), true);
Map<String, Resource> list = getResourceRepository().getResources(category, filter);
List<Template<TResult>> result = new ArrayList<>(list.size());
for (Resource res : list.values()) {
String fullname = buildName(category, res.getFilename());
Template<TResult> st = createTemplateFromResource(fullname, res, charset);
if (st != null) {
result.add(st);
}
}
return result;
}
/**
*
* @return
*/
protected abstract ResourceRepository getResourceRepository();
}
|
package org.languagetool.rules.spelling.hunspell;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import org.apache.commons.lang3.StringUtils;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.Language;
import org.languagetool.rules.Categories;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.spelling.SpellingCheckRule;
public class HunspellRule extends SpellingCheckRule {
public static final String RULE_ID = "HUNSPELL_RULE";
protected boolean needsInit = true;
protected Hunspell.Dictionary hunspellDict = null;
private static final String NON_ALPHABETIC = "[^\\p{L}]";
private static final String[] WHITESPACE_ARRAY = new String[20];
static {
for (int i = 0; i < 20; i++) {
WHITESPACE_ARRAY[i] = StringUtils.repeat(' ', i);
}
}
protected Pattern nonWordPattern;
public HunspellRule(ResourceBundle messages, Language language) {
super(messages, language);
super.setCategory(Categories.TYPOS.getCategory(messages));
}
@Override
public String getId() {
return RULE_ID;
}
@Override
public String getDescription() {
return messages.getString("desc_spelling");
}
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
if (needsInit) {
init();
}
if (hunspellDict == null) {
// some languages might not have a dictionary, be silent about it
return toRuleMatchArray(ruleMatches);
}
String[] tokens = tokenizeText(getSentenceTextWithoutUrlsAndImmunizedTokens(sentence));
// starting with the first token to skip the zero-length START_SENT
int len = sentence.getTokens()[1].getStartPos();
for (int i = 0; i < tokens.length; i++) {
String word = tokens[i];
if (ignoreWord(Arrays.asList(tokens), i) || ignoreWord(word)) {
len += word.length() + 1;
continue;
}
if (isMisspelled(word)) {
RuleMatch ruleMatch = new RuleMatch(this,
len, len + word.length(),
messages.getString("spelling"),
messages.getString("desc_spelling_short"));
List<String> suggestions = getSuggestions(word);
List<String> additionalTopSuggestions = getAdditionalTopSuggestions(suggestions, word);
Collections.reverse(additionalTopSuggestions);
for (String additionalTopSuggestion : additionalTopSuggestions) {
if (!word.equals(additionalTopSuggestion)) {
suggestions.add(0, additionalTopSuggestion);
}
}
List<String> additionalSuggestions = getAdditionalSuggestions(suggestions, word);
for (String additionalSuggestion : additionalSuggestions) {
if (!word.equals(additionalSuggestion)) {
suggestions.addAll(additionalSuggestions);
}
}
if (!suggestions.isEmpty()) {
filterSuggestions(suggestions);
filterDupes(suggestions);
ruleMatch.setSuggestedReplacements(suggestions);
}
ruleMatches.add(ruleMatch);
}
len += word.length() + 1;
}
return toRuleMatchArray(ruleMatches);
}
boolean isMisspelled(String word) {
boolean isAlphabetic = true;
if (word.length() == 1) { // hunspell dictionaries usually do not contain punctuation
isAlphabetic = Character.isAlphabetic(word.charAt(0));
}
return (isAlphabetic && !"--".equals(word) && hunspellDict.misspelled(word)) || isProhibited(removeTrailingDot(word));
}
void filterDupes(List<String> words) {
Set<String> seen = new HashSet<>();
Iterator<String> iterator = words.iterator();
while (iterator.hasNext()) {
String word = iterator.next();
if (seen.contains(word)) {
iterator.remove();
}
seen.add(word);
}
}
private String removeTrailingDot(String word) {
if (word.endsWith(".")) {
return word.substring(0, word.length()-1);
}
return word;
}
public List<String> getSuggestions(String word) throws IOException {
if (needsInit) {
init();
}
return hunspellDict.suggest(word);
}
protected String[] tokenizeText(String sentence) {
return nonWordPattern.split(sentence);
}
private String getSentenceTextWithoutUrlsAndImmunizedTokens(AnalyzedSentence sentence) {
StringBuilder sb = new StringBuilder();
AnalyzedTokenReadings[] sentenceTokens = getSentenceWithImmunization(sentence).getTokens();
for (int i = 1; i < sentenceTokens.length; i++) {
String token = sentenceTokens[i].getToken();
if (sentenceTokens[i].isImmunized() || isUrl(token) || isEMail(token) || sentenceTokens[i].isIgnoredBySpeller()) {
// replace URLs and immunized tokens with whitespace to ignore them for spell checking:
if (token.length() < 20) {
sb.append(WHITESPACE_ARRAY[token.length()]);
} else {
for (int j = 0; j < token.length(); j++) {
sb.append(' ');
}
}
} else if (token.length() > 1 && token.codePointCount(0, token.length()) != token.length()) {
// some symbols such as emojis () have a string length that equals 2
for (int charIndex = 0; charIndex < token.length();) {
int unicodeCodePoint = token.codePointAt(charIndex);
int increment = Character.charCount(unicodeCodePoint);
if (increment == 1) {
sb.append(token.charAt(charIndex));
} else {
sb.append(" ");
}
charIndex += increment;
}
} else {
sb.append(token);
}
}
return sb.toString();
}
@Override
protected void init() throws IOException {
super.init();
String langCountry;
if (language.getCountries().length > 0) {
langCountry = language.getShortCode() + "_" + language.getCountries()[0];
} else {
langCountry = language.getShortCode();
}
String shortDicPath = "/"
+ language.getShortCode()
+ "/hunspell/"
+ langCountry
+ ".dic";
String wordChars = "";
// set dictionary only if there are dictionary files:
if (JLanguageTool.getDataBroker().resourceExists(shortDicPath)) {
String path = getDictionaryPath(langCountry, shortDicPath);
if ("".equals(path)) {
hunspellDict = null;
} else {
hunspellDict = Hunspell.getInstance().getDictionary(path);
if (!"".equals(hunspellDict.getWordChars())) {
wordChars = "(?![" + hunspellDict.getWordChars().replace("-", "\\-") + "])";
}
addIgnoreWords();
}
}
nonWordPattern = Pattern.compile(wordChars + NON_ALPHABETIC);
needsInit = false;
}
private void addIgnoreWords() throws IOException {
hunspellDict.addWord(SpellingCheckRule.LANGUAGETOOL);
URL ignoreUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(getIgnoreFileName());
List<String> ignoreLines = Resources.readLines(ignoreUrl, Charsets.UTF_8);
for (String ignoreLine : ignoreLines) {
if (!ignoreLine.startsWith("
hunspellDict.addWord(ignoreLine);
}
}
}
private String getDictionaryPath(String dicName,
String originalPath) throws IOException {
URL dictURL = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(originalPath);
String dictionaryPath;
//in the webstart, java EE or OSGi bundle version, we need to copy the files outside the jar
//to the local temporary directory
if ("jar".equals(dictURL.getProtocol()) || "vfs".equals(dictURL.getProtocol()) || "bundle".equals(dictURL.getProtocol()) || "bundleresource".equals(dictURL.getProtocol())) {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File tempDicFile = new File(tempDir, dicName + ".dic");
JLanguageTool.addTemporaryFile(tempDicFile);
try (InputStream dicStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(originalPath)) {
fileCopy(dicStream, tempDicFile);
}
File tempAffFile = new File(tempDir, dicName + ".aff");
JLanguageTool.addTemporaryFile(tempAffFile);
try (InputStream affStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(originalPath.replaceFirst(".dic$", ".aff"))) {
fileCopy(affStream, tempAffFile);
}
dictionaryPath = tempDir.getAbsolutePath() + "/" + dicName;
} else {
int suffixLength = ".dic".length();
try {
dictionaryPath = new File(dictURL.toURI()).getAbsolutePath();
dictionaryPath = dictionaryPath.substring(0, dictionaryPath.length() - suffixLength);
} catch (URISyntaxException e) {
return "";
}
}
return dictionaryPath;
}
private void fileCopy(InputStream in, File targetFile) throws IOException {
try (OutputStream out = new FileOutputStream(targetFile)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
}
}
}
|
package test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import bot.Bot;
public class BotTests {
@Test
public void connectionTest() throws IOException {
Bot bot = new Bot(System.getenv(Bot.TOKEN_NAME));
assertFalse(bot.isConnected());
bot.connect();
assertTrue(bot.isConnected());
bot.disconnect();
assertFalse(bot.isConnected());
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyil;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import wybs.lang.Builder;
import wyil.io.WyilFileWriter;
import wyil.transforms.*;
/**
* A Pipeline consists of a number of stages which are applied to the
* intermediate language (wyil). A pipeline is instantiated before being used to
* create an instance of Compiler.
*
* @author David J. Pearce
*
*/
public class Pipeline {
/**
* Identify transforms which are registered for use with the Whiley
* Compiler.
*/
private static final ArrayList<Class<? extends Transform>> transforms = new ArrayList();
/**
* The list of stage templates which make up this pipeline. When the
* pipeline is instantiated, these stages are instantiated.
*/
private final ArrayList<Template> stages;
public Pipeline(List<Template> stages) {
this.stages = new ArrayList<Template>(stages);
}
public static final List<Template> defaultPipeline = Collections
.unmodifiableList(new ArrayList<Template>() {
{
add(new Template(DefiniteAssignmentCheck.class, Collections.EMPTY_MAP));
add(new Template(ModuleCheck.class, Collections.EMPTY_MAP));
add(new Template(ConstraintInline.class, Collections.EMPTY_MAP));
add(new Template(WyilFileWriter.class, Collections.EMPTY_MAP));
add(new Template(BackPropagation.class, Collections.EMPTY_MAP));
// Constant Propagation is disabled as there are some
// serious problems with that phase.
//add(new Template(ConstantPropagation.class, Collections.EMPTY_MAP));
add(new Template(CoercionCheck.class, Collections.EMPTY_MAP));
add(new Template(DeadCodeElimination.class, Collections.EMPTY_MAP));
add(new Template(VerificationCheck.class, Collections.EMPTY_MAP));
add(new Template(LiveVariablesAnalysis.class, Collections.EMPTY_MAP));
// add(new Template(WyilFileWriter.class, Collections.EMPTY_MAP));
}
});
/**
* Register default transforms. This is necessary so they can be referred to
* from the command-line using abbreviated names, rather than their full
* names.
*/
static {
register(BackPropagation.class);
register(DefiniteAssignmentCheck.class);
register(ConstantPropagation.class);
register(ModuleCheck.class);
register(ConstraintInline.class);
register(CoercionCheck.class);
register(WyilFileWriter.class);
register(DeadCodeElimination.class);
register(LiveVariablesAnalysis.class);
register(VerificationCheck.class);
}
/**
* Set a specific option on a given pipeline stage. The previous value of
* this option is returned, or null if there is none.
*
* @param clazz
* @param name
* @param value
* @return
*/
public Object setOption(Class<? extends Transform> clazz, String name,
Object value) {
for (Template template : stages) {
if (template.clazz == clazz) {
Map<String,Object> options = template.options;
if(options == Collections.EMPTY_MAP) {
options = new HashMap<String,Object>();
template.options = options;
}
return options.put(name, value);
}
}
return null;
}
/**
* Apply a list of modifiers in the order of appearance. Modifiers may
* remove stages, add new stages or reconfigure existing stages.
*
* @param modifiers
*/
public void apply(List<Modifier> modifiers) {
for (Modifier p : modifiers) {
Class<? extends Transform> stage = lookupTransform(p.name);
if(stage == null) {
throw new IllegalArgumentException("invalid pipeline stage \"" + p.name + "\"");
}
switch(p.op) {
case APPEND:
stages.add(new Template(stage,p.options));
break;
case REPLACE:
{
int index = findTransform(lookupTransform(p.name));
stages.set(index,new Template(stage,p.options));
break;
}
case REMOVE:
{
int index = findTransform(lookupTransform(p.name));
stages.remove(index);
break;
}
}
}
}
public List<Transform> instantiate(Builder builder) {
ArrayList<Transform> pipeline = new ArrayList<Transform>();
for (Template s : stages) {
pipeline.add(s.instantiate(builder));
}
return pipeline;
}
/**
* A template is an uninstantiated pipeline stage. This contains all of the
* necessary information to instantiate the stage.
*
* @author David J. Pearce
*/
public static class Template {
Class<? extends Transform> clazz;
public Map<String,Object> options;
public Template(Class<? extends Transform> clazz,
Map<String, Object> options) {
this.clazz = clazz;
this.options = options;
}
/**
* Construct an instance of a given compiler stage, using the given argument
* list. A constructor which accepts a ModuleLoader, and Map<String,String>
* arguments will be called. If such a constructor doesn't exist, an
* exception will be raised.
*
* @return
*/
public Transform instantiate(Builder builder) {
Transform stage;
// first, instantiate the transform
try {
Constructor<? extends Transform> c = clazz.getConstructor(
Builder.class);
stage = (Transform) c.newInstance(builder);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"failed to instantiate transform \""
+ clazz.getSimpleName() + "\"",e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(
"failed to instantiate transform \""
+ clazz.getSimpleName() + "\"",e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(
"failed to instantiate transform \""
+ clazz.getSimpleName() + "\"",e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(
"failed to instantiate transform \""
+ clazz.getSimpleName() + "\"",e);
}
// second, configure the instance
String attribute = "";
try {
for (Map.Entry<String, Object> e : options.entrySet()) {
attribute = e.getKey();
String name = "set" + capitalise(e.getKey());
Object value = e.getValue();
Method m;
if(value instanceof Boolean) {
m = clazz.getDeclaredMethod(name, boolean.class);
} else if(value instanceof Integer) {
m = clazz.getDeclaredMethod(name, int.class);
} else {
// default
m = clazz.getDeclaredMethod(name, value.getClass());
}
m.invoke(stage, value);
}
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("failed to set attribute \""
+ attribute + "\" on transform \""
+ clazz.getSimpleName() + "\"",e);
} catch(InvocationTargetException e) {
throw new IllegalArgumentException("failed to set attribute \""
+ attribute + "\" on transform \""
+ clazz.getSimpleName() + "\"",e);
} catch(IllegalAccessException e) {
throw new IllegalArgumentException("failed to set attribute \""
+ attribute + "\" on transform \""
+ clazz.getSimpleName() + "\"",e);
}
return stage;
}
}
/**
* Make the first letter of the string a captial.
* @param str
* @return
*/
private static String capitalise(String str) {
String rest = str.substring(1);
char c = Character.toUpperCase(str.charAt(0));
return c + rest;
}
/**
* The pipeline modifier captures a requested adjustment to the compilation
* pipeline.
*
* @author David J. Pearce
*/
public static class Modifier {
public final POP op;
public final String name;
public final Map<String,Object> options;
public Modifier(POP pop, String name, Map<String, Object> options) {
this.op = pop;
this.name = name;
this.options = options;
}
}
public enum POP {
APPEND,
BEFORE,
AFTER,
REPLACE,
REMOVE
}
/**
* Search through the pipeline looking form the first matching stage.
*
* @param match
* @return
*/
private int findTransform(Class<? extends Transform> match) {
int i = 0;
for (Template stage : stages) {
if (stage.clazz == match) {
return i;
}
++i;
}
throw new IllegalArgumentException("invalid stage name \"" + match
+ "\"");
}
/**
* Register a transform with the system, in order that it can be used in a
* given Pipeline. This is particularly useful because it allows transforms
* to be referred to by abbreviations in pipeline modifiers.
*
* @param transform
*/
public static void register(Class<? extends Transform> transform) {
transforms.add(transform);
}
/**
* Lookup a transform in the list of registered transforms. This matches the
* given name again the class names of registered transforms. The matching
* of names is case-insensitive and will also match a substring.
*
* @param name
* @return
*/
public static Class<? extends Transform> lookupTransform(String name) {
name = name.toLowerCase();
for (Class<? extends Transform> t : transforms) {
String tn = t.getSimpleName().toLowerCase();
if (tn.startsWith(name)) {
return t;
}
}
throw new IllegalArgumentException("no transform matching \"" + name
+ "\"");
}
}
|
package net.worcade.client.query;
import net.worcade.client.internal.WorcadeQuery;
import java.util.Collection;
public interface Query<T extends EntityField> {
static Builder<AssetField> asset() {
return WorcadeQuery.builder();
}
static Builder<ConversationField> conversation() {
return WorcadeQuery.builder();
}
static Builder<GroupField> group() {
return WorcadeQuery.builder();
}
static Builder<LabelField> label() {
return WorcadeQuery.builder();
}
static Builder<RoomField> room() {
return WorcadeQuery.builder();
}
static Builder<SiteField> site() {
return WorcadeQuery.builder();
}
static Builder<ContactField> contacts() {
return WorcadeQuery.builder();
}
static Builder<WebhookField> webhook() {
return WorcadeQuery.builder();
}
interface Builder<T extends EntityField> {
/**
* Add the specified fields to the result
*/
@SuppressWarnings("unchecked")
Builder<T> fields(T... fields);
/**
* Add the specified fields to the result
*/
Builder<T> fields(Collection<T> fields);
Builder<T> filter(T field, String value);
Builder<T> order(T field, boolean ascending);
/**
* Limit the amount of results returned.
* Defaults to 10. Cannot exceed 100.
*/
Builder<T> limit(int limit);
/**
* Text to search for
*/
Builder<T> search(String search);
Query<T> build();
}
}
|
package jodd.lagarto.dom;
import jodd.lagarto.Doctype;
import jodd.lagarto.Tag;
import jodd.lagarto.TagType;
import jodd.lagarto.TagUtil;
import jodd.lagarto.TagVisitor;
import jodd.util.JoddScript;
import jodd.util.StringPool;
import jodd.log.Logger;
import jodd.log.LoggerFactory;
/**
* Lagarto tag visitor that builds DOM tree.
* It (still) does not build the tree <i>fully</i> by the HTML specs,
* however, it works good enough for any sane HTML out there.
* In the default mode, the tree builder does <b>not</b> change
* the order of the elements, so the returned tree reflects
* the input. So if the input contains crazy stuff, the tree will
* be weird, too :)
* <p>
* In experimental <i>html-plus</i> mode we do have some
* further HTML5 rules implemented, that according to some rules
* may change the node position. However, not all rules are
* implemented (yet) and this is still just experimental.
*/
public class LagartoDOMBuilderTagVisitor implements TagVisitor {
private static final Logger log = LoggerFactory.getLogger(LagartoDOMBuilderTagVisitor.class);
protected final LagartoDOMBuilder domBuilder;
protected final HtmlImplicitClosingRules implRules = new HtmlImplicitClosingRules();
protected HtmlVoidRules htmlVoidRules;
protected Document rootNode;
protected Node parentNode;
/**
* While enabled, nodes will be added to the DOM tree.
* Useful for skipping some tags.
*/
protected boolean enabled;
public LagartoDOMBuilderTagVisitor(LagartoDOMBuilder domBuilder) {
this.domBuilder = domBuilder;
}
/**
* Returns root {@link Document document} node of parsed DOM tree.
*/
public Document getDocument() {
return rootNode;
}
/**
* Starts with DOM building.
* Creates root {@link jodd.lagarto.dom.Document} node.
*/
public void start() {
log.debug("DomTree builder started");
if (rootNode == null) {
rootNode = new Document(domBuilder.config, domBuilder.getRenderer());
}
parentNode = rootNode;
enabled = true;
if (domBuilder.config.isEnabledVoidTags()) {
htmlVoidRules = new HtmlVoidRules();
}
}
/**
* Finishes the tree building. Closes unclosed tags.
*/
public void end() {
if (parentNode != rootNode) {
Node thisNode = parentNode;
while (thisNode != rootNode) {
if (domBuilder.config.isImpliedEndTags()) {
if (implRules.implicitlyCloseTagOnEOF(thisNode.getNodeName())) {
thisNode = thisNode.getParentNode();
continue;
}
}
error("Unclosed tag closed: <" + thisNode.getNodeName() + ">");
thisNode = thisNode.getParentNode();
}
}
// remove whitespaces
if (domBuilder.config.isIgnoreWhitespacesBetweenTags()) {
removeLastChildNodeIfEmptyText(parentNode, true);
}
// foster
if (domBuilder.config.isUseFosterRules()) {
HtmlFosterRules fosterRules = new HtmlFosterRules();
fosterRules.fixFosterElements(rootNode);
}
// elapsed
rootNode.end();
if (log.isDebugEnabled()) {
log.debug("LagartoDom tree created in " + rootNode.getElapsedTime() + " ms.");
}
}
/**
* Creates new element with correct configuration.
*/
protected Element createElementNode(Tag tag) {
boolean hasVoidTags = htmlVoidRules != null;
boolean isVoid = false;
boolean selfClosed = false;
if (hasVoidTags) {
isVoid = htmlVoidRules.isVoidTag(tag.getName());
// HTML and XHTML
if (isVoid) {
// it's void tag, lookup the flag
selfClosed = domBuilder.config.isSelfCloseVoidTags();
}
} else {
// XML, no voids, lookup the flag
selfClosed = domBuilder.config.isSelfCloseVoidTags();
}
return new Element(rootNode, tag, isVoid, selfClosed);
}
/**
* Visits tags.
*/
public void tag(Tag tag) {
if (!enabled) {
return;
}
TagType tagType = tag.getType();
Element node;
switch (tagType) {
case START:
if (domBuilder.config.isIgnoreWhitespacesBetweenTags()) {
removeLastChildNodeIfEmptyText(parentNode, false);
}
node = createElementNode(tag);
if (domBuilder.config.isImpliedEndTags()) {
while (true) {
String parentNodeName = parentNode.getNodeName();
if (!implRules.implicitlyCloseParentTagOnNewTag(parentNodeName, node.getNodeName())) {
break;
}
parentNode = parentNode.getParentNode();
if (log.isDebugEnabled()) {
log.debug("Implicitly closed tag <" + node.getNodeName() + "> ");
}
}
}
parentNode.addChild(node);
if (node.isVoidElement() == false) {
parentNode = node;
}
break;
case END:
if (domBuilder.config.isIgnoreWhitespacesBetweenTags()) {
removeLastChildNodeIfEmptyText(parentNode, true);
}
String tagName = tag.getName().toString();
Node matchingParent = findMatchingParentOpenTag(tagName);
if (matchingParent == parentNode) { // regular situation
parentNode = parentNode.getParentNode();
break;
}
if (matchingParent == null) { // matching open tag not found, remove it
error("Orphan closed tag ignored: </" + tagName + "> " + tag.getTagPosition());
break;
}
// try to close it implicitly
if (domBuilder.config.isImpliedEndTags()) {
boolean fixed = false;
while (implRules.implicitlyCloseParentTagOnTagEnd(parentNode.getNodeName(), tagName)) {
parentNode = parentNode.getParentNode();
if (log.isDebugEnabled()) {
log.debug("Implicitly closed tag <" + tagName + ">");
}
if (parentNode == matchingParent) {
parentNode = matchingParent.parentNode;
fixed = true;
break;
}
}
if (fixed) {
break;
}
}
// matching tag found, but it is not a regular situation
// therefore close all unclosed tags in between
fixUnclosedTagsUpToMatchingParent(tag, matchingParent);
break;
case SELF_CLOSING:
if (domBuilder.config.isIgnoreWhitespacesBetweenTags()) {
removeLastChildNodeIfEmptyText(parentNode, false);
}
node = createElementNode(tag);
parentNode.addChild(node);
break;
}
}
/**
* Removes last child node if contains just empty text.
*/
protected void removeLastChildNodeIfEmptyText(Node parentNode, boolean closedTag) {
if (parentNode == null) {
return;
}
Node lastChild = parentNode.getLastChild();
if (lastChild == null) {
return;
}
if (lastChild.getNodeType() != Node.NodeType.TEXT) {
return;
}
if (closedTag) {
if (parentNode.getChildNodesCount() == 1) {
return;
}
}
Text text = (Text) lastChild;
if (text.isBlank()) {
lastChild.detachFromParent();
}
}
/**
* Finds matching parent open tag or <code>null</code> if not found.
*/
protected Node findMatchingParentOpenTag(String tagName) {
Node parent = parentNode;
if (!rootNode.config.isCaseSensitive()) {
tagName = tagName.toLowerCase();
}
while (parent != null) {
String parentNodeName = parent.getNodeName();
if (parentNodeName != null) {
if (!rootNode.config.isCaseSensitive()) {
parentNodeName = parentNodeName.toLowerCase();
}
}
if (tagName.equals(parentNodeName)) {
return parent;
}
parent = parent.getParentNode();
}
return null;
}
/**
* Fixes all unclosed tags up to matching parent. Missing end tags will be added
* just before parent tag is closed, making the whole inner content as its tag body.
* <p>
* Tags that can be closed implicitly are checked and closed.
* <p>
* There is optional check for detecting orphan tags inside the
* table or lists. If set, tags can be closed beyond the border of the
* table and the list and it is reported as orphan tag.
* <p>
* This is just a generic solutions, closest to the rules.
*/
protected void fixUnclosedTagsUpToMatchingParent(Tag tag, Node matchingParent) {
if (domBuilder.config.isUnclosedTagAsOrphanCheck()) {
Node thisNode = parentNode;
if (!TagUtil.equalsIgnoreCase(tag.getName(), "table")) {
// check if there is table or list between this node
// and matching parent
while (thisNode != matchingParent) {
String thisNodeName = thisNode.getNodeName().toLowerCase();
if (thisNodeName.equals("table") || thisNodeName.equals("ul") || thisNodeName.equals("ol")) {
String positionString = tag.getPosition();
if (positionString == null) {
positionString = StringPool.EMPTY;
}
error("Orphan closed tag ignored: </" + tag.getName() + "> " + positionString);
return;
}
thisNode = thisNode.getParentNode();
}
}
}
while (true) {
if (parentNode == matchingParent) {
parentNode = parentNode.getParentNode();
break;
}
Node parentParentNode = parentNode.getParentNode();
if (domBuilder.config.isImpliedEndTags()) {
if (implRules.implicitlyCloseParentTagOnNewTag(
parentParentNode.getNodeName(), parentNode.getNodeName())) {
// break the tree: detach this node and append it after parent
parentNode.detachFromParent();
parentParentNode.getParentNode().addChild(parentNode);
}
}
// debug message
error("Unclosed tag closed: <" + parentNode.getNodeName() + ">");
// continue looping
parentNode = parentParentNode;
}
}
public void script(Tag tag, CharSequence body) {
if (!enabled) {
return;
}
Element node = createElementNode(tag);
parentNode.addChild(node);
if (body.length() != 0) {
Node text = new Text(rootNode, body.toString());
node.addChild(text);
}
}
public void comment(CharSequence comment) {
if (!enabled) {
return;
}
if (domBuilder.config.isIgnoreWhitespacesBetweenTags()) {
removeLastChildNodeIfEmptyText(parentNode, false);
}
if (domBuilder.config.isIgnoreComments()) {
return;
}
Node node = new Comment(rootNode, comment.toString());
parentNode.addChild(node);
}
public void text(CharSequence text) {
if (!enabled) {
return;
}
String textValue = text.toString();
Node node = new Text(rootNode, textValue);
parentNode.addChild(node);
}
public void cdata(CharSequence cdata) {
if (!enabled) {
return;
}
CData cdataNode = new CData(rootNode, cdata.toString());
parentNode.addChild(cdataNode);
}
public void xml(CharSequence version, CharSequence encoding, CharSequence standalone) {
if (!enabled) {
return;
}
XmlDeclaration xmlDeclaration = new XmlDeclaration(rootNode, version, encoding, standalone);
parentNode.addChild(xmlDeclaration);
}
public void doctype(Doctype doctype) {
if (!enabled) {
return;
}
DocumentType documentType = new DocumentType(rootNode,
JoddScript.toString(doctype.getName()),
JoddScript.toString(doctype.getPublicIdentifier()),
JoddScript.toString(doctype.getSystemIdentifier())
);
parentNode.addChild(documentType);
}
public void condComment(CharSequence expression, boolean isStartingTag, boolean isHidden, boolean isHiddenEndTag) {
String expressionString = expression.toString().trim();
if (expressionString.equals("endif")) {
enabled = true;
return;
}
if (expressionString.equals("if !IE")) {
enabled = false;
return;
}
int ieVersion = domBuilder.config.getCondCommentIEVersion();
if (htmlCCommentExpressionMatcher == null) {
htmlCCommentExpressionMatcher = new HtmlCCommentExpressionMatcher();
}
enabled = htmlCCommentExpressionMatcher.match(ieVersion, expressionString);
}
protected HtmlCCommentExpressionMatcher htmlCCommentExpressionMatcher;
public void error(String message) {
rootNode.addError(message);
log.log(domBuilder.config.getParsingErrorLogLevel(), message);
}
}
|
package org.jetbrains.jps.model.impl;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.JpsElementChildRole;
/**
* @author nik
*/
public class JpsElementChildRoleBase<E extends JpsElement> extends JpsElementChildRole<E> {
private String myDebugName;
protected JpsElementChildRoleBase(String debugName) {
myDebugName = debugName;
}
@Override
public String toString() {
return myDebugName;
}
public static <E extends JpsElement> JpsElementChildRoleBase<E> create(String debugName) {
return new JpsElementChildRoleBase<E>(debugName);
}
}
|
package org.junit.gen5.commons.util;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Collection of utilities for working with Java reflection APIs.
*
* @author Sam Brannen
* @author Stefan Bechtold
* @since 5.0
*/
public final class ReflectionUtils {
public enum MethodSortOrder {
HierarchyDown, HierarchyUp
}
private ReflectionUtils() {
/* no-op */
}
public static ClassLoader getDefaultClassLoader() {
try {
return Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
/* ignore */
}
return ClassLoader.getSystemClassLoader();
}
public static boolean isPrivate(Class<?> clazz) {
return Modifier.isPrivate(clazz.getModifiers());
}
public static boolean isPublic(Class<?> clazz) {
return Modifier.isPublic(clazz.getModifiers());
}
public static boolean isPrivate(Member member) {
return Modifier.isPrivate(member.getModifiers());
}
public static boolean isPublic(Member member) {
return Modifier.isPublic(member.getModifiers());
}
public static boolean isAbstract(Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
public static boolean isAbstract(Member member) {
return Modifier.isAbstract(member.getModifiers());
}
public static boolean isStatic(Class<?> clazz) {
return Modifier.isStatic(clazz.getModifiers());
}
public static boolean isStatic(Member member) {
return Modifier.isStatic(member.getModifiers());
}
public static <T> T newInstance(Class<T> clazz, Object... args) {
Preconditions.notNull(clazz, "class must not be null");
try {
Class<?>[] parameterTypes = Arrays.stream(args).map(Object::getClass).toArray(Class<?>[]::new);
Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
makeAccessible(constructor);
return constructor.newInstance(args);
}
catch (Throwable ex) {
handleException(ex);
}
// Appeasing the compiler: this should hopefully never happen...
throw new IllegalStateException("Exception handling algorithm in ReflectionUtils is incomplete");
}
public static Object invokeMethod(Method method, Object target, Object... args) {
Preconditions.notNull(method, "method must not be null");
Preconditions.condition((target != null || Modifier.isStatic(method.getModifiers())),
() -> String.format("Cannot invoke non-static method [%s] on a null target.", method.toGenericString()));
try {
makeAccessible(method);
return method.invoke(target, args);
}
catch (Throwable ex) {
handleException(ex);
}
// Appeasing the compiler: this should hopefully never happen...
throw new IllegalStateException("Exception handling algorithm in ReflectionUtils is incomplete");
}
public static Optional<Class<?>> loadClass(String name) {
return loadClass(name, getDefaultClassLoader());
}
public static Optional<Class<?>> loadClass(String name, ClassLoader classLoader) {
Preconditions.notBlank(name, "class name must not be null or empty");
Preconditions.notNull(classLoader, "ClassLoader must not be null");
try {
// TODO Add support for primitive types and arrays.
return Optional.of(classLoader.loadClass(name.trim()));
}
catch (ClassNotFoundException e) {
return Optional.empty();
}
}
public static <T> Optional<Class<T>> loadClass(String name, Class<T> requiredType) {
return loadClass(name, requiredType, getDefaultClassLoader());
}
@SuppressWarnings("unchecked")
public static <T> Optional<Class<T>> loadClass(String name, Class<T> requiredType, ClassLoader classLoader) {
Preconditions.notBlank(name, "class name must not be null or empty");
Preconditions.notNull(requiredType, "requiredType must not be null");
Preconditions.notNull(classLoader, "ClassLoader must not be null");
try {
// TODO Add support for primitive types and arrays.
Class<?> clazz = classLoader.loadClass(name);
if (requiredType.isAssignableFrom(clazz)) {
return Optional.of((Class<T>) clazz);
}
else {
throw new IllegalStateException(
String.format("Class [%s] is not of required type [%s]", name, requiredType.getName()));
}
}
catch (ClassNotFoundException e) {
return Optional.empty();
}
}
/**
* Try to load a method by its fully qualified name (if such a thing exists for methods).
* @param fullyQualifiedMethodName In the form 'package.subpackage.ClassName#methodName'
* @return Optional of Method
*/
public static Optional<Method> loadMethod(String fullyQualifiedMethodName) {
Preconditions.notBlank(fullyQualifiedMethodName, "full method name must not be null or empty");
//TODO Handle overloaded and inherited methods
Optional<Method> testMethodOptional = Optional.empty();
int hashPosition = fullyQualifiedMethodName.lastIndexOf('
if (hashPosition >= 0 && hashPosition < fullyQualifiedMethodName.length()) {
String className = fullyQualifiedMethodName.substring(0, hashPosition);
String methodName = fullyQualifiedMethodName.substring(hashPosition + 1);
Optional<Class<?>> methodClassOptional = loadClass(className);
if (methodClassOptional.isPresent()) {
try {
testMethodOptional = Optional.of(methodClassOptional.get().getDeclaredMethod(methodName));
}
catch (NoSuchMethodException ignore) {
}
}
}
return testMethodOptional;
}
public static Optional<Object> getOuterInstance(Object inner) {
// This is risky since it depends on the name of the field which is nowhere guaranteed
// but has been stable so far in all JDKs
Optional<Object> outerInstance = Arrays.stream(inner.getClass().getDeclaredFields()).filter(
f -> f.getName().startsWith("this$")).findFirst().map(f -> {
makeAccessible(f);
try {
return f.get(inner);
}
catch (IllegalAccessException e) {
return Optional.empty();
}
});
return outerInstance;
}
public static boolean isPackage(String packageName) {
return new ClasspathScanner(ReflectionUtils::getDefaultClassLoader, ReflectionUtils::loadClass).isPackage(
packageName);
}
public static List<Class<?>> findAllClassesInClassFiles(Predicate<Class<?>> classTester) {
ClasspathScanner scanner = new ClasspathScanner(ReflectionUtils::getDefaultClassLoader,
ReflectionUtils::loadClass);
List<Class<?>> collectedClasses = new ArrayList<>();
// @formatter:off
getAllClasspathRootDirectories().stream()
.filter(File::exists)
.forEach(root -> collectedClasses.addAll(scanner.scanForClassesInClasspathRoot(root, classTester)));
// @formatter:on
return collectedClasses;
}
private static List<File> getAllClasspathRootDirectories() {
//TODO This is quite a hack, since sometimes the classpath is quite different
//A real solution would require the build tools / IDEs to hand in all root directories
String fullClassPath = System.getProperty("java.class.path");
final String separator = System.getProperty("path.separator");
// @formatter:off
return Arrays.stream(fullClassPath.split(separator))
.filter(part -> !part.endsWith(".jar"))
.map(dirPath -> new File(dirPath))
.collect(Collectors.toList());
// @formatter:on
}
public static List<Class<?>> findAllClassesInClasspathRoot(File root, Predicate<Class<?>> classTester) {
return new ClasspathScanner(ReflectionUtils::getDefaultClassLoader,
ReflectionUtils::loadClass).scanForClassesInClasspathRoot(root, classTester);
}
public static List<Class<?>> findAllClassesInPackage(String basePackageName, Predicate<Class<?>> classTester) {
return new ClasspathScanner(ReflectionUtils::getDefaultClassLoader,
ReflectionUtils::loadClass).scanForClassesInPackage(basePackageName, classTester);
}
public static List<Class<?>> findInnerClasses(Class<?> clazz, Predicate<Class<?>> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "predicate must not be null");
return Arrays.stream(clazz.getDeclaredClasses()).filter(predicate).collect(Collectors.toList());
}
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Predicate<Method> nameAndParameterTypesMatch = (method -> method.getName().equals(methodName)
&& Arrays.equals(method.getParameterTypes(), parameterTypes));
List<Method> candidates = findMethods(clazz, nameAndParameterTypesMatch);
return (!candidates.isEmpty() ? Optional.of(candidates.get(0)) : Optional.empty());
}
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate) {
return findMethods(clazz, predicate, MethodSortOrder.HierarchyDown);
}
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate, MethodSortOrder sortOrder) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "predicate must not be null");
Preconditions.notNull(sortOrder, "MethodSortOrder must not be null");
// @formatter:off
return findAllMethodsInHierarchy(clazz, sortOrder).stream()
.filter(predicate)
.collect(toList());
// @formatter:on
}
/**
* Return all methods in superclass hierarchy except from Object.
*/
public static List<Method> findAllMethodsInHierarchy(Class<?> clazz, MethodSortOrder sortOrder) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(sortOrder, "MethodSortOrder must not be null");
// TODO Support interface default methods.
// TODO Determine if we need to support bridged methods.
List<Method> localMethods = Arrays.asList(clazz.getDeclaredMethods());
// @formatter:off
List<Method> superclassMethods = getSuperclassMethods(clazz, sortOrder).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
// @formatter:off
List<Method> interfaceMethods = getInterfaceMethods(clazz, sortOrder).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
List<Method> methods = new ArrayList<>();
if (sortOrder == MethodSortOrder.HierarchyDown) {
methods.addAll(superclassMethods);
methods.addAll(interfaceMethods);
}
methods.addAll(localMethods);
if (sortOrder == MethodSortOrder.HierarchyUp) {
methods.addAll(interfaceMethods);
methods.addAll(superclassMethods);
}
return methods;
}
private static List<Method> getInterfaceMethods(Class<?> clazz, MethodSortOrder sortOrder) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(sortOrder, "MethodSortOrder must not be null");
List<Method> allInterfaceMethods = new ArrayList<>();
for (Class<?> ifc : clazz.getInterfaces()) {
List<Method> localMethods = Arrays.stream(ifc.getDeclaredMethods()).filter(
method -> method.isDefault()).collect(Collectors.toList());
// @formatter:off
List<Method> subInterfaceMethods = getInterfaceMethods(ifc, sortOrder).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
if (sortOrder == MethodSortOrder.HierarchyDown) {
allInterfaceMethods.addAll(subInterfaceMethods);
}
allInterfaceMethods.addAll(localMethods);
if (sortOrder == MethodSortOrder.HierarchyUp) {
allInterfaceMethods.addAll(subInterfaceMethods);
}
}
return allInterfaceMethods;
}
private static List<Method> getSuperclassMethods(Class<?> clazz, MethodSortOrder sortOrder) {
if (clazz.getSuperclass() != Object.class) {
return findAllMethodsInHierarchy(clazz.getSuperclass(), sortOrder);
}
else {
return Collections.emptyList();
}
}
private static boolean isMethodShadowedByLocalMethods(Method method, List<Method> localMethods) {
return localMethods.stream().anyMatch(local -> isMethodShadowedBy(method, local));
}
private static boolean isMethodShadowedBy(Method upper, Method lower) {
if (!lower.getName().equals(upper.getName())) {
return false;
}
Class<?>[] lowerParameterTypes = lower.getParameterTypes();
Class<?>[] upperParameterTypes = upper.getParameterTypes();
if (lowerParameterTypes.length != upperParameterTypes.length) {
return false;
}
for (int i = 0; i < lowerParameterTypes.length; i++) {
if (!lowerParameterTypes[i].equals(upperParameterTypes[i])) {
return false;
}
}
return true;
}
private static void makeAccessible(AccessibleObject object) {
if (!object.isAccessible()) {
object.setAccessible(true);
}
}
private static void handleException(Throwable ex) {
if (ex instanceof InvocationTargetException) {
handleException(((InvocationTargetException) ex).getTargetException());
}
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("No such method or constructor", ex);
}
if (ex instanceof NoSuchFieldException) {
throw new IllegalStateException("No such field", ex);
}
if (ex instanceof InstantiationException) {
throw new IllegalStateException("Instantiation failed", ex);
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Failed to access method or constructor", ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
throw new IllegalStateException("Unhandled exception", ex);
}
}
|
package ch.uzh.ddis.katts.bolts.join;
import java.util.ArrayList;
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 ch.uzh.ddis.katts.query.processor.join.JoinConditionConfiguration;
import ch.uzh.ddis.katts.query.processor.join.SameValueJoinConditionConfiguration;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
/**
* This condition joins the variable bindings of each stream if they share the same value on a given field.
*
* @author fischer
*
*/
public class SameValueJoinCondition implements JoinCondition {
/**
* This empty set will be returned by the join method if the new binding could not be joined the the ones already in
* the cache.
*/
private static final ImmutableSet<SimpleVariableBindings> emptySet = ImmutableSet.of();
/**
* This set contains the identifiers of all streams this condition works on.
*/
private Set<String> streamIds;
/** The name of the field, this condition joins on. */
private String joinField;
/**
* This map contains a multimap for each stream this condition works on. Each multimap contains all the bindings
* that share the same value on the field with name joinField.
*/
private Map<String, HashMultimap<String, SimpleVariableBindings>> joinCache;
@Override
public void prepare(JoinConditionConfiguration configuration, Set<String> streamIds) {
SameValueJoinConditionConfiguration castConfiguration;
if (!(configuration instanceof SameValueJoinConditionConfiguration)) {
throw new IllegalStateException("An object of type " + configuration.getClass()
+ " cannot be used to configure an object of type " + this.getClass());
}
castConfiguration = (SameValueJoinConditionConfiguration) configuration;
if (castConfiguration.getJoinField() == null) {
throw new IllegalArgumentException("Missing join field 'joinOn' in configuration: " + configuration);
}
this.joinField = castConfiguration.getJoinField();
this.joinCache = new HashMap<String, HashMultimap<String, SimpleVariableBindings>>();
this.streamIds = streamIds;
for (String streamId : this.streamIds) { // create a join map per stream
HashMultimap<String, SimpleVariableBindings> mapForStream = HashMultimap.create();
this.joinCache.put(streamId, mapForStream);
}
}
@Override
public Set<SimpleVariableBindings> join(SimpleVariableBindings newBindings, String fromStreamId) {
Set<SimpleVariableBindings> result = emptySet;
Object fieldValue = newBindings.get(this.joinField.toString());
if (fieldValue != null) {
List<Set<SimpleVariableBindings>> setsToJoin;
// put the bindings object into the join cache
this.joinCache.get(fromStreamId).put(fieldValue.toString(), newBindings);
// create the list of streamIds we have to check for matching values
setsToJoin = new ArrayList<Set<SimpleVariableBindings>>();
for (String streamId : this.streamIds) {
if (!streamId.equals(fromStreamId)) { // we only test all other caches
HashMultimap<String, SimpleVariableBindings> bindingsForValues = this.joinCache.get(streamId);
if (!bindingsForValues.containsKey(fieldValue)) {
// we don't have to check any other cache and can safely abort here.
break;
}
setsToJoin.add(bindingsForValues.get(fieldValue.toString()));
}
}
if (setsToJoin.size() > 0) {
result = new HashSet<SimpleVariableBindings>();
for (SimpleVariableBindings bindings : createCartesianBindings(setsToJoin)) {
result.add(merge(newBindings, bindings));
}
}
}
/*
* only if we found a match in all streams (except the one the new bindings was received on), we return the
* resulting set of new bindings.
*/
return result;
}
/**
* Merges b1 and b2.
*
* @param b1
* the first bindings object to join.
* @param b2
* the second bindings object to join
* @return a new variable bindings object containing the contents of both.
*/
private SimpleVariableBindings merge(SimpleVariableBindings b1, SimpleVariableBindings b2) {
SimpleVariableBindings mergedBindings = new SimpleVariableBindings();
mergedBindings.putAll(b1);
/*
* For now, we hard code the handling of startDate and endDate conflicts here. For the future, we could think of
* creating a conflict management facility.
*/
for (String key : b2.keySet()) {
if (mergedBindings.containsKey(key)) {
if (!mergedBindings.get(key).equals(b2.get(key))) {
Object existingValue = mergedBindings.get(key);
Object conflictingValue = b2.get(key);
Object newValue = existingValue;
if (key.equals("startDate")) {
Date d1 = (Date) existingValue;
Date d2 = (Date) conflictingValue;
newValue = new Date(Math.min(d1.getTime(), d2.getTime()));
} else if (key.equals("endDate")) {
Date d1 = (Date) existingValue;
Date d2 = (Date) conflictingValue;
newValue = new Date(Math.max(d1.getTime(), d2.getTime()));
} else {
throw new IllegalStateException(String.format("Conflicting values for key '%1s' "
+ "when trying to merge variable bindings %2s into %s3.", key, b2.toString(),
mergedBindings.toString()));
}
mergedBindings.put(key, newValue);
} else {
mergedBindings.put(key, b2.get(key));
}
}
}
return mergedBindings;
}
/**
* Recursively merges the list of sets variable bindings so that the result is the cartesian product of all sets.
*
* @param setsToJoin
* @return a set containing the joined results
*/
private List<SimpleVariableBindings> createCartesianBindings(List<Set<SimpleVariableBindings>> setsToJoin) {
List<SimpleVariableBindings> result;
if (setsToJoin.size() == 1) {
result = new ArrayList<SimpleVariableBindings>(setsToJoin.get(0));
} else {
result = new ArrayList<SimpleVariableBindings>();
for (SimpleVariableBindings outer : setsToJoin.get(0)) {
for (SimpleVariableBindings inner : createCartesianBindings(setsToJoin.subList(1, setsToJoin.size()))) {
result.add(merge(outer, inner));
}
}
}
return result;
}
@Override
public void removeBindingsFromCache(SimpleVariableBindings bindings, String streamId) {
this.joinCache.get(streamId).remove(bindings.get(this.joinField), bindings);
}
@Override
public void removeBindingsFromCache(SimpleVariableBindings bindings) {
for (String streamId : this.streamIds) { // create a join map per stream
removeBindingsFromCache(bindings, streamId);
}
}
}
|
package com.shmenkins.core.handler.builder;
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.shmenkins.core.handler.BasicHandler;
import com.shmenkins.core.infra.binarystorage.BinaryStorage;
import com.shmenkins.core.infra.notification.BuildScheduledEvent;
import net.lingala.zip4j.core.ZipFile;
public class Builder implements BasicHandler<BuildScheduledEvent, Void> {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final BinaryStorage binStorage;
public Builder(BinaryStorage binStorage) {
this.binStorage = binStorage;
log.info("Instantiated");
}
@Override
public Void handle(BuildScheduledEvent buildScheduledEvent) {
log.debug("Building; buildScheduledEvent={}", buildScheduledEvent);
try {
// download source code zip
String zipUrl = buildScheduledEvent.repoChangeEvent.repoUrl + "/archive/"
+ buildScheduledEvent.repoChangeEvent.headCommit + ".zip";
File zipFile = new File("/tmp/" + buildScheduledEvent.repoChangeEvent.headCommit + ".zip");
log.debug("Downloading source code; url={}", zipUrl);
FileUtils.copyURLToFile(new URL(zipUrl), zipFile);
log.debug("Downloaded source code; url={}", zipUrl);
// extract
String destDir = "/tmp";
log.debug("Extracting source code; file={}", zipFile);
new ZipFile(zipFile).extractAll(destDir);
FileUtils.deleteQuietly(zipFile);
// download build tool
log.debug("Getting maven source code; file={}", zipFile);
File mavenZip = binStorage.getFile("apache-maven-3.3.9-bin.zip", "/tmp/apache-maven-3.3.9-bin.zip");
log.debug("extracting maven source code; file={}", mavenZip);
FileUtils.deleteQuietly(mavenZip);
// extract
new ZipFile(mavenZip).extractAll("/tmp");
// build
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
return null;
}
}
|
package com.quemb.qmbform.brower;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;
import com.bumptech.glide.Glide;
import com.quemb.qmbform.R;
import com.quemb.qmbform.pojo.ProcessedFile;
import java.util.ArrayList;
import me.relex.circleindicator.CircleIndicator;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
public class PhotoBrowserActivity extends AppCompatActivity {
public final static String PHOTOS = "PhotoBrowserFragment.PHOTOS";
public final static String SELECTED_ITEM = "PhotoBrowserFragment.SELECTED_ITEM";
public final static String PREVIEW_MODE = "PhotoBrowserActivity.PREVIEW_MODE";
ViewPager viewpager;
CircleIndicator indicator;
Toolbar toolbar;
SamplePagerAdapter samplePagerAdapter;
TextView titleTextView;
ArrayList<ProcessedFile> photos = new ArrayList<>();
int currentItem;
int photoCount;
boolean previewModel;
VideoView videoView;
protected LinearLayout footerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
previewModel = getIntent().getBooleanExtra(PREVIEW_MODE, false);
if (previewModel) {
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN, android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setContentView(R.layout.qm_activity_photo_preview);
setupViews();
}
@Override
protected void onResume() {
super.onResume();
if (photos != null && photos.size() > 0 && viewpager.getCurrentItem() < photos.size()) {
ProcessedFile processedFile = photos.get(viewpager.getCurrentItem());
if (processedFile.isVideo() && videoView != null) {
videoView.start();
videoView.resume();
videoView.requestFocus();
}
}
}
protected void setupViews() {
photos = (ArrayList<ProcessedFile>) getIntent().getSerializableExtra(PHOTOS);
photoCount = photos.size();
viewpager = (ViewPager) findViewById(R.id.viewpager);
indicator = (CircleIndicator) findViewById(R.id.indicator);
toolbar = (Toolbar) findViewById(R.id.toolbar);
titleTextView = (TextView) findViewById(R.id.titleTextView);
footerLayout = (LinearLayout) findViewById(R.id.footerLayout);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if (previewModel) {
toolbar.setVisibility(View.GONE);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
viewpager.setAdapter(samplePagerAdapter = new SamplePagerAdapter(photos));
indicator.setViewPager(viewpager);
viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
setTitle(position + 1 + "/" + photos.size());
ProcessedFile processedFile = photos.get(position);
if (processedFile.isVideo()) {
if (videoView != null) {
videoView.start();
videoView.resume();
videoView.requestFocus();
videoView.setVisibility(View.VISIBLE);
}
} else {
if (videoView != null) {
videoView.pause();
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
currentItem = getIntent().getIntExtra(SELECTED_ITEM, 0);
if (currentItem > 0) {
viewpager.setCurrentItem(currentItem);
} else {
setTitle(1 + "/" + photos.size());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_photo_browser, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else if (item.getItemId() == R.id.delete) {
confirmDialog(viewpager.getCurrentItem());
}
return true;
}
private void confirmDialog(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("?")
.setPositiveButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
photos.remove(position);
if (photos.size() == 0) {
finish();
} else {
samplePagerAdapter.notifyDataSetChanged();
setTitle(viewpager.getCurrentItem() + 1 + "/" + photos.size());
}
}
})
.setNegativeButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
@Override
public void finish() {
if (photoCount != photos.size()) {
Intent intent = new Intent();
intent.putExtra(PHOTOS, photos);
setResult(RESULT_OK, intent);
}
super.finish();
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
titleTextView.setText(title);
}
protected void pageItemClick() {
if (previewModel) {
super.finish();
return;
}
if (toolbar.getVisibility() == View.GONE) {
toolbar.setVisibility(View.VISIBLE);
} else {
toolbar.setVisibility(View.GONE);
}
}
class SamplePagerAdapter extends PagerAdapter {
ArrayList<ProcessedFile> photos = new ArrayList<>();
public SamplePagerAdapter(ArrayList<ProcessedFile> photos) {
super();
this.photos = photos;
}
@Override
public int getCount() {
return photos.size();
}
@Override
public View instantiateItem(ViewGroup container, final int position) {
final ProcessedFile processedFile = photos.get(position);
if (processedFile.isVideo()) {
View v = LayoutInflater.from(PhotoBrowserActivity.this).inflate(R.layout.qm_video_item, null);
videoView = (VideoView) v.findViewById(R.id.videoView);
videoView.setVideoURI(Uri.parse(processedFile.getPath()));
final ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
final ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.progressBar);
Glide.with(PhotoBrowserActivity.this).load(processedFile.getThumbPath()).into(imageView);
v.findViewById(R.id.playButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pageItemClick();
}
});
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
imageView.animate().alpha(0).setDuration(500).start();
progressBar.setVisibility(View.GONE);
}
});
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (currentItem == position) {
videoView.setVideoURI(Uri.parse(processedFile.getPath()));
videoView.start();
videoView.requestFocus();
}
}
});
if (currentItem == position) {
videoView.start();
videoView.resume();
videoView.requestFocus();
videoView.postDelayed(new Runnable() {
@Override
public void run() {
videoView.setVisibility(View.VISIBLE);
}
}, 500);
}
container.addView(v, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return v;
}
FrameLayout frameLayout = new FrameLayout(PhotoBrowserActivity.this);
ImageView thumbImageView = new ImageView(PhotoBrowserActivity.this);
thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
frameLayout.addView(thumbImageView, getResources().getDimensionPixelSize(R.dimen.browser_thumb_size), getResources().getDimensionPixelSize(R.dimen.browser_thumb_size));
FrameLayout.LayoutParams thumbImageViewLP = (FrameLayout.LayoutParams) thumbImageView.getLayoutParams();
thumbImageViewLP.gravity = Gravity.CENTER;
if (photos.get(position).getThumbPath() != null && !photos.get(position).getThumbPath().isEmpty()) {
Glide.with(PhotoBrowserActivity.this).load(photos.get(position).getThumbPath()).into(thumbImageView);
}
ProgressBar progressBar = new ProgressBar(PhotoBrowserActivity.this);
frameLayout.addView(progressBar, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) progressBar.getLayoutParams();
lp.gravity = Gravity.CENTER;
PhotoView photoView = new PhotoView(container.getContext());
// Now just add PhotoView to ViewPager and return it
frameLayout.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
Glide.with(PhotoBrowserActivity.this).load(photos.get(position).getPath()).into(photoView);
photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View view, float x, float y) {
pageItemClick();
}
@Override
public void onOutsidePhotoTap() {
pageItemClick();
}
});
container.addView(frameLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return frameLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
|
package com.kaneki.xchatmessageview.base;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.kaneki.xchatmessageview.listener.OnLoadMoreListener;
import java.util.List;
/**
* @author yueqian
* @Desctription
* @date 2017/1/16
* @email yueqian@mogujie.com
*/
public class XChatMessageView<T> extends ViewGroup {
private static final String DEFAULT_BACKGROUND_COLOR = "#f5f5f5";
private Context context;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private XMessageAdapter messageAdpter;
private OnLoadMoreListener onLoadMoreListener;
private boolean isLoadMore = false;
private int lastPosition = 0;
private int lastOffset = 0;
public XChatMessageView(Context context) {
this(context, null);
}
public XChatMessageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public XChatMessageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
initView();
initListener();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int measureWidth = measureWidth(widthMeasureSpec);
int measureHeight = measureHeight(heightMeasureSpec);
// ViewGroup
measureChildren(widthMeasureSpec, heightMeasureSpec);
// MyViewGroup
setMeasuredDimension(measureWidth, measureHeight);
}
private int measureWidth(int pWidthMeasureSpec) {
int result = 0;
int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);
int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);
switch (widthMode) {
/**
* modeMeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY,
* MeasureSpec.AT_MOST
*
*
* MeasureSpec.EXACTLY
* layout_widthlayout_heightandorid
* :layout_width="50dip"FILL_PARENT
*
*
* MeasureSpec.AT_MOST
* layout_widthlayout_heightWRAP_CONTENT
*
* modeAT_MOSTsize
*
*
* MeasureSpec.UNSPECIFIEDAdapterView
* measure
*/
case MeasureSpec.AT_MOST:
case MeasureSpec.UNSPECIFIED:
case MeasureSpec.EXACTLY:
result = widthSize;
break;
}
return result;
}
private int measureHeight(int pHeightMeasureSpec) {
int result = 0;
int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);
switch (heightMode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.UNSPECIFIED:
case MeasureSpec.EXACTLY:
result = heightSize;
break;
}
return result;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int mTotalHeight = 0;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
// onMeasure
int measureHeight = childView.getMeasuredHeight();
int measuredWidth = childView.getMeasuredWidth();
childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight
+ measureHeight);
mTotalHeight += measureHeight;
}
}
private void initView() {
recyclerView = new RecyclerView(context);
recyclerView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT));
recyclerView.setBackgroundColor(Color.parseColor(DEFAULT_BACKGROUND_COLOR));
linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
addView(recyclerView);
}
private void initListener() {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (messageAdpter.isNeedLoadMore())
saveCurrent();
}
});
}
private void saveCurrent() {
int pos = linearLayoutManager.findFirstVisibleItemPosition();
if (pos == 0 && !isLoadMore) {
//headerView
View headerView = linearLayoutManager.getChildAt(0);
//view
View firstView = linearLayoutManager.getChildAt(1);
if (headerView != null && firstView != null) {
//view
lastOffset = firstView.getTop() + headerView.getHeight();
//View
lastPosition = linearLayoutManager.getPosition(headerView);
isLoadMore = true;
onLoadMoreListener.onLoadMore();
}
} else {
//headerView
View currentView = linearLayoutManager.getChildAt(pos);
if (currentView != null) {
//view
lastOffset = currentView.getTop();
//View
lastPosition = linearLayoutManager.getPosition(currentView);
}
}
}
private void resumeSave(int changeSize) {
linearLayoutManager.scrollToPositionWithOffset(lastPosition + changeSize, lastOffset);
}
/**
* set message adapter, the adpter should extend XMessageAdapter.
* @param messageAdapter
*/
public void setMessageAdapter(XMessageAdapter messageAdapter) {
this.messageAdpter = messageAdapter;
recyclerView.setAdapter(messageAdapter);
recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1);
}
/**
* set message load more listener, it calls when the header is visibile and only
* calls once when trigger.
* @param onLoadMoreListener
*/
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
/**
* get message adpater, it may return null if setMessageAdapter method whit null set.
* @return
*/
public XMessageAdapter getMessageAdpter() {
return messageAdpter;
}
/**
* toggle the load more header, it should be call before the datas change.
* @param isNeedLoadMore
*/
public void setIsNeedLoadMore(boolean isNeedLoadMore) {
messageAdpter.setNeedLoadMore(isNeedLoadMore);
}
/**
* return the view's position on the XChatMessageView, the view should come from the XViewHolder.
* @param view
* @return
*/
public int getMessageItemPosition(View view) {
return linearLayoutManager == null ? -1 : linearLayoutManager.getPosition(view);
}
/**
* add a new message at the last of the XChatMessageView, the message should as same as the T of the
* XViewHolder or XMessageAdapter.
* @param t
*/
@SuppressWarnings("unchecked")
public void addMessageAtLast(T t) {
messageAdpter.addMessageAtLast(t);
recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1);
}
/**
* add messages at the last of the XChatMessageView, the message should as same as the T of the
* XViewHolder or XMessageAdapter.
* @param tList
*/
@SuppressWarnings("unchecked")
public void addMoreMessageAtLast(List<T> tList) {
messageAdpter.addMoreMessageAtLast(tList);
recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1);
}
/**
* add messages at the first of the XChatMessageView, the message should as same as the T of the
* XViewHolder or XMessageAdapter.
* @param tList
*/
@SuppressWarnings("unchecked")
public void addMoreMessageAtFirst(List<T> tList) {
messageAdpter.addMoreMessageAtFirst(tList);
if (!messageAdpter.isNeedLoadMore())
resumeSave(tList.size());
isLoadMore = false;
}
/**
* remove the message on the XChatMessageView, the view should come from the XViewHolder callback.
* @param view
*/
public void reomveMessage(View view) {
int pos = linearLayoutManager.getPosition(view);
messageAdpter.removeMessageAtPosition(pos);
}
/**
* scroll to the bottom of the XChatMessageView
*/
public void scrollToBottom() {
recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1);
}
public void saveCurrentStatus() {
saveCurrent();
}
public void resumeSaveStatus() {
resumeSave(0);
}
}
|
package lucee.runtime.interpreter.ref.literal;
import lucee.runtime.PageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.interpreter.ref.Ref;
import lucee.runtime.interpreter.ref.util.RefUtil;
import lucee.runtime.op.Caster;
/**
* Literal Number
*/
public final class LNumber implements Literal {
public static final LNumber ZERO = new LNumber(new Double(0));
public static final LNumber ONE = new LNumber(new Double(1));
private Object literal;
/**
* constructor of the class
* @param literal
*/
public LNumber(Double literal) {
this.literal=literal;
}
/**
* constructor of the class
* @param literal
* @throws PageException
*/
public LNumber(String literal) throws PageException {
this.literal=Caster.toDouble(literal);
// in theory this filter (>10) makes not really sense, just better for performance!!!
if(literal.length()>10) {
if(!Caster.toString(this.literal).equals(literal))
this.literal=literal;
}
}
@Override
public Object getValue(PageContext pc) {
return literal;
}
@Override
public Object getCollection(PageContext pc) {
return getValue(pc);
}
@Override
public String getTypeName() {
return "number";
}
@Override
public Object touchValue(PageContext pc) {
return getValue(pc);
}
@Override
public String getString(PageContext pc) {
return toString();
}
@Override
public String toString() {
return literal instanceof String?(String)literal:Caster.toString((Double)literal);
}
@Override
public boolean eeq(PageContext pc,Ref other) throws PageException {
if(other instanceof LNumber){
if(literal instanceof Double) {
// Double|Double
if(((LNumber)other).literal instanceof Double) {
return ((Double)literal).doubleValue()==((Double)((LNumber)other).literal).doubleValue();
}
// Double|String
return Caster.toString(((Double)literal).doubleValue()).equals(((LNumber)other).literal);
}
// String|Double
if(((LNumber)other).literal instanceof Double) {
return ((String)literal).equals(Caster.toString(((Double)((LNumber)other).literal).doubleValue()));
}
// String|String
return ((String)literal).equals((((LNumber)other).literal));
}
return RefUtil.eeq(pc,this,other);
}
}
|
package org.motechproject.mockil.service;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.motechproject.commons.date.model.Time;
import org.motechproject.commons.date.util.JodaFormatter;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.EventRelay;
import org.motechproject.event.listener.annotations.MotechListener;
import org.motechproject.ivr.service.OutboundCallService;
import org.motechproject.messagecampaign.EventKeys;
import org.motechproject.messagecampaign.contract.CampaignRequest;
import org.motechproject.messagecampaign.domain.campaign.CampaignType;
import org.motechproject.messagecampaign.service.CampaignEnrollmentRecord;
import org.motechproject.messagecampaign.service.CampaignEnrollmentsQuery;
import org.motechproject.messagecampaign.service.MessageCampaignService;
import org.motechproject.messagecampaign.userspecified.CampaignMessageRecord;
import org.motechproject.messagecampaign.userspecified.CampaignRecord;
import org.motechproject.mockil.database.Recipient;
import org.motechproject.mockil.database.RecipientDataService;
import org.motechproject.scheduler.service.MotechSchedulerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
@Service("mockilService")
public class MockilServiceImpl implements MockilService {
private final static long MILLIS_PER_SECOND = 1000;
private static final String DATE_TIME_REGEX = "([0-9][0-9][0-9][0-9])([^0-9])([0-9][0-9])([^0-9])([0-9][0-9])" +
"([^0-9])([0-9][0-9])([^0-9])([0-9][0-9])";
private static final String DURATION_REGEX = "([0-9]*)([a-zA-Z]*)";
private static final String TEST_EVENT = "org.motechproject.mockil.test";
private String campaignNameRegex;
private String externalIdRegex;
private Logger logger = LoggerFactory.getLogger(MockilServiceImpl.class);
private MessageCampaignService messageCampaignService;
private EventRelay eventRelay;
private MotechSchedulerService schedulerService;
private OutboundCallService outboundCallService;
private RecipientDataService recipientDataService;
private String hostName;
private List<String> campaignList;
private List<String> absoluteCampaigns;
private List<String> externalIdList;
private List<String> phoneNumberList; //indexed the same way externalIdList is
private Random rand;
private boolean expecting = false;
private int expected = 0;
private int stillExpecting = 0;
private long expectingStart = 0;
private boolean dontCall = false;
@Autowired
public MockilServiceImpl(EventRelay eventRelay, MessageCampaignService messageCampaignService,
OutboundCallService outboundCallService, RecipientDataService recipientDataService,
MotechSchedulerService schedulerService) {
this.eventRelay = eventRelay;
this.messageCampaignService = messageCampaignService;
this.outboundCallService = outboundCallService;
this.recipientDataService = recipientDataService;
this.schedulerService = schedulerService;
setupData();
}
private String campaignName(int id) {
return String.format("%s-C%d", hostName, id);
}
private String externalId(int id) {
return String.format("%s-E%d", hostName, id);
}
private void setupData() {
Integer maxCampaignId = 0;
Integer maxExternalId = 0;
campaignList = new ArrayList<>();
absoluteCampaigns = new ArrayList<>();
externalIdList = new ArrayList<>();
phoneNumberList = new ArrayList<>();
rand = new Random();
try {
InetAddress ip = InetAddress.getLocalHost();
hostName = ip.getHostName();
} catch (UnknownHostException e) {
throw new RuntimeException("Could not get instance host name: " + e.toString(), e);
}
campaignNameRegex = String.format("(%s-C)([0-9]*)", hostName);
externalIdRegex = String.format("(%s-E)([0-9]*)", hostName);
List<CampaignRecord> campaigns = messageCampaignService.getAllCampaignRecords();
for (CampaignRecord campaign : campaigns) {
String campaignName = campaign.getName();
if (campaignName.matches(campaignNameRegex)) {
logger.info("Reading campaign {}", campaign.getName());
Integer i = Integer.parseInt(campaignName.replaceAll(campaignNameRegex, "$2"));
campaignList.add(i, campaignName(i));
if (campaign.getCampaignType() == CampaignType.ABSOLUTE) {
absoluteCampaigns.add(campaign.getName());
}
if (i > maxCampaignId) {
maxCampaignId = i;
}
List<CampaignEnrollmentRecord> enrollments = messageCampaignService.search(
new CampaignEnrollmentsQuery().withCampaignName(campaignName));
for (CampaignEnrollmentRecord enrollment : enrollments) {
String externalId = enrollment.getExternalId();
Recipient recipient = recipientDataService.findByExternalId(externalId);
Integer j = Integer.parseInt(externalId.replaceAll(externalIdRegex, "$2"));
externalIdList.add(j, externalId(j));
phoneNumberList.add(j, recipient.getPhoneNumber());
if (j > maxExternalId) {
maxExternalId = j;
}
if (j % 100 == 0) {
logger.info("Reading enrollment {}", externalId);
}
}
}
}
logger.info("Read {} campaigns & {} enrollments from the database", campaignList.size(), externalIdList.size());
}
private String randomPhoneNumber() {
return String.format("%03d %03d %04d", rand.nextInt(1000), rand.nextInt(1000), rand.nextInt(10000));
}
private synchronized int createRecipient() {
int id = externalIdList.size();
externalIdList.add(id, externalId(id));
phoneNumberList.add(id, randomPhoneNumber());
return id;
}
private synchronized int createCampaign() {
int id = campaignList.size();
campaignList.add(id, campaignName(id));
return id;
}
@MotechListener(subjects = { EventKeys.SEND_MESSAGE })
public void handleFiredCampaignMessage(MotechEvent event) {
String externalId = (String)event.getParameters().get("ExternalID");
logger.debug("handleFiredCampaignMessage({})", event.toString());
call(externalId);
meetExpectation();
}
@MotechListener(subjects = { TEST_EVENT })
public void handleTestEvent(MotechEvent event) {
logger.debug("handleTestEvent()");
meetExpectation();
}
public String sendCampaignEvent() {
logger.debug("sendCampaignEvent()");
Map<String, Object> eventParams = new HashMap<>();
String externalId = externalIdList.get(rand.nextInt(externalIdList.size()));
eventParams.put("ExternalID", externalId);
MotechEvent event = new MotechEvent(EventKeys.SEND_MESSAGE, eventParams);
eventRelay.sendEventMessage(event);
return externalId;
}
public String sendTestEvent() {
logger.debug("sendTestEvent()");
Map<String, Object> eventParams = new HashMap<>();
MotechEvent event = new MotechEvent(TEST_EVENT, eventParams);
eventRelay.sendEventMessage(event);
return "OK";
}
private String call(String externalId) {
logger.debug("call({})", externalId);
if (dontCall) {
return externalId;
}
Recipient recipient = recipientDataService.findByExternalId(externalId);
logger.debug("The phone number for recipient with externalID {} is {}", externalId, recipient.getPhoneNumber());
Map<String, String> params = new HashMap<>();
params.put("ExternalID", externalId);
params.put("to", recipient.getPhoneNumber().replaceAll("[^0-9]", ""));
outboundCallService.initiateCall("config", params);
return externalId;
}
public String makeOutboundCall() {
logger.debug("makeOutboundCall()");
String externalId = externalIdList.get(rand.nextInt(externalIdList.size()));
call(externalId);
meetExpectation();
return externalId;
}
private LocalDate extractDate(String datetime) {
String date = datetime.replaceAll(DATE_TIME_REGEX, "$1-$3-$5");
return new LocalDate(date);
}
private String extractTime(String datetime) {
String time = datetime.replaceAll(DATE_TIME_REGEX, "$7:$9");
return time;
}
private String fixPeriod(String delay) {
String s = delay.replaceAll("[^a-zA-Z0-9]", " ");
s = s.replaceAll("([0-9]*)([a-z]*)", "$1 $2");
return s;
}
public String createAbsolute(String dateOrPeriod) {
LocalDate date;
String time;
if (dateOrPeriod.matches(DATE_TIME_REGEX)) {
date = extractDate(dateOrPeriod);
time = extractTime(dateOrPeriod);
} else if (dateOrPeriod.matches(DURATION_REGEX)) {
Period period = new JodaFormatter().parsePeriod(fixPeriod(dateOrPeriod));
DateTime now = DateTime.now().plus(period.toPeriod());
date = now.toLocalDate();
time = String.format("%02d:%02d", now.getHourOfDay(), now.getMinuteOfHour());
} else {
throw new IllegalStateException(String.format("%s seems to be neither a datetime or a duration.",
dateOrPeriod));
}
CampaignRecord campaign = new CampaignRecord();
int id = createCampaign();
String campaignName = campaignList.get(id);
campaign.setName(campaignName);
campaign.setCampaignType(CampaignType.ABSOLUTE);
CampaignMessageRecord message = new CampaignMessageRecord();
message.setName("firstMessage");
message.setDate(date);
message.setStartTime(time);
campaign.setMessages(Arrays.asList(message));
messageCampaignService.saveCampaign(campaign);
logger.info(String.format("Absolute campaign %s: %s %s", campaignName, date.toString(), time));
absoluteCampaigns.add(campaignName);
return campaignName;
}
public String createOffset(String period) {
String fixedupPeriod = fixPeriod(period);
CampaignRecord campaign = new CampaignRecord();
int id = createCampaign();
String campaignName = campaignList.get(id);
campaign.setName(campaignName);
campaign.setCampaignType(CampaignType.OFFSET);
CampaignMessageRecord message = new CampaignMessageRecord();
message.setName("firstMessage");
message.setStartTime("00:00");
message.setTimeOffset(fixedupPeriod);
campaign.setMessages(Arrays.asList(message));
messageCampaignService.saveCampaign(campaign);
logger.info("Offset campaign: {}: {}", campaignName, fixedupPeriod);
return campaignName;
}
public String delete(String campaignName) {
logger.debug("delete({})", campaignName);
messageCampaignService.deleteCampaign(campaignName);
return campaignName;
}
public String enroll(String campaignName) {
Time now = null;
LocalDate today = LocalDate.now();
if (!absoluteCampaigns.contains(campaignName)) {
now = new Time(DateTime.now().getHourOfDay(), DateTime.now().getMinuteOfHour());
}
int id = createRecipient();
String externalId = externalIdList.get(id);
String phoneNumber = phoneNumberList.get(id);
recipientDataService.create(new Recipient(externalId, phoneNumber));
CampaignRequest campaignRequest = new CampaignRequest(externalId, campaignName, today, now);
messageCampaignService.enroll(campaignRequest);
logger.debug("{}: {}", externalId, phoneNumber);
if (id % 1000 == 0) {
logger.info("Enroll id {}", id);
}
return externalId;
}
private synchronized void meetExpectation() {
if (expecting) {
if (stillExpecting == expected) {
// we've met the first expectation, start timer
logger.info("First of {} expected calls, starting timer.", expected);
expectingStart = System.currentTimeMillis();
}
stillExpecting
if (stillExpecting == 0) {
long millis = System.currentTimeMillis() - expectingStart;
float rate = (float) expected * MILLIS_PER_SECOND / millis;
logger.info("Measured {} calls at {} calls/second", expected, rate);
expecting = false;
expected = 0;
}
}
}
public String expect(int number) {
expecting = true;
stillExpecting += number;
expected += number;
String info = String.format("Expectations set to %d calls", expected);
if (expected > number) {
info += String.format(", expecting %d in total", stillExpecting);
}
logger.info(info);
return String.format("%d", expected);
}
public String resetExpectations() {
expecting = false;
stillExpecting = 0;
expected = 0;
logger.info("Reset expectations");
return "OK";
}
public String doCall() {
dontCall = false;
return "will call";
}
public String dontCall() {
dontCall = true;
return "won't call";
}
public String resetAll() {
schedulerService.safeUnscheduleAllJobs("org.motechproject.messagecampaign");
List<CampaignRecord> campaigns = messageCampaignService.getAllCampaignRecords();
for (CampaignRecord campaign : campaigns) {
String campaignName = campaign.getName();
messageCampaignService.deleteCampaign(campaignName);
logger.debug("Deleted {}", campaignName);
}
campaignList = new ArrayList<>();
absoluteCampaigns = new ArrayList<>();
externalIdList = new ArrayList<>();
phoneNumberList = new ArrayList<>();
resetExpectations();
return "OK";
}
}
|
package org.jboss.as.modcluster;
import org.apache.catalina.connector.Connector;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ServiceVerificationHandler;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.network.SocketBinding;
import org.jboss.as.network.SocketBindingManager;
import org.jboss.as.web.WebServer;
import org.jboss.as.web.WebSubsystemServices;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.modcluster.config.impl.ModClusterConfig;
import org.jboss.modcluster.load.LoadBalanceFactorProvider;
import org.jboss.modcluster.load.impl.DynamicLoadBalanceFactorProvider;
import org.jboss.modcluster.load.impl.SimpleLoadBalanceFactorProvider;
import org.jboss.modcluster.load.metric.LoadMetric;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.jboss.as.modcluster.LoadMetricDefinition.CAPACITY;
import static org.jboss.as.modcluster.LoadMetricDefinition.TYPE;
import static org.jboss.as.modcluster.LoadMetricDefinition.WEIGHT;
import static org.jboss.as.modcluster.ModClusterConfigResourceDefinition.*;
import static org.jboss.as.modcluster.ModClusterExtension.SSL_CONFIGURATION_PATH;
import static org.jboss.as.modcluster.ModClusterLogger.ROOT_LOGGER;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.CA_CERTIFICATE_FILE;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.CA_REVOCATION_URL;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.CERTIFICATE_KEY_FILE;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.CIPHER_SUITE;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.KEY_ALIAS;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.PASSWORD;
import static org.jboss.as.modcluster.ModClusterSSLResourceDefinition.PROTOCOL;
/**
* The managed subsystem add update.
*
* @author Jean-Frederic Clere
* @author Tomaz Cerar
*/
class ModClusterSubsystemAdd extends AbstractAddStepHandler {
static final ModClusterSubsystemAdd INSTANCE = new ModClusterSubsystemAdd();
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model,
ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers) throws OperationFailedException {
final ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));
final ModelNode modelConfig = fullModel.get(ModClusterExtension.CONFIGURATION_PATH.getKeyValuePair());
final ModClusterConfig config = getModClusterConfig(context, modelConfig);
final LoadBalanceFactorProvider loadProvider = getModClusterLoadProvider(context, modelConfig);
final String connector = CONNECTOR.resolveModelAttribute(context, modelConfig).asString();
// Add mod_cluster service
final ModClusterService service = new ModClusterService(config, loadProvider);
final ServiceBuilder<ModCluster> serviceBuilder = context.getServiceTarget().addService(ModClusterService.NAME, service)
.addDependency(WebSubsystemServices.JBOSS_WEB, WebServer.class, service.getWebServer())
.addDependency(SocketBindingManager.SOCKET_BINDING_MANAGER, SocketBindingManager.class, service.getBindingManager())
.addDependency(WebSubsystemServices.JBOSS_WEB_CONNECTOR.append(connector), Connector.class, service.getConnectorInjector())
.addListener(verificationHandler)
.setInitialMode(Mode.ACTIVE)
;
final ModelNode bindingRefNode = ADVERTISE_SOCKET.resolveModelAttribute(context, modelConfig);
final String bindingRef = bindingRefNode.isDefined() ? bindingRefNode.asString() : null;
if (bindingRef != null) {
serviceBuilder.addDependency(SocketBinding.JBOSS_BINDING_NAME.append(bindingRef), SocketBinding.class, service.getBinding());
}
newControllers.add(serviceBuilder.install());
}
/*
this is here so legacy configuration can be supported
*/
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(CommonAttributes.MOD_CLUSTER_CONFIG)) {
PathAddress opAddress = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));
PathAddress parent = opAddress.append(ModClusterExtension.CONFIGURATION_PATH);
ModelNode targetOperation = Util.createAddOperation(parent);
for (AttributeDefinition def : ModClusterConfigResourceDefinition.ATTRIBUTES) {
def.validateAndSet(operation, targetOperation);
}
context.addStep(targetOperation, ModClusterConfigAdd.INSTANCE, OperationContext.Stage.IMMEDIATE);
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
}
private ModClusterConfig getModClusterConfig(final OperationContext context, ModelNode model) throws OperationFailedException {
ModClusterConfig config = new ModClusterConfig();
config.setAdvertise(ADVERTISE.resolveModelAttribute(context, model).asBoolean());
if (model.get(SSL_CONFIGURATION_PATH.getKeyValuePair()).isDefined()) {
// Add SSL configuration.
config.setSsl(true);
final ModelNode ssl = model.get(SSL_CONFIGURATION_PATH.getKeyValuePair());
ModelNode keyAlias = KEY_ALIAS.resolveModelAttribute(context, ssl);
ModelNode password = PASSWORD.resolveModelAttribute(context, ssl);
if (keyAlias.isDefined()) {
config.setSslKeyAlias(keyAlias.asString());
}
if (password.isDefined()) {
config.setSslTrustStorePassword(password.asString());
config.setSslKeyStorePassword(password.asString());
}
if (ssl.hasDefined(CommonAttributes.CERTIFICATE_KEY_FILE)) {
config.setSslKeyStore(CERTIFICATE_KEY_FILE.resolveModelAttribute(context, ssl).asString());
}
if (ssl.hasDefined(CommonAttributes.CIPHER_SUITE)) {
config.setSslCiphers(CIPHER_SUITE.resolveModelAttribute(context, ssl).asString());
}
if (ssl.hasDefined(CommonAttributes.PROTOCOL)) {
config.setSslProtocol(PROTOCOL.resolveModelAttribute(context, ssl).asString());
}
if (ssl.hasDefined(CommonAttributes.CA_CERTIFICATE_FILE)) {
config.setSslTrustStore(CA_CERTIFICATE_FILE.resolveModelAttribute(context, ssl).asString());
}
if (ssl.hasDefined(CommonAttributes.CA_REVOCATION_URL)) {
config.setSslCrlFile(CA_REVOCATION_URL.resolveModelAttribute(context, ssl).asString());
}
}
if (model.hasDefined(CommonAttributes.PROXY_LIST)) {
config.setProxyList(PROXY_LIST.resolveModelAttribute(context, model).asString());
}
if (model.hasDefined(CommonAttributes.ADVERTISE_SECURITY_KEY)) {
config.setAdvertiseSecurityKey(ADVERTISE_SECURITY_KEY.resolveModelAttribute(context, model).asString());
}
config.setProxyURL(PROXY_URL.resolveModelAttribute(context, model).asString());
config.setExcludedContexts(EXCLUDED_CONTEXTS.resolveModelAttribute(context, model).asString().trim());
config.setAutoEnableContexts(AUTO_ENABLE_CONTEXTS.resolveModelAttribute(context, model).asBoolean());
config.setStopContextTimeout(STOP_CONTEXT_TIMEOUT.resolveModelAttribute(context, model).asInt());
config.setStopContextTimeoutUnit(TimeUnit.valueOf(STOP_CONTEXT_TIMEOUT.getMeasurementUnit().getName()));
//config.setStopContextTimeoutUnit(TimeUnit.SECONDS); //todo use AttributeDefinition.getMeasurementUnit
// the default value is 20000 = 20 seconds.
config.setSocketTimeout(SOCKET_TIMEOUT.resolveModelAttribute(context, model).asInt() * 1000);
config.setStickySession(STICKY_SESSION.resolveModelAttribute(context, model).asBoolean());
config.setStickySessionRemove(STICKY_SESSION_REMOVE.resolveModelAttribute(context, model).asBoolean());
config.setStickySessionForce(STICKY_SESSION_FORCE.resolveModelAttribute(context, model).asBoolean());
config.setWorkerTimeout(WORKER_TIMEOUT.resolveModelAttribute(context, model).asInt());
config.setMaxAttempts(MAX_ATTEMPTS.resolveModelAttribute(context, model).asInt());
config.setFlushPackets(FLUSH_PACKETS.resolveModelAttribute(context, model).asBoolean());
config.setFlushWait(FLUSH_WAIT.resolveModelAttribute(context, model).asInt());
config.setPing(PING.resolveModelAttribute(context, model).asInt());
config.setSmax(SMAX.resolveModelAttribute(context, model).asInt());
config.setTtl(TTL.resolveModelAttribute(context, model).asInt());
config.setNodeTimeout(NODE_TIMEOUT.resolveModelAttribute(context, model).asInt());
if (model.hasDefined(CommonAttributes.BALANCER)) {
config.setBalancer(BALANCER.resolveModelAttribute(context, model).asString());
}
if (model.hasDefined(CommonAttributes.LOAD_BALANCING_GROUP)) {
config.setLoadBalancingGroup(LOAD_BALANCING_GROUP.resolveModelAttribute(context, model).asString());
}
return config;
}
private LoadBalanceFactorProvider getModClusterLoadProvider(final OperationContext context, ModelNode model) throws OperationFailedException {
LoadBalanceFactorProvider load = null;
if (model.hasDefined(CommonAttributes.SIMPLE_LOAD_PROVIDER_FACTOR)) {
// TODO it seems we don't support that stuff.
int value = ModClusterConfigResourceDefinition.SIMPLE_LOAD_PROVIDER.resolveModelAttribute(context, model).asInt(1);
SimpleLoadBalanceFactorProvider myload = new SimpleLoadBalanceFactorProvider();
myload.setLoadBalanceFactor(value);
load = myload;
}
Set<LoadMetric> metrics = new HashSet<LoadMetric>();
if (model.get(ModClusterExtension.DYNAMIC_LOAD_PROVIDER.getKeyValuePair()).isDefined()) {
final ModelNode node = model.get(ModClusterExtension.DYNAMIC_LOAD_PROVIDER.getKeyValuePair());
int decayFactor = DynamicLoadProviderDefinition.DECAY.resolveModelAttribute(context, model).asInt();
int history = DynamicLoadProviderDefinition.HISTORY.resolveModelAttribute(context, model).asInt();
if (node.hasDefined(CommonAttributes.LOAD_METRIC)) {
addLoadMetrics(metrics, node.get(CommonAttributes.LOAD_METRIC), context);
}
if (node.hasDefined(CommonAttributes.CUSTOM_LOAD_METRIC)) {
addLoadMetrics(metrics, node.get(CommonAttributes.CUSTOM_LOAD_METRIC), context);
}
if (!metrics.isEmpty()) {
DynamicLoadBalanceFactorProvider loader = new DynamicLoadBalanceFactorProvider(metrics);
loader.setDecayFactor(decayFactor);
loader.setHistory(history);
load = loader;
}
}
if (load == null) {
// Use a default one...
ROOT_LOGGER.useDefaultLoadBalancer();
SimpleLoadBalanceFactorProvider myload = new SimpleLoadBalanceFactorProvider();
myload.setLoadBalanceFactor(1);
load = myload;
}
return load;
}
private void addLoadMetrics(Set<LoadMetric> metrics, ModelNode nodes, final OperationContext context) throws OperationFailedException {
for (Property p : nodes.asPropertyList()) {
ModelNode node = p.getValue();
double capacity = CAPACITY.resolveModelAttribute(context, node).asDouble();
int weight = WEIGHT.resolveModelAttribute(context, node).asInt();
Class<? extends LoadMetric> loadMetricClass = null;
if (node.hasDefined(CommonAttributes.TYPE)) {
String type = TYPE.resolveModelAttribute(context, node).asString();
LoadMetricEnum metric = LoadMetricEnum.forType(type);
loadMetricClass = (metric != null) ? metric.getLoadMetricClass() : null;
} else {
String className = CustomLoadMetricDefinition.CLASS.resolveModelAttribute(context, node).asString();
try {
loadMetricClass = this.getClass().getClassLoader().loadClass(className).asSubclass(LoadMetric.class);
} catch (ClassNotFoundException e) {
ROOT_LOGGER.errorAddingMetrics(e);
}
}
if (loadMetricClass != null) {
try {
LoadMetric metric = loadMetricClass.newInstance();
metric.setCapacity(capacity);
metric.setWeight(weight);
metrics.add(metric);
} catch (InstantiationException e) {
ROOT_LOGGER.errorAddingMetrics(e);
} catch (IllegalAccessException e) {
ROOT_LOGGER.errorAddingMetrics(e);
}
}
}
}
}
|
package org.apache.geronimo.deployment;
public interface MockEndpoint {
String doSomething(String name);
}
|
package com.haulmont.cuba.desktop.sys;
import com.haulmont.cuba.desktop.sys.vcl.ToolTipButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Class that encapsulates displaying of tooltips for all components.
*
* @author devyatkin
* @version $Id$
*/
public class DesktopToolTipManager extends MouseAdapter {
public static final int F1_CODE = 112;
private static int CLOSE_TIME = 500;
private static int SHOW_TIME = 1000;
private boolean tooltipShowing = false;
private JToolTip toolTipWindow;
private Popup window;
private JComponent component;
private Timer showTimer = new Timer(SHOW_TIME, null);
private Timer closeTimer;
private MouseListener componentMouseListener = new ComponentMouseListener();
private KeyListener fieldKeyListener = new FieldKeyListener();
private ActionListener btnActionListener = new ButtonClickListener();
private static DesktopToolTipManager instance;
/**
* Return singleton instance of DesktopToolTipManager for application.
*
* @return instance of DesktopToolTipManager
*/
public static DesktopToolTipManager getInstance() {
if (instance == null) {
instance = new DesktopToolTipManager();
}
return instance;
}
private DesktopToolTipManager() {
closeTimer = new Timer(CLOSE_TIME, null);
closeTimer.setRepeats(false);
closeTimer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
window.hide();
tooltipShowing = false;
toolTipWindow.removeMouseListener(DesktopToolTipManager.this);
component.removeMouseListener(DesktopToolTipManager.this);
}
});
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
private MouseEvent event;
@Override
public void eventDispatched(AWTEvent e) {
if (!tooltipShowing) {
return;
}
event = (MouseEvent) e;
if (event.getID() == MouseEvent.MOUSE_PRESSED) {
if (event.getComponent() != null && event.getComponent().isShowing()) {
if (!isPointInComponent(event.getLocationOnScreen(), toolTipWindow))
hideTooltip();
} else
hideTooltip();
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
private boolean isPointInComponent(Point point, JComponent component) {
if (!component.isShowing())
return false;
Point componentLocation = component.getLocationOnScreen();
Rectangle bounds = component.getBounds();
return (((point.x >= componentLocation.x) && (point.x <= componentLocation.x + bounds.width)) &&
(point.y >= componentLocation.y) && (point.y <= componentLocation.y + bounds.height));
}
/**
* Register tooltip for component.
* Tooltip is displayed when user press F1 on focused component
* ToolTip text is taken from {@link javax.swing.JComponent#getToolTipText()}.
*
* @param component component to register
*/
public void registerTooltip(final JComponent component) {
component.removeKeyListener(fieldKeyListener);
component.addKeyListener(fieldKeyListener);
}
/**
* Register tooltip for {@link javax.swing.AbstractButton}.
* Tooltip is displayed when the user hovers over a button
* ToolTip text is taken from {@link javax.swing.JComponent#getToolTipText()}.
*
* @param btn Button to register
*/
public void registerTooltip(final AbstractButton btn) {
btn.removeMouseListener(componentMouseListener);
btn.addMouseListener(componentMouseListener);
}
/**
* Register tooltip for ToolTipButton.
* Tooltip is displayed when the user presses the button
* ToolTip text is taken from {@link javax.swing.JComponent#getToolTipText()} .
*
* @param btn Button to register
*/
public void registerTooltip(final ToolTipButton btn) {
btn.removeActionListener(btnActionListener);
btn.addActionListener(btnActionListener);
}
private void hideTooltip() {
closeTimer.stop();
if (window != null) {
window.hide();
tooltipShowing = false;
toolTipWindow.removeMouseListener(DesktopToolTipManager.this);
component.removeMouseListener(DesktopToolTipManager.this);
}
}
private void showTooltip(JComponent field, String text) {
if (!field.isShowing())
return;
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
Point location = new Point();
GraphicsConfiguration gc;
gc = field.getGraphicsConfiguration();
Rectangle sBounds = gc.getBounds();
Insets screenInsets = Toolkit.getDefaultToolkit()
.getScreenInsets(gc);
sBounds.x += screenInsets.left;
sBounds.y += screenInsets.top;
sBounds.width -= (screenInsets.left + screenInsets.right);
sBounds.height -= (screenInsets.top + screenInsets.bottom);
location.x = mouseLocation.x + 15;
location.y = mouseLocation.y + 15;
int x = location.x;
int y = location.y;
if (toolTipWindow != null) {
hideTooltip();
}
component = field;
final JToolTip toolTip = new JToolTip();
toolTip.setTipText("<html>" + text + "</html>");
final Popup tooltipContainer = PopupFactory.getSharedInstance().getPopup(field, toolTip, x, y);
tooltipContainer.show();
window = tooltipContainer;
toolTipWindow = toolTip;
tooltipShowing = true;
if ((!(field instanceof ToolTipButton)) && (field instanceof AbstractButton)) {
toolTip.addMouseListener(this);
field.addMouseListener(this);
}
}
@Override
public void mouseExited(MouseEvent e) {
closeTimer.start();
}
@Override
public void mouseEntered(MouseEvent e) {
if (closeTimer.isRunning()) {
closeTimer.stop();
}
}
private class ComponentMouseListener extends MouseAdapter {
private AbstractButton btn;
{
showTimer.setRepeats(false);
showTimer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!tooltipShowing)
showTooltip(btn, btn.getToolTipText());
}
});
}
@Override
public void mouseEntered(MouseEvent e) {
if (window != null) {
if (e.getSource() != component && e.getSource() != toolTipWindow && component instanceof AbstractButton) {
hideTooltip();
btn = (AbstractButton) e.getSource();
showTimer.start();
return;
}
}
if (!tooltipShowing) {
btn = (AbstractButton) e.getSource();
showTimer.start();
}
}
@Override
public void mouseExited(MouseEvent e) {
if (!tooltipShowing) {
if (showTimer.isRunning()) {
showTimer.stop();
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
showTimer.stop();
hideTooltip();
}
}
private class FieldKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == F1_CODE) {
hideTooltip();
JComponent field = (JComponent) e.getSource();
showTooltip(field, field.getToolTipText());
} else {
if (tooltipShowing) {
hideTooltip();
}
}
}
}
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (component == e.getSource() && tooltipShowing) {
return;
}
if (tooltipShowing) {
hideTooltip();
}
showTooltip((JComponent) e.getSource(), ((JButton) e.getSource()).getToolTipText());
}
}
}
|
package org.interonet.ldm.VMM;
import com.jcraft.jsch.JSchException;
public interface initBV {
String createBridge() throws JSchException;
String createVLAN() throws JSchException;
String addBridgeToVlan() throws JSchException;
}
|
import java.util.Random;
public final class BooleanUtils {
private static final Random RANDOM = new Random();
private BooleanUtils() {
}
public static boolean maybe() {
return RANDOM.nextBoolean();
}
}
|
package com.kotcrab.vis.editor;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.kotcrab.vis.editor.event.Event;
import com.kotcrab.vis.editor.event.EventListener;
import com.kotcrab.vis.editor.event.ProjectStatusEvent;
import com.kotcrab.vis.editor.event.ProjectStatusEvent.Status;
import com.kotcrab.vis.editor.event.StatusBarEvent;
import com.kotcrab.vis.editor.module.ColorPickerModule;
import com.kotcrab.vis.editor.module.EditorModuleContainer;
import com.kotcrab.vis.editor.module.EditorSettingsIOModule;
import com.kotcrab.vis.editor.module.GeneralSettingsModule;
import com.kotcrab.vis.editor.module.MenuBarModule;
import com.kotcrab.vis.editor.module.ProjectIOModule;
import com.kotcrab.vis.editor.module.StatusBarModule;
import com.kotcrab.vis.editor.module.TabsModule;
import com.kotcrab.vis.editor.module.ToolbarModule;
import com.kotcrab.vis.editor.module.project.AssetsManagerUIModule;
import com.kotcrab.vis.editor.module.project.AssetsWatcherModule;
import com.kotcrab.vis.editor.module.project.ExportModule;
import com.kotcrab.vis.editor.module.project.FileAccessModule;
import com.kotcrab.vis.editor.module.project.Project;
import com.kotcrab.vis.editor.module.project.ProjectInfoTabModule;
import com.kotcrab.vis.editor.module.project.ProjectModuleContainer;
import com.kotcrab.vis.editor.module.project.SceneIOModule;
import com.kotcrab.vis.editor.module.project.SceneMetadataModule;
import com.kotcrab.vis.editor.module.project.SceneTabsModule;
import com.kotcrab.vis.editor.module.project.TextureCacheModule;
import com.kotcrab.vis.editor.module.scene.EditorScene;
import com.kotcrab.vis.editor.module.scene.GridRendererModule.GridSettingsModule;
import com.kotcrab.vis.editor.module.scene.InputModule;
import com.kotcrab.vis.editor.ui.EditorFrame;
import com.kotcrab.vis.editor.ui.SettingsDialog;
import com.kotcrab.vis.editor.ui.tab.Tab;
import com.kotcrab.vis.editor.ui.tab.TabViewMode;
import com.kotcrab.vis.editor.util.EditorException;
import com.kotcrab.vis.editor.util.Log;
import com.kotcrab.vis.ui.OptionDialogAdapter;
import com.kotcrab.vis.ui.VisTable;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.util.DialogUtils;
import com.kotcrab.vis.ui.util.DialogUtils.OptionDialogType;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisSplitPane;
import com.kotcrab.vis.ui.widget.file.FileChooser;
public class Editor extends ApplicationAdapter implements EventListener {
public static Editor instance;
private EditorFrame frame;
private Stage stage;
private Table root;
// TODO move to module
private Table mainContentTable;
private Table tabContentTable;
private VisTable projectContentTable;
private VisSplitPane splitPane;
private SettingsDialog settingsDialog;
private EditorModuleContainer editorMC;
private ProjectModuleContainer projectMC;
private InputModule inputModule;
private GeneralSettingsModule settings;
private boolean projectLoaded = false;
private Tab tab;
public Editor (EditorFrame frame) {
this.frame = frame;
}
@Override
public void create () {
instance = this;
Assets.load();
VisUI.load();
VisUI.setDefaultTitleAlign(Align.center);
FileChooser.setFavoritesPrefsName("com.kotcrab.vis.editor");
App.eventBus.register(this);
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
root = new Table();
root.setFillParent(true);
stage.addActor(root);
createUI();
createModuleContainers();
createModulesUI();
// debug section
try {
editorMC.get(ProjectIOModule.class).load((Gdx.files.absolute("F:\\Poligon\\Tester")));
} catch (EditorException e) {
Log.exception(e);
}
FileHandle scene = Gdx.files.absolute("F:\\Poligon\\Tester\\vis\\assets\\scene\\test.scene");
if (scene.exists()) {
EditorScene testScene = projectMC.get(SceneIOModule.class).load(scene);
projectMC.get(SceneTabsModule.class).open(testScene);
}
//showSettingsWindow();
//debug end
Log.info("Loading completed");
}
private void createUI () {
mainContentTable = new Table();
tabContentTable = new Table();
projectContentTable = new VisTable(true);
splitPane = new VisSplitPane(null, null, true);
splitPane.setSplitAmount(0.78f);
projectContentTable.add(new VisLabel("Project Content Manager has not been loaded yet"));
settingsDialog = new SettingsDialog();
}
private void createModuleContainers () {
editorMC = new EditorModuleContainer();
projectMC = new ProjectModuleContainer(editorMC);
editorMC.add(new ProjectIOModule());
editorMC.add(inputModule = new InputModule(mainContentTable));
editorMC.add(new MenuBarModule(projectMC));
editorMC.add(new ToolbarModule());
editorMC.add(new TabsModule());
editorMC.add(new StatusBarModule());
editorMC.add(new EditorSettingsIOModule());
editorMC.add(new ColorPickerModule());
editorMC.add(settings = new GeneralSettingsModule());
editorMC.add(new GridSettingsModule());
editorMC.init();
settingsDialog.addAll(editorMC.getModules());
}
private void createModulesUI () {
root.add(editorMC.get(MenuBarModule.class).getTable()).fillX().expandX().row();
root.add(editorMC.get(ToolbarModule.class).getTable()).fillX().expandX().row();
root.add(editorMC.get(TabsModule.class).getTable()).fillX().expandX().row();
root.add(mainContentTable).expand().fill().row();
root.add(editorMC.get(StatusBarModule.class).getTable()).fillX().expandX().row();
}
@Override
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
editorMC.resize();
projectMC.resize();
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
if (tab != null) tab.render(stage.getBatch());
stage.draw();
}
@Override
public void dispose () {
App.eventBus.stop();
editorMC.dispose();
if (projectLoaded) projectMC.dispose();
stage.dispose();
Assets.dispose();
VisUI.dispose();
frame.dispose();
Log.dispose();
}
public void requestExit () {
if (settings.isConfirmExit()) {
DialogUtils.OptionDialog dialog = DialogUtils.showOptionDialog(getStage(), "Confirm Exit", "Are you sure you want to exit VisEditor?", OptionDialogType.YES_CANCEL, new OptionDialogAdapter() {
@Override
public void yes () {
exit();
}
});
dialog.setYesButtonText("Exit");
} else
exit();
}
private void exit () {
Gdx.app.exit();
}
public Stage getStage () {
return stage;
}
@Override
public boolean onEvent (Event e) {
return false;
}
public void requestProjectUnload () {
projectLoaded = false;
projectMC.dispose();
settingsDialog.removeAll(projectMC.getModules());
App.eventBus.post(new StatusBarEvent("Project unloaded"));
App.eventBus.post(new ProjectStatusEvent(Status.Unloaded));
}
public void projectLoaded (final Project project) {
if (projectLoaded) {
DialogUtils.showOptionDialog(getStage(), "Warning", "Other project is already loaded, unload it and continue?", OptionDialogType.YES_CANCEL, new OptionDialogAdapter() {
@Override
public void yes () {
switchProject(project);
}
});
return;
}
projectLoaded = true;
projectMC.setProject(project);
projectMC.add(new FileAccessModule());
projectMC.add(new AssetsWatcherModule());
projectMC.add(new TextureCacheModule());
projectMC.add(new ExportModule());
projectMC.add(new SceneIOModule());
projectMC.add(new SceneMetadataModule());
projectMC.add(new SceneTabsModule());
projectMC.add(new ProjectInfoTabModule());
projectMC.add(new AssetsManagerUIModule());
projectMC.init();
settingsDialog.addAll(projectMC.getModules());
App.eventBus.post(new StatusBarEvent("Project loaded"));
App.eventBus.post(new ProjectStatusEvent(Status.Loaded));
}
private void switchProject (final Project project) {
requestProjectUnload();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
projectLoaded(project);
}
});
}
public void tabChanged (Tab tab) {
this.tab = tab;
tabContentTable.clear();
mainContentTable.clear();
splitPane.setWidgets(null, null);
if (tab != null) {
tabContentTable.add(tab.getContentTable()).expand().fill();
if (tab.getViewMode() == TabViewMode.TAB_ONLY)
mainContentTable.add(tabContentTable).expand().fill();
else {
splitPane.setWidgets(tabContentTable, projectContentTable);
mainContentTable.add(splitPane).expand().fill();
}
}
inputModule.reattachListeners();
}
public VisTable getProjectContentTable () {
return projectContentTable;
}
public void showSettingsWindow () {
stage.addActor(settingsDialog.fadeIn());
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class DownloadAll {
public static void main(String[] args) throws IOException {
int size = 50000;
int count = 0;
int nextFile = 0;
File file = new File(args[0]);
BufferedReader reader = new BufferedReader(new FileReader(file));
File out = new File(args[0] + "_" +String.valueOf(nextFile) + ".songs");
out.createNewFile();
FileWriter fw = new FileWriter(out.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String line;
while ((line = reader.readLine()) != null) {
try {
String prefix = "http:
String band = line.split("/")[3];
HashSet<String> links = new HashSet<String>();
Document doc = Jsoup.connect(line).get();
Elements elements = doc.getElementsByTag("li");
for (Element li : elements) {
Elements as = li.getElementsByTag("a");
for (Element a : as) {
String linkHref = a.attr("href");
if (linkHref.contains(band)) {
links.add(linkHref);
}
}
}
for (String link : links) {
bw.write(prefix + link + "\n");
count++;
}
if (count >= size){
nextFile++;
bw.close();
out = new File(args[0] + "_" +String.valueOf(nextFile) + ".songs");
out.createNewFile();
fw = new FileWriter(out.getAbsoluteFile());
bw = new BufferedWriter(fw);
count = 0;
}
} catch (Exception e) {
System.out.println("ERRO");
System.out.println(e.getMessage());
}
}
bw.close();
}
}
|
package org.akvo.flow.events;
import static com.gallatinsystems.common.util.MemCacheUtils.initCache;
import static org.akvo.flow.events.EventUtils.getEventAndActionType;
import static org.akvo.flow.events.EventUtils.newContext;
import static org.akvo.flow.events.EventUtils.newEntity;
import static org.akvo.flow.events.EventUtils.newEvent;
import static org.akvo.flow.events.EventUtils.newSource;
import static org.akvo.flow.events.EventUtils.populateEntityProperties;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jsr107cache.Cache;
import org.akvo.flow.events.EventUtils.Action;
import org.akvo.flow.events.EventUtils.EventTypes;
import org.akvo.flow.events.EventUtils.Key;
import org.akvo.flow.events.EventUtils.Prop;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.common.util.PropertyUtil;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.DeleteContext;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PostDelete;
import com.google.appengine.api.datastore.PostPut;
import com.google.appengine.api.datastore.PutContext;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.utils.SystemProperty;
public class EventLogger {
private static Logger logger = Logger.getLogger(EventLogger.class.getName());
private static final long MIN_TIME_DIFF = 60000; // 60 seconds
private void sendNotification() {
try {
String urlPath = PropertyUtil.getProperty(Prop.EVENT_NOTIFICATION);
if (urlPath == null || urlPath.trim().length() == 0) {
logger.log(Level.SEVERE, "Event notification URL not present in appengine-web.xml");
return;
}
URL url = new URL(urlPath.trim());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
Map<String, String> messageMap = new HashMap<String, String>();
String appId = SystemProperty.applicationId.get();
messageMap.put(Key.APP_ID, appId);
messageMap.put(Key.URL, appId + ".appspot.com");
ObjectMapper m = new ObjectMapper();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
m.writeValue(writer, messageMap);
writer.close();
if (connection.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT) {
logger.log(Level.SEVERE, "Unified log notification failed with status code: "
+ connection.getResponseCode());
}
} catch (MalformedURLException e) {
logger.log(Level.SEVERE,
"Unified log notification failed with malformed URL exception", e);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unified log notification failed with IO exception", e);
} catch (Exception e) {
logger.log(Level.SEVERE, "Unified log notification failed with error", e);
}
}
/*
* Notify the log that a new event is ready to be downloaded.
*/
private void notifyLog() {
Cache cache = initCache(60 * 60); // 1 hour
if (cache == null) {
// cache is not accessible, so we will notify anyway
logger.log(Level.WARNING,
"cache not accessible, but still sending notification to unified log");
sendNotification();
return;
}
if (cache.containsKey(Action.UNIFIED_LOG_NOTIFIED)) {
// check if the time the last notification was send is less than one minute ago
Date cacheDate = (Date) cache.get(Action.UNIFIED_LOG_NOTIFIED);
Date nowDate = new Date();
Long deltaMils = nowDate.getTime() - cacheDate.getTime();
if (deltaMils < MIN_TIME_DIFF) {
// it is too soon, so don't send the notification
return;
}
}
// if we are here, either the key is not in the cache, or it is too old
// in both cases, we send the notification and add a fresh value to the cache
sendNotification();
cache.put(Action.UNIFIED_LOG_NOTIFIED, new Date());
}
private void storeEvent(Map<String, Object> event, Date timestamp) {
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
ObjectMapper m = new ObjectMapper();
StringWriter w = new StringWriter();
m.writeValue(w, event);
Entity entity = new Entity("EventQueue");
entity.setProperty("createdDateTime", timestamp);
entity.setProperty("lastUpdateDateTime", timestamp);
String payload = w.toString();
if (payload.length() > Constants.MAX_LENGTH) {
entity.setProperty("payload", null);
entity.setProperty("payloadText", new Text(payload));
} else {
entity.setProperty("payload", w.toString());
entity.setProperty("payloadText", null);
}
datastore.put(entity);
notifyLog();
} catch (Exception e) {
logger.log(Level.SEVERE, "could not store " + event.get("eventType")
+ " event. Error: " + e.toString(), e);
}
}
@PostPut(kinds = {
"SurveyGroup", "Survey", "QuestionGroup", "Question", "SurveyInstance",
"QuestionAnswerStore", "SurveyedLocale", "DeviceFiles"
})
void logPut(PutContext context) {
try {
if (!"true".equals(PropertyUtil.getProperty(Prop.ENABLE_CHANGE_EVENTS))) {
return;
}
Entity current = context.getCurrentElement();
// determine type of event and type of action
EventTypes types = getEventAndActionType(current.getKey().getKind());
// determine if this entity was created or updated
Date lastUpdateDatetime = (Date) current.getProperty(Prop.LAST_UPDATE_DATE_TIME);
Date createdDateTime = (Date) current.getProperty(Prop.CREATED_DATE_TIME);
String actionType = createdDateTime.equals(lastUpdateDatetime) ? Action.CREATED
: Action.UPDATED;
// create event source
// get the authentication information. This seems to contain the userId, but
// according to the documentation, should hold the 'password'
final Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
Map<String, Object> eventSource = newSource(authentication.getPrincipal());
Date timestamp = (Date) context.getCurrentElement().getProperty(
Prop.LAST_UPDATE_DATE_TIME);
// create event context map
Map<String, Object> eventContext = newContext(timestamp, eventSource);
// create event entity
Map<String, Object> eventEntity = newEntity(types.type, context
.getCurrentElement().getKey().getId());
populateEntityProperties(types.type, context.getCurrentElement(), eventEntity);
// create event
Map<String, Object> event = newEvent(SystemProperty.applicationId.get(),
types.action + actionType, eventEntity, eventContext);
// store it
storeEvent(event, timestamp);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not handle datastore put event: " + e.getMessage(), e);
}
}
@PostDelete(kinds = {
"SurveyGroup", "Survey", "QuestionGroup", "Question", "SurveyInstance",
"QuestionAnswerStore", "SurveyedLocale", "DeviceFiles"
})
void logDelete(DeleteContext context) {
try {
if (!"true".equals(PropertyUtil.getProperty(Prop.ENABLE_CHANGE_EVENTS))) {
return;
}
// determine type of event and type of action
EventTypes types = getEventAndActionType(context.getCurrentElement().getKind());
// create event source
// get the authentication information. This seems to contain the userId, but
// according to the documentation, should hold the 'password'
final Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
Object principal = authentication.getPrincipal();
Map<String, Object> eventSource = newSource(principal);
// create event context map
// we create our own timestamp here, as we don't have one in the context
Date timestamp = new Date();
Map<String, Object> eventContext = newContext(timestamp, eventSource);
// create event entity
Map<String, Object> eventEntity = newEntity(types.type, context
.getCurrentElement().getId());
// create event
Map<String, Object> event = newEvent(SystemProperty.applicationId.get(),
types.action + Action.DELETED, eventEntity, eventContext);
// store it
storeEvent(event, timestamp);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not handle datastore delete event: " + e.getMessage(),
e);
}
}
}
|
package jasy.lang.ast;
import jasy.lang.ASMCompiler;
import jasy.lang.ASMCompiler.Region;
import jasy.lang.ClassResolver;
import jasy.lang.SingleClassLoader;
import jasy.runtime.asm.CommonClassTransformer;
import jasy.runtime.asm.CompositeTransformer;
import jasy.runtime.asm.IfAllTransformer;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.OptionalInt;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceClassVisitor;
public class MethodAST extends AbstractAST implements MemberAST {
public boolean isAdd;
public MethodSelectorAST selector;
public CodeAST body; // AST generator body
public ASMCompiler.MetaProcessing mp;
public MethodAST(Region region, boolean isAdd, MethodSelectorAST selector, CodeAST body, ASMCompiler.MetaProcessing mp) {
super(region);
this.isAdd = isAdd;
this.selector = selector;
this.body = body;
this.mp = mp;
}
@Override
public void accept(MemberVisitor visitor) {
visitor.visitMethod(this);
}
@Override
public void resolve(Scope thisClass, TypeAST expectedResultType, ClassResolver resolver, List<jasy.lang.ASMCompiler.Message> errorMessages) {
selector.resolve(thisClass, expectedResultType, resolver, errorMessages);
body.resolve(thisClass, expectedResultType, resolver, errorMessages);
}
public void populate(CompositeTransformer<Transformation<ClassNode>> classTransformer, IfAllTransformer<Transformation<MethodNode>> transformer) {
if(!isAdd) {
selector.populate(transformer);
} else {
java.lang.reflect.Method astGeneratorMethod = createASTGeneratorMethod();
classTransformer.addTransformer(c -> {
return () -> {
try {
// Invoke code generator code resulting into a CodeAST
Class<?> astGeneratorClass = astGeneratorMethod.getDeclaringClass();
Object astGenerator = astGeneratorClass.newInstance();
for(String fieldName: mp.metaScope.getFieldNames()) {
try {
Field f = astGeneratorClass.getField(fieldName);
Object value = c.getVariableValue(fieldName);
f.set(astGenerator, value);
} catch (NoSuchFieldException ex) {
Logger.getLogger(MethodAST.class.getName()).log(Level.SEVERE, null, ex);
}
}
CodeAST body = (CodeAST)astGeneratorMethod.invoke(astGenerator, new Object[0]);
// Use the resulting CodeAST in toCode below
int methodAccess = AST.Util.getAccessModifier(selector.accessModifier, selector.isStatic);
String methodName = selector.name;
Type[] argumentTypes = selector.parameters.stream()
.map(x -> Type.getType(x.type.getDescriptor(c.getTarget().name)))
.toArray(size -> new Type[size]);
String methodDescriptor = Type.getMethodDescriptor(
Type.getType(selector.returnType.getDescriptor(c.getTarget().name)),
argumentTypes);
MethodNode methodNode = new MethodNode(methodAccess, methodName, methodDescriptor, null, null);
GeneratorAdapter generatorAdapter = new GeneratorAdapter(methodNode, methodAccess, methodName, methodDescriptor);
MethodCodeGenerator generator = new MethodCodeGenerator(generatorAdapter, selector.returnType);
Hashtable<String, ParameterInfo> parameters = new Hashtable<>();
for(int i = 0; i < selector.parameters.size(); i++) {
Parameter p = selector.parameters.get(i);
parameters.put(p.name, new ParameterInfo(p.type, i + 1));
}
methodNode.visitCode();
generator.start();
toCode(c, body, generator, parameters, new InsnList() /*Something that generates a default values for non-void returns?*/);
generator.end();
methodNode.visitEnd();
OptionalInt existingMethodIndex =
IntStream.range(0, c.getTarget().methods.size())
.filter(i ->
((MethodNode)c.getTarget().methods.get(i)).name.equals(methodName) &&
((MethodNode)c.getTarget().methods.get(i)).desc.equals(methodDescriptor))
.findFirst();
if(existingMethodIndex.isPresent())
c.getTarget().methods.remove(existingMethodIndex.getAsInt());
c.getTarget().methods.add(methodNode);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(MethodAST.class.getName()).log(Level.SEVERE, null, ex);
}
};
});
}
}
private java.lang.reflect.Method createASTGeneratorMethod() {
// 1) Generate code to generate code
ClassNode metaObjectClassNode = new ClassNode(Opcodes.ASM5);
mp.metaScope.addFields(metaObjectClassNode);
Hashtable<String, ParameterInfo> metaParameters = new Hashtable<>();
Hashtable<String, TypeAST> metaVariables = new Hashtable<>();
PreparedAST pbody = toCode(mp.metaScope, body, metaParameters, metaVariables);
// ArrayList<TypeAST> returnTypes = new ArrayList<>();
// pbody.returns(returnTypes);
// Must return CodeAST
// TypeAST returnType = returnTypes.get(0);
Class<?> returnTypeClass = CodeAST.class;//((NameTypeAST)returnType).getType();
metaObjectClassNode.version = MetaExpressionAST.getOpcodesVersion();
metaObjectClassNode.access = Opcodes.ACC_PUBLIC;
metaObjectClassNode.name = "dejain/generator/ASMGenerator" + mp.generatorCount;
metaObjectClassNode.superName = "java/lang/Object";
MethodNode generatorMethod = new MethodNode(Opcodes.ACC_PUBLIC, "generator", Type.getMethodDescriptor(Type.getType(returnTypeClass)), null, new String[]{});
metaObjectClassNode.methods.add(generatorMethod);
MethodNode defaultConstructor = new MethodNode(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
defaultConstructor.visitCode();
defaultConstructor.visitVarInsn(Opcodes.ALOAD, 0);
defaultConstructor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
defaultConstructor.visitInsn(Opcodes.RETURN);
defaultConstructor.visitMaxs(1,1);
defaultConstructor.visitEnd();
metaObjectClassNode.methods.add(defaultConstructor);
GeneratorAdapter generatorAdapter = new GeneratorAdapter(generatorMethod, generatorMethod.access, generatorMethod.name, generatorMethod.desc);
MethodCodeGenerator metaCodeGenerator = new MethodCodeGenerator(generatorAdapter, null);
metaCodeGenerator.start();
pbody.generate(new Transformation<>(metaObjectClassNode), metaCodeGenerator, new InsnList());
metaCodeGenerator.end();
generatorMethod.visitEnd();
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
metaObjectClassNode.accept(cw);
TraceClassVisitor traceClassVisitor = new TraceClassVisitor(null, new Textifier(), new PrintWriter(System.out));
metaObjectClassNode.accept(traceClassVisitor);
CheckClassAdapter.verify(new ClassReader(cw.toByteArray()), true, new PrintWriter(System.out));
SingleClassLoader classLoader = new SingleClassLoader(metaObjectClassNode);
Class<?> metaObjectClass = classLoader.loadClass();
java.lang.reflect.Method bodyAsMethodTmp = null;
try {
bodyAsMethodTmp = metaObjectClass.getMethod("generator", new Class<?>[0]);
} catch (NoSuchMethodException | SecurityException ex) {
Logger.getLogger(MetaExpressionAST.class.getName()).log(Level.SEVERE, null, ex);
}
mp.generatorCount++;
return bodyAsMethodTmp;
}
public static void toCode(Transformation<ClassNode> c, CodeAST body, MethodCodeGenerator generator, Hashtable<String, ParameterInfo> parameters) {
toCode(c, body, generator, parameters, new InsnList());
}
private static void toCode(Transformation<ClassNode> c, CodeAST body, MethodCodeGenerator generator, Hashtable<String, ParameterInfo> parameters, InsnList originalIl) {
Hashtable<String, TypeAST> variables = new Hashtable<>();
PreparedAST pa = toCode(new ClassNodeScope(c.getTarget()), body, parameters, variables);
pa.generate(c, generator, originalIl);
}
public static PreparedAST toCode(Scope thisClass, CodeAST ctx, Hashtable<String, ParameterInfo> parameters, Hashtable<String, TypeAST> variables) {
return ctx.accept(new CodePreparer(thisClass, ctx, parameters, variables));
}
public static void appendStore(MethodCodeGenerator generator, int ordinal, TypeAST type) {
switch(type.getSimpleName()) {
case "int":
generator.methodNode.visitVarInsn(Opcodes.ISTORE, ordinal);
break;
default:
generator.methodNode.visitVarInsn(Opcodes.ASTORE, ordinal);
break;
}
}
public static PreparedExpressionAST toExpression(Scope thisClass, ExpressionAST expression, Hashtable<String, ParameterInfo> parameters, Hashtable<String, TypeAST> variables) {
return toExpression(thisClass, expression, parameters, variables, true);
}
public static PreparedExpressionAST toExpression(Scope thisClass, ExpressionAST expression, Hashtable<String, ParameterInfo> parameters, Hashtable<String, TypeAST> variables, boolean asExpression) {
return expression.accept(new ExpressionPreparer(thisClass, expression, parameters, variables, asExpression));
}
public static ExpressionAST quote(Scope thisClass, CodeAST ctx, Hashtable<String, TypeAST> variables) {
return ctx.accept(new CodeQuoter(thisClass, ctx, variables));
}
public static ExpressionAST quote(String str) {
return new StringLiteralAST(null, str);
}
public static ExpressionAST quote(TypeAST type) {
ExpressionAST classForName = new GetClassAST(null, type);
return new NewAST(null, new NameTypeAST(null, NameTypeAST.class), Arrays.asList(new NullAST(null), classForName));
}
@Override
public void populate(CommonClassTransformer transformer) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package drones.simulation;
import akka.actor.Cancellable;
import akka.japi.pf.ReceiveBuilder;
import akka.japi.pf.UnitPFBuilder;
import drones.messages.*;
import drones.models.*;
import drones.simulation.messages.SetConnectionLostMessage;
import drones.simulation.messages.SetCrashedMessage;
import play.libs.Akka;
import scala.concurrent.Promise;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
public class BepopSimulator extends DroneActor {
private static class StepSimulationMessage implements Serializable {
private FiniteDuration timeStep;
public StepSimulationMessage(FiniteDuration timeStep) {
this.timeStep = timeStep;
}
public FiniteDuration getTimeStep() { return timeStep; }
}
// Simulator properties
// TODO: make drones.simulation properties settable
protected byte batteryLowLevel = 10;
protected byte batteryCriticalLevel = 5;
protected Cancellable simulationTick;
protected FiniteDuration simulationTimeStep = Duration.create(1, TimeUnit.SECONDS);
protected double maxHeight;
protected double topSpeed; // assume m/s
protected double initialAngleWithRespectToEquator; // in radians, facing East is 0
// internal state
private boolean crashed = false;
private boolean connectionLost = false;
private boolean initialized = false;
private Location homeLocation;
private boolean flyingToHome;
// angleWrtEquator: in radians
public BepopSimulator(Location startLocation, double maxHeight, double angleWrtEquator, double topSpeed) {
// Set initial values
location.setValue(startLocation);
batteryPercentage.setValue((byte) 100);
rotation.setValue(new Rotation(0, 0, 0));
version.setValue(new DroneVersion("1.0", "1.0"));
gpsFix.setValue(false);
// Set simulation values
this.maxHeight = maxHeight;
this.topSpeed = topSpeed;
initialAngleWithRespectToEquator = angleWrtEquator; // facing north
// Disable messages before initialization
eventBus.setPublishDisabled(true);
// Setup drone
bootDrone();
}
// Utility methods
public void rebootDrone() {
shutDownDrone();
bootDrone();
}
public void bootDrone() {
// Set default values
state.setValue(FlyingState.LANDED);
alertState.setValue(AlertState.NONE);
speed.setValue(new Speed(0.0, 0.0, 0.0));
altitude.setValue(0.0);
navigationState.setValue(NavigationState.AVAILABLE);
navigationStateReason.setValue(NavigationStateReason.ENABLED);
gpsFix.setValue(true);
}
public void shutDownDrone() {
// Cancel everything: drone is powered off
simulationTick.cancel();
flyingToHome = false;
eventBus.setPublishDisabled(true);
setConnectionLost(true);
initialized = false;
}
private void returnToHome(NavigationStateReason reason) {
// Check if drone is not already flying home
if(!flyingToHome && !crashed) {
flyingToHome = true;
tellSelf(new TakeOffRequestMessage());
tellSelf(new NavigationStateChangedMessage(
NavigationState.PENDING,
reason
));
tellSelf(new FlyingStateChangedMessage(FlyingState.FLYING));
tellSelf(new NavigationStateChangedMessage(
NavigationState.IN_PROGRESS,
reason
));
tellSelf(new SpeedChangedMessage(10, 10, 10));
}
}
private void stepSimulation(FiniteDuration stepDuration) {
// Move
simulateMovement(stepDuration);
// Fly further
progressFlight(stepDuration);
// TODO: send update to eventbus of all properties that periodically update
}
private void progressFlight(FiniteDuration timeFlown) {
// Check if moveToLocation wasn't cancelled
// If flying is aborted, the states, reasons & other properties
// should be set in the caller that set this flag to false
if(flyingToHome) {
Location currentLocation = location.getRawValue();
// Calculate distance
double distance = Location.distance(currentLocation, homeLocation);
double timeTillArrival = distance/topSpeed;
double timeStep = timeFlown.toUnit(TimeUnit.SECONDS);
if (timeTillArrival > timeStep) {
// Not there yet
double deltaLongtitude = homeLocation.getLongtitude() - currentLocation.getLongtitude();
double deltaLatitude = homeLocation.getLatitude() - currentLocation.getLatitude();
double deltaAltitude = homeLocation.getHeigth() - currentLocation.getHeigth();
double fraction = timeStep/timeTillArrival;
double newLongtitude = currentLocation.getLongtitude() + deltaLongtitude * fraction;
double newLatitude = currentLocation.getLatitude() + deltaLatitude * fraction;
double newHeight = currentLocation.getHeigth() + deltaAltitude * fraction;
tellSelf(new LocationChangedMessage(
newLongtitude,
newLatitude,
newHeight));
} else {
// We have arrived
flyingToHome = false;
tellSelf(new LocationChangedMessage(
homeLocation.getLongtitude(),
homeLocation.getLatitude(),
homeLocation.getHeigth()
));
tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING));
tellSelf(new NavigationStateChangedMessage(
NavigationState.AVAILABLE,
NavigationStateReason.FINISHED
));
}
}
}
// Simulate movement based on speed
private void simulateMovement(FiniteDuration simulationTimeStep) {
if(!flyingToHome) {
// Figure out angle wrt North South Axis
double yawInRadians = rotation.getRawValue().getYaw() * Math.PI;
double angleWrtNSAxis = initialAngleWithRespectToEquator + yawInRadians;
// Decompose speed-x vector
double p1 = Math.sin(angleWrtNSAxis); // = cos(angle - PI/2) = cos(angleVyWrtNS)
double p2 = Math.cos(angleWrtNSAxis); // = -sin(angle - PI/2) = -sin(angleVyWrtNS);
// Calculate speed along earth axises
Speed movement = speed.getRawValue();
double vNS = movement.getVx() * p1;
double vEquator = movement.getVx() * p2;
vNS += -p2 * movement.getVx();
vEquator += p1 * movement.getVy();
// Calculate flown distance
double durationInSec = simulationTimeStep.toUnit(TimeUnit.SECONDS);
double dNS = vNS * durationInSec;
double dEquator = vEquator * durationInSec;
// Calculate delta in radians
double radius = Location.EARTH_RADIUS + location.getRawValue().getHeigth();
double deltaLatitude = dNS/radius * 180/Math.PI; // in degrees
double deltaLongitude = dEquator/radius * 180/Math.PI; // in degrees
// Calculate new coordinates
Location oldLocation = location.getRawValue();
double latitude = (oldLocation.getLatitude() + deltaLatitude); // in degrees
if (latitude > 90) latitude = 180 -latitude;
if (latitude < -90) latitude = Math.abs(latitude) -180;
double longitude = (oldLocation.getLongtitude() + deltaLongitude); // in degrees
if (longitude > 180) longitude -= 360;
if (longitude < -180) longitude += 360;
Location newLocation = new Location(latitude, longitude, oldLocation.getHeigth());
tellSelf(new LocationChangedMessage(longitude, latitude, newLocation.getHeigth()));
}
}
// Calculates speed corresponding with a give rotation
private Speed calculateSpeed(Rotation rotation, double vz) {
// Getting necessary info
double pitch = rotation.getPitch();
double roll = rotation.getRoll();
// Calculate speed components
double xFraction, yFraction;
if (roll != 0) {
// Calculate flying angle
double angle = Math.atan(pitch / roll);
xFraction = Math.sin(angle)*pitch;
yFraction = Math.cos(angle)*roll;
}
else {
// We know the flying angle
xFraction = 1*pitch;
yFraction = 0*roll;
}
double vx = xFraction * topSpeed;
double vy = yFraction * topSpeed;
return new Speed(vx, vy, vz);
}
protected void tellSelf(Object msg) {
self().tell(msg, self());
}
// External control
@Override
protected UnitPFBuilder<Object> createListeners() {
return ReceiveBuilder.
match(BatteryPercentageChangedMessage.class, m -> processBatteryLevel(m.getPercent())).
match(SetCrashedMessage.class, m -> setCrashed(m.isCrashed())).
match(SetConnectionLostMessage.class, m -> setConnectionLost(m.isConnectionLost())).
match(StepSimulationMessage.class, m -> stepSimulation(m.getTimeStep()));
}
protected void processBatteryLevel(byte percentage) {
if(percentage < batteryLowLevel) {
if (percentage == 0) {
// Drone shuts down
shutDownDrone();
}
else if (percentage < batteryCriticalLevel) {
tellSelf(new AlertStateChangedMessage(AlertState.BATTERY_CRITICAL));
// TODO: figure out what happens
/*
tellSelf(new LandRequestMessage());
tellSelf(new NavigationStateChangedMessage(
NavigationState.UNAVAILABLE,
NavigationStateReason.BATTERY_LOW));
*/
}
else {
// Return to home on low battery
tellSelf(new AlertStateChangedMessage(AlertState.BATTERY_LOW));
returnToHome(NavigationStateReason.BATTERY_LOW);
}
}
}
protected void setCrashed(boolean crashed) {
if (crashed) {
flyingToHome = false;
tellSelf(new AltitudeChangedMessage(0.0));
tellSelf(new SpeedChangedMessage(0, 0, 0));
tellSelf(new FlyingStateChangedMessage(FlyingState.EMERGENCY));
tellSelf(new AlertStateChangedMessage(AlertState.CUT_OUT));
tellSelf(new NavigationStateChangedMessage(
NavigationState.UNAVAILABLE,
NavigationStateReason.STOPPED
));
}
else {
rebootDrone();
}
this.crashed = crashed;
}
protected void setConnectionLost(boolean connectionLost) {
// Disable/re-enable event bus
eventBus.setPublishDisabled(connectionLost);
if(connectionLost) {
// Should start navigation to home
returnToHome(NavigationStateReason.CONNECTION_LOST);
tellSelf(new AlertStateChangedMessage(AlertState.CUT_OUT));
}
else {
tellSelf(new AlertStateChangedMessage(AlertState.NONE));
}
this.connectionLost = connectionLost;
}
// Implementation of DroneActor
private <T> boolean prematureExit(Promise<T> p) {
if(connectionLost) {
return true;
}
if(!initialized) {
p.failure(new DroneException("Failed to send command. Not initialized yet."));
return true;
}
if(crashed) {
p.failure(new DroneException("Drone crashed, unable to execute commands"));
return true;
}
return false;
}
@Override
protected void init(Promise<Void> p) {
if(connectionLost) {
return;
}
// Enable status updates
eventBus.setPublishDisabled(false);
// Schedule drones.simulation loop
simulationTick = Akka.system().scheduler().schedule(
simulationTimeStep,
simulationTimeStep,
self(),
new StepSimulationMessage(simulationTimeStep),
Akka.system().dispatcher(),
self());
initialized = true;
p.success(null);
}
@Override
protected void reset(Promise<Void> p) {
if(connectionLost) return;
rebootDrone();
init(p);
}
@Override
protected void emergency(Promise<Void> p) {
if (connectionLost) return;
// Land
p.failure(new NotImplementedException());
}
@Override
protected void takeOff(Promise<Void> p) {
if (prematureExit(p)) {
return;
}
switch (state.getRawValue()) {
case EMERGENCY:
p.failure(new DroneException("Drone is in emergency status"));
break;
case LANDING:
// Land drone before taking off again
tellSelf(new FlyingStateChangedMessage(FlyingState.LANDED));
// Fall-through
case LANDED:
tellSelf(new FlyingStateChangedMessage(FlyingState.TAKINGOFF));
tellSelf(new AltitudeChangedMessage(1.0));
tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING));
// Fall-through
default:
p.success(null);
}
}
@Override
protected void land(Promise<Void> p) {
if (prematureExit(p)) {
return;
}
flyingToHome = false;
switch (state.getRawValue()) {
case EMERGENCY:
p.failure(new DroneException("Drone is in emergency status"));
break;
case TAKINGOFF:
// Hover drone before landing again
tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING));
// Fall-through
case HOVERING:
tellSelf(new FlyingStateChangedMessage(FlyingState.LANDING));
// Fall-through
default:
tellSelf(new AltitudeChangedMessage(0.0));
tellSelf(new FlyingStateChangedMessage(FlyingState.LANDED));
p.success(null);
}
}
@Override
protected void move3d(Promise<Void> p, double vx, double vy, double vz, double vr) {
if (prematureExit(p)) {
return;
}
// Drone is flying to home
if (flyingToHome) {
p.failure(new DroneException("Drone is flying to home, first cancel move to location"));
}
// Check if arguments are valid
if (Math.abs(vx) > 1 || Math.abs(vy) > 1 || Math.abs(vz) > 1 || Math.abs(vr) > 1) {
p.failure(new DroneException("Invalid arguments: vx, vy, vz and vr need to be in [-1, 1]"));
}
// 1: update rotation
tellSelf(new AttitudeChangedMessage(vy, vx, vr));
// 2: calculate speed resulting from the rotation
Speed newSpeed = calculateSpeed(new Rotation(vy, vx, vr), vz);
// 3: update the speed
tellSelf(new SpeedChangedMessage(newSpeed.getVx(), newSpeed.getVy(), newSpeed.getVz()));
// After processing these messages, simulateMove will have the correct behaviour
p.failure(new NotImplementedException());
}
@Override
protected void moveToLocation(Promise<Void> p, double latitude, double longitude, double altitude) {
if (prematureExit(p)) {
return;
}
FlyingState flyingState = state.getRawValue();
if(flyingState == FlyingState.FLYING || flyingState == FlyingState.HOVERING) {
// Set new home location & fly towards it
double height = Math.min(altitude, maxHeight);
homeLocation = new Location(latitude, longitude, height);
returnToHome(NavigationStateReason.REQUESTED);
p.success(null);
} else {
p.failure(new DroneException("Drone is unable to move in current state: "
+ flyingState.name()));
}
}
@Override
protected void cancelMoveToLocation(Promise<Void> p) {
if (prematureExit(p)) {
return;
}
if(state.getRawValue() == FlyingState.EMERGENCY) {
p.failure(new DroneException("Unable to send commands to drone in emergency state"));
} else {
flyingToHome = false;
tellSelf(new SpeedChangedMessage(0, 0, 0));
tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING));
tellSelf(new NavigationStateChangedMessage(
NavigationState.AVAILABLE,
NavigationStateReason.STOPPED
));
p.success(null);
}
}
@Override
protected void setMaxHeight(Promise<Void> p, float meters) {
if (prematureExit(p)) {
return;
}
maxHeight = meters;
p.success(null);
}
@Override
protected void setMaxTilt(Promise<Void> p, float degrees) {
if (prematureExit(p)) {
return;
}
p.success(null);
}
@Override
protected void setOutdoor(Promise<Void> p, boolean outdoor) {
if (prematureExit(p)) {
return;
}
// no effect on drones.simulation
p.success(null);
}
@Override
protected void setHull(Promise<Void> p, boolean hull) {
if (prematureExit(p)) {
return;
}
// No effect on drones.simulation
p.success(null);
}
@Override
protected void flatTrim(Promise<Void> p) {
if (prematureExit(p)) {
return;
}
// TODO: find out what this should do
p.success(null);
}
}
|
package mainFiles;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.InputMismatchException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
/**
* @author Ian Davila
* @version 0.6.1
*
*/
public class MainClass extends JFrame
{
public String version = "0.6.1";
private static final long serialVersionUID = 89L;
protected final int MAX_X = 620;
protected final int MAX_Y = 400;
private final String newLine = "\n";
protected JPanel lowerPanel;//used to contain the buttons for the lower section
protected JTextField messageInput;
protected JButton sendInputButton;
protected JTextArea chatLog;
protected JScrollPane scrollypolly;
protected String lastUserInput;
protected boolean newInput = false;
//This is a special string that indicates that we do not have new input
protected String noInputString = "#$%NO%$#";//This is a weird sequence of characters so that way we know a user didnt type it
protected Color forgroundColor = new Color(255, 247, 74);
//past colors: 73, 228, 241, a shade of cyna
protected Font font = new Font("Verdana", Font.PLAIN, 12);//setting the font size and style
protected Color backgroundColor = Color.black;
protected ProcessCommands theCommands = new ProcessCommands(this);//this is needed
/*
* These are the strings that determine the names of certain components
* in the GUI
*/
protected String name_Button1 = "Enter";
protected String name_JPane_Title = "Graphical Console";
protected Thread commandThread = new Thread(theCommands);
/**
* This constructor will draw the console and run the initilizing functions.
* Then it will run the command thread
*/
public MainClass()
{
this.setSize(MAX_X, MAX_Y);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle(name_JPane_Title);
this.setVisible(true);
this.setBackground(backgroundColor);
//This is used when the user presses the enter key to grab input
//setting up the fields that will be used to declare the other JComponents
initComponents();
initComponentFunctions();
commandThread.start();
}
/**
* Init the different Jcomponents
*/
public void initComponents()
{
lowerPanel = new JPanel();
lowerPanel.setBackground(backgroundColor);
sendInputButton = new JButton(name_Button1);
Border empty = BorderFactory.createEmptyBorder();//This is used to create an empty border for the gui
messageInput = new JTextField(30);
messageInput.setBackground(Color.DARK_GRAY);
messageInput.setForeground(forgroundColor);
messageInput.setFont(font);
messageInput.setBorder(empty);
messageInput.setCaretColor(forgroundColor);
//This is the key listener so the component can listen for the enter key to send the commands
messageInput.addKeyListener(new KeyListener(){
//unused
@Override
public void keyPressed(KeyEvent arg0) {
}
//unused
@Override
public void keyReleased(KeyEvent arg0) {}
//This is the section for when the enter key is typed
@Override
public void keyTyped(KeyEvent k) {
//System.out.println("TYPED");
//Code was being weird so I used the get char method to detect the enter key
if(k.getKeyChar() == '\n')
{
lastUserInput = messageInput.getText(); //This stores the last user input to be used in other functions
//When another function wants to know what a user typed in it will look at the lastUserInput
newInput = true; //this is telling the computer that we have received new input and it can/should be read by other programs
String tempAddingCharacters = ">" + lastUserInput;
addToChatLog(tempAddingCharacters);
messageInput.setText("");
}
}
});
chatLog = new JTextArea(8, 20);
chatLog.setFont(font);
scrollypolly = new JScrollPane(chatLog);
chatLog.setEditable(false);
chatLog.setForeground(forgroundColor);
chatLog.setBackground(backgroundColor);
chatLog.setBorder(empty);
scrollypolly.setBorder(empty);
lowerPanel.setLayout(new GridLayout(2,0, 0, 5));//Contains the lowerPanelbuttons and the inputmessage
//setting colors
sendInputButton.setBackground(forgroundColor);
//adding panels
lowerPanel.add(messageInput);
//adding components to the second panel
lowerPanel.add(sendInputButton);
//adding components to the upper panel
this.add("South",lowerPanel);
this.add("Center", scrollypolly);
validate();//Need this for things to show up
}
/**
* This is sets all of the functions for the different JComponents
*/
public void initComponentFunctions()
{
sendInputButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
lastUserInput = messageInput.getText(); //This stores the last user input to be used in other functions
//When another function wants to know what a user typed in it will look at the lastUserInput
newInput = true; //this is telling the computer that we have received new input and it can/should be read by other programs
String tempAddingCharacters = ">" + lastUserInput;
addToChatLog(tempAddingCharacters);
}
});
}
/**
* Checks to see if new input has been given
* @return a string once we have new input
*/
public String checkForInput()
{
if(newInput)//if there is new input
{
newInput = false;
return lastUserInput;
}
else
return "#$%NO%$#";//#$%NO%$# is used as a special string to indicate that we do not have new information
}
/**
* Adds somethings to the chat lof
* @param stuff Strings you want to add to the screen
*/
public void addToChatLog(String stuff)
{
chatLog.append(stuff + newLine);
chatLog.setCaretPosition(chatLog.getDocument().getLength());
}
/**
* Adds something to the chat log without adding a new line
* @param stuff Strings you want to add to the screen
*/
public void addToChatLogsl(String stuff)
{
chatLog.append(stuff);
chatLog.setCaretPosition(chatLog.getDocument().getLength());
}
/**
* This will pause the program until the user types in something new
* @return the input from the console once there is new input
*/
public String waitForInput()
{
String theInput = "%%%%ERROR%%%";//if this is somehow returned then there is a problem!!
while(true)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
theInput = this.checkForInput();
if(theInput.equalsIgnoreCase("
{
//if we havnt actually gotten new input then lets just get out
}
else
{
//otherwise lets get out of the loop and return the new input
break;
}
}
return theInput;
}
/**
* This is used for grabbing integers from the console. If it cant
* turn the input into an integer it returns -1 as a default
* @return a number from the console once there is new integer input. If not it will return -1
*/
public int waitForInputInt()
{
String theInput = "%%%%ERROR%%%";//if this is somehow returned then there is a problem!!
int theInputInt;
while(true)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
theInput = this.checkForInput();
if(theInput.equalsIgnoreCase("
{
//if there is not any new inpur then lets just do nothing
}
else //if there is input lets do stuff
{
//Lets try and see if we can turn it into an integer, if not then we disregard the input
try{
theInputInt = Integer.parseInt(theInput);//try and convert it
}
catch(InputMismatchException e)
{
//if not then we will return a -1 since most people would probably not be looking for that number hopefuly
theInputInt = -1;
}
break;
}
}
return theInputInt;
}
/**
* Sets the foreground color of the panel
* @param newColor
*/
public void setFontColor(Color newColor)
{
chatLog.setForeground(newColor);
chatLog.setCaretColor(newColor);
sendInputButton.setBackground(newColor);
messageInput.setForeground(newColor);
}
/**
* Sets the background color of the new panel
* @param newColor
*/
public void setBackgroundColor(Color newColor)
{
chatLog.setBackground(newColor);
lowerPanel.setBackground(newColor);
Color dialC = newColor.darker();
messageInput.setBackground(dialC);
}
/**
* Sets the chat log font to the specified type. If what was given
* is not a valid font it returns false.
* @param newFont the new font name
* @return true or false
*/
public boolean setFontType(String newFont)
{
String[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for(int i = 0; i < allFonts.length; i++)
{
if(allFonts[i].equalsIgnoreCase(newFont))//if what they typed equals a font type
{
//set that font and return true
chatLog.setFont(new Font(allFonts[i], font.PLAIN, 12));
messageInput.setFont(new Font(allFonts[i], font.PLAIN, 12));
return true;
}
}
//if we got here thats because no fonts matched so return false
return false;
}
/**
* Prints out all of the fonts available
*/
public void printFonts()
{
String fonts[] =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for(int i = 0; i < fonts.length; i++)
{
addToChatLog(fonts[i]);
}
}
/**
* Adds a a special string to the front and to the back
* of the message that will be printed out. If bothSides
* is set to false will only print to the front of the message
* Sets carrot to the next line.
* @param stuff the content of the string
* @param special the special string to be added to the front and back
* @param bothSides should we put the special on both sides?
*/
public void addToChatLog(String stuff, String special, boolean bothSides)
{
if(bothSides)
{
chatLog.append(special + stuff + special + newLine);
chatLog.setCaretPosition(chatLog.getDocument().getLength());
}
else
{
chatLog.append(special + stuff + newLine);
chatLog.setCaretPosition(chatLog.getDocument().getLength());
}
}
//Main method
public static void main(String args[])
{
MainClass test = new MainClass();
}
}
|
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
public class RequestFromUIControllerToGetaResource extends RequestFromUIController implements Runnable
{
/**
*
* Miguel Velez
* April 29, 2015
*
* This class is a request from ui controller to get a resource
*
* Class variables:
*
* boolean[] responses;
* the part numbers that correspond to responses of this request
*
* Constructors:
*
* public RequestFromUIControllerToGetaResource(ID id)
* create a request to find resources from peers
*
* Methods:
*
* public void updateRequest(UDPMessage udpMessage);
* update the request
*
* public void run()
* Process packets from the UI and community
*
* public Thread startAsThread()
* Start this class as a thread
*
*
* Modification History:
*
* May 7, 2015
* Original version.
*
* May 13, 2015
* Implemented getting a part number and sending to UI.
*
* May 14, 2015
* Using a thread to synchronize the sending and receiving.
*
*/
private boolean[] responses;
private ID resourceID;
public RequestFromUIControllerToGetaResource(ID id, ID resourceId, InetSocketAddress uiController, OutgoingPacketQueue outgoingPacket, int numberOfParts)
{
// Create a request to find resources from peers
// Call the super constructor
super(id, uiController, outgoingPacket);
this.resourceID = resourceId;
this.responses = new boolean[numberOfParts];
// System.out.println(this.responses.length);
}
@Override
public void updateRequest(UDPMessage udpMessage)
{
// Send the datagram packet to the UI controller
// Check if null
if(udpMessage == null)
{
throw new IllegalArgumentException("The UDP message that you provided is null");
}
// Get the request part
byte[] partRequested = new byte[PartNumbers.getLengthInBytes()];
System.arraycopy(udpMessage.getMessage(), ID.getLengthInBytes(), partRequested, 0, PartNumbers.getLengthInBytes());
// System.out.println(partRequested[0] + " - " + partRequested[1] + " - " + partRequested[2] + " - " + partRequested[3]);
// Get the integer representation of the part
int partNumberRequested = ByteBuffer.wrap(partRequested).getInt();
// // Get an int from a byte array
// for(int i = 0; i < PartNumbers.getLengthInBytes(); i++) {
// partNumberRequested = partNumberRequested | ((partRequested[i] & 0xFF) << ((PartNumbers.getLengthInBytes() - 1 - i) * 8));
// System.out.println("Part requested: " + partNumberRequested);
// System.out.println("Before synchronize");
// Synchronize the responses array
synchronized(this.responses)
{
// System.out.println("Have we seen this part: " + partNumberRequested + " - " + this.responses[partNumberRequested]);
// Check if we have seen this response before
if(!this.responses[partNumberRequested])
{
// System.out.println("Part not seen before");
// Add a response with the part number
this.responses[partNumberRequested] = new Boolean(true);
// Get the response packet
byte[] responseMessage = udpMessage.getMessage();
// Get the bytes that we requested
byte[] bytesToSend = new byte[488];
// Pass the resource id
System.arraycopy(udpMessage.getID1().getBytes(), 0, bytesToSend, 0, ID.getLengthInBytes());
// Get the starting byte
long startByte = partNumberRequested * (UDPMessage.getMaximumPacketSizeInBytes() - ID.getLengthInBytes() - (PartNumbers.getLengthInBytes() * 2));
byte[] byteNumber = new byte[8];
for(int i = 0; i < 8; i++) {
byteNumber[i] = (byte) (startByte >> ((8 - 1 - i) * 8));
}
// Put the 4 bytes of the starting byte at the 16 slot to send
System.arraycopy(byteNumber, 0, bytesToSend, ID.getLengthInBytes(), (PartNumbers.getLengthInBytes() * 2));
// Get the end byte
long endByte = startByte + (UDPMessage.getMaximumPacketSizeInBytes() - ID.getLengthInBytes() - (8));
System.out.println(endByte);
byteNumber = new byte[8];
for(int i = 0; i < (8); i++) {
byteNumber[i] = (byte) (endByte >> ((8 - 1 - i) * 8));
}
// Put the 4 bytes of the end byte in spot 20 of the bytes to send
System.arraycopy(byteNumber, 0, bytesToSend, (8) + ID.getLengthInBytes(), (8));
// Copy the bytes to send
System.arraycopy(responseMessage, ID.getLengthInBytes() + 4, bytesToSend, (16) + ID.getLengthInBytes(), 456);
// Create a new datagram
DatagramPacket resourceBytes = new DatagramPacket(bytesToSend, bytesToSend.length);
// Set the address of the UICOntroller
resourceBytes.setAddress(this.getUIControllerAddress().getAddress());
// Set the port of the UIController
resourceBytes.setPort(this.getUIControllerAddress().getPort());
// Send the bytes as start, end, bytes
this.getQueue().enQueue(resourceBytes);
// System.out.println("Sent to ui part:" + partNumberRequested);
// Notify to get a new part
this.responses.notify();
}
}
}
@Override
public void run()
{
for (int i = 0; i < this.responses.length; i++)
{
// Synchronize the responses array
synchronized(this.responses)
{
// Get a byte array from the part number
byte[] partNumber = new byte[4];
// for(int j = 0; j < PartNumbers.getLengthInBytes(); j++) {
// partNumber[j] = (byte) (i >> ((PartNumbers.getLengthInBytes() - 1 - j) * 8));
int temp = i;
// System.out.println("\n" + i);
for(int j = PartNumbers.getLengthInBytes() - 1; j >= 0; j
partNumber[j] = (byte) (temp & 0xFF);
temp = temp >>> 8;
// System.out.println(">>>> "+ (int)partNumber[j]);
}
// partNumber = ByteBuffer.allocate(4).putInt(i).array();
// System.out.println(i+":"+ByteBuffer.wrap(partNumber).getInt());
byte[] message = new byte[ID.getLengthInBytes() + PartNumbers.getLengthInBytes()];
// new String(ID.idFactory().getBytes()) + new String(partNumber)
System.arraycopy(ID.idFactory().getBytes(), 0, message, 0, ID.getLengthInBytes());
System.arraycopy(partNumber, 0, message, ID.getLengthInBytes(), PartNumbers.getLengthInBytes());
// Create a UDP message with format RequestID, ResourceID, TTL, RandomID, partNumber
UDPMessage getMessage = new UDPMessage(this.getID(), this.resourceID, new TimeToLive(), message);
// Send to peers
GossipPartners.getInstance().send(getMessage);
// System.out.println("Requested part: " + i);
// While we have not receive the part number that we requested
while(!this.responses[i])
{
try
{
// Wait
this.responses.wait();
}
catch (InterruptedException ei)
{
}
}
}
}
}
public Thread startAsThread()
{
Thread thread = new Thread();
thread = new Thread(this);
// Execute the run method
thread.start();
return thread;
}
}
|
package com.parc.ccn.library;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.parc.ccn.CCNBase;
import com.parc.ccn.Library;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.MalformedContentNameStringException;
import com.parc.ccn.data.content.Collection;
import com.parc.ccn.data.content.Link;
import com.parc.ccn.data.content.LinkReference;
import com.parc.ccn.data.query.ExcludeFilter;
import com.parc.ccn.data.query.Interest;
import com.parc.ccn.data.security.ContentVerifier;
import com.parc.ccn.data.security.KeyLocator;
import com.parc.ccn.data.security.PublisherPublicKeyDigest;
import com.parc.ccn.data.security.SignedInfo.ContentType;
import com.parc.ccn.library.io.repo.RepositoryOutputStream;
import com.parc.ccn.library.profiles.SegmentationProfile;
import com.parc.ccn.library.profiles.VersioningProfile;
import com.parc.ccn.network.CCNNetworkManager;
import com.parc.ccn.security.keys.KeyManager;
/**
* An implementation of the basic CCN library.
* rides on top of the CCNBase low-level interface. It uses
* CCNNetworkManager to interface with a "real" virtual CCN,
* and KeyManager to interface with the user's collection of
* signing and verification keys.
*
* Need to expand get-side interface to allow querier better
* access to signing information and trust path building.
*
* @author smetters,rasmussen
*
* * <META> tag under which to store metadata (either on name or on version)
* <V> tag under which to put versions
* n/<V>/<number> -> points to header
* <B> tag under which to put actual fragments
* n/<V>/<number>/<B>/<number> -> fragments
* n/<latest>/1/2/... has pointer to latest version
* -- use latest to get header of latest version, otherwise get via <v>/<n>
* configuration parameters:
* blocksize -- size of chunks to fragment into
*
* get always reconstructs fragments and traverses links
* can getLink to get link info
*
*/
public class CCNLibrary extends CCNBase implements ContentVerifier {
static {
Security.addProvider(new BouncyCastleProvider());
}
protected static CCNLibrary _library = null;
/**
* Do we want to do this this way, or everything static?
*/
protected KeyManager _userKeyManager = null;
public static CCNLibrary open() throws ConfigurationException, IOException {
synchronized (CCNLibrary.class) {
try {
return new CCNLibrary();
} catch (ConfigurationException e) {
Library.logger().severe("Configuration exception initializing CCN library: " + e.getMessage());
throw e;
} catch (IOException e) {
Library.logger().severe("IO exception initializing CCN library: " + e.getMessage());
throw e;
}
}
}
public static CCNLibrary open(KeyManager keyManager) {
synchronized (CCNLibrary.class) {
return new CCNLibrary(keyManager);
}
}
public static CCNLibrary getLibrary() {
if (null != _library)
return _library;
try {
return createCCNLibrary();
} catch (ConfigurationException e) {
Library.logger().warning("Configuration exception attempting to create library: " + e.getMessage());
Library.warningStackTrace(e);
throw new RuntimeException("Error in system configuration. Cannot create library.",e);
} catch (IOException e) {
Library.logger().warning("IO exception attempting to create library: " + e.getMessage());
Library.warningStackTrace(e);
throw new RuntimeException("Error in system IO. Cannot create library.",e);
}
}
protected static synchronized CCNLibrary
createCCNLibrary() throws ConfigurationException, IOException {
if (null == _library) {
_library = new CCNLibrary();
}
return _library;
}
protected CCNLibrary(KeyManager keyManager) {
_userKeyManager = keyManager;
// force initialization of network manager
try {
_networkManager = new CCNNetworkManager();
} catch (IOException ex){
Library.logger().warning("IOException instantiating network manager: " + ex.getMessage());
ex.printStackTrace();
_networkManager = null;
}
}
protected CCNLibrary() throws ConfigurationException, IOException {
this(KeyManager.getDefaultKeyManager());
}
/*
* For testing only
*/
protected CCNLibrary(boolean useNetwork) {}
public void setKeyManager(KeyManager keyManager) {
if (null == keyManager) {
Library.logger().warning("StandardCCNLibrary::setKeyManager: Key manager cannot be null!");
throw new IllegalArgumentException("Key manager cannot be null!");
}
_userKeyManager = keyManager;
}
public KeyManager keyManager() { return _userKeyManager; }
public PublisherPublicKeyDigest getDefaultPublisher() {
return keyManager().getDefaultKeyID();
}
/**
* DKS -- TODO -- collection and link functions move to collection and link, respectively
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws SignatureException
* @throws InvalidKeyException
*/
@Deprecated
public Link put(ContentName name, LinkReference target) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
return put(name, target, null, null, null);
}
@Deprecated
public Link put(
ContentName name,
LinkReference target,
PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
if (null == signingKey)
signingKey = keyManager().getDefaultSigningKey();
if (null == locator)
locator = keyManager().getKeyLocator(signingKey);
if (null == publisher) {
publisher = keyManager().getPublisherKeyID(signingKey);
}
try {
Link link = new Link(VersioningProfile.addVersion(name), target,
publisher, locator, signingKey);
put(link);
return link;
} catch (XMLStreamException e) {
Library.logger().warning("Cannot canonicalize a standard container!");
Library.warningStackTrace(e);
throw new IOException("Cannot canonicalize a standard container!");
}
}
/**
* The following 3 methods create a Collection with the argument references,
* put it, and return it. Note that fragmentation is not handled.
*
* @param name
* @param references
* @return
* @throws SignatureException
* @throws IOException
*/
@Deprecated
public Collection put(ContentName name, LinkReference [] references) throws SignatureException, IOException {
return put(name, references, getDefaultPublisher());
}
@Deprecated
public Collection put(ContentName name, LinkReference [] references, PublisherPublicKeyDigest publisher)
throws SignatureException, IOException {
try {
return put(name, references, publisher, null, null);
} catch (InvalidKeyException e) {
Library.logger().warning("Default key invalid.");
Library.warningStackTrace(e);
throw new SignatureException(e);
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Default key has invalid algorithm.");
Library.warningStackTrace(e);
throw new SignatureException(e);
}
}
@Deprecated
public Collection put(
ContentName name,
LinkReference[] references,
PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
if (null == signingKey)
signingKey = keyManager().getDefaultSigningKey();
if (null == locator)
locator = keyManager().getKeyLocator(signingKey);
if (null == publisher) {
publisher = keyManager().getPublisherKeyID(signingKey);
}
try {
Collection collection = new Collection(VersioningProfile.addVersion(name), references,
publisher, locator, signingKey);
put(collection);
return collection;
} catch (XMLStreamException e) {
Library.logger().warning("Cannot canonicalize a standard container!");
Library.warningStackTrace(e);
throw new IOException("Cannot canonicalize a standard container!");
}
}
@Deprecated
public Collection put(
ContentName name,
ContentName[] references) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
return put(name, references, null, null, null);
}
@Deprecated
public Collection put(
ContentName name,
ContentName[] references,
PublisherPublicKeyDigest publisher) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
return put(name, references, publisher, null, null);
}
@Deprecated
public Collection put(
ContentName name,
ContentName[] references,
PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
LinkReference[] lrs = new LinkReference[references.length];
for (int i = 0; i < lrs.length; i++)
lrs[i] = new LinkReference(references[i]);
return put(name, lrs, publisher, locator, signingKey);
}
/**
*
* @param name - ContentName
* @param timeout - milliseconds
* @return
* @throws IOException
* @throws XMLStreamException
*/
@Deprecated
public Collection getCollection(ContentName name, long timeout) throws IOException, XMLStreamException {
ContentObject co = getLatestVersion(name, null, timeout);
if (null == co)
return null;
if (co.signedInfo().getType() != ContentType.DATA)
throw new IOException("Content is not data, so can't be a collection.");
Collection collection = Collection.contentToCollection(co);
return collection;
}
/**
* Use the same publisherID that we used originally.
* @throws IOException
* @throws SignatureException
* @throws XMLStreamException
* @throws InvalidKeyException
*/
@Deprecated
public Collection createCollection(
ContentName name,
ContentName [] references, PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws IOException, SignatureException,
XMLStreamException, InvalidKeyException {
LinkReference[] lrs = new LinkReference[references.length];
for (int i = 0; i < references.length; i++) {
lrs[i] = new LinkReference(references[i]);
}
return createCollection(name, lrs, publisher, locator, signingKey);
}
@Deprecated
public Collection createCollection(
ContentName name,
LinkReference [] references, PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws IOException, SignatureException,
XMLStreamException, InvalidKeyException {
if (null == signingKey)
signingKey = keyManager().getDefaultSigningKey();
if (null == locator)
locator = keyManager().getKeyLocator(signingKey);
if (null == publisher) {
publisher = keyManager().getPublisherKeyID(signingKey);
}
return new Collection(name, references, publisher, locator, signingKey);
}
@Deprecated
public Collection addToCollection(
Collection collection,
ContentName [] references) throws IOException, SignatureException,
XMLStreamException, InvalidKeyException {
LinkedList<LinkReference> contents = collection.contents();
for (ContentName reference : references)
contents.add(new LinkReference(reference));
return updateCollection(collection, contents, null, null, null);
}
@Deprecated
public ContentObject removeFromCollection(
Collection collection,
ContentName [] references) throws IOException, SignatureException,
XMLStreamException, InvalidKeyException {
LinkedList<LinkReference> contents = collection.contents();
for (ContentName reference : references)
contents.remove(new LinkReference(reference));
return updateCollection(collection, contents, null, null, null);
}
@Deprecated
public ContentObject updateCollection(
Collection collection,
ContentName [] referencesToAdd,
ContentName [] referencesToRemove) throws IOException, SignatureException,
XMLStreamException, InvalidKeyException {
LinkedList<LinkReference> contents = collection.contents();
for (ContentName reference : referencesToAdd)
contents.add(new LinkReference(reference));
for (ContentName reference : referencesToRemove)
contents.remove(new LinkReference(reference));
return updateCollection(collection, contents, null, null, null);
}
/**
* Create a Collection with the next version name and the input
* references and put it. Note that this can't handle fragmentation.
*
* @param oldCollection
* @param references
* @return
* @throws XMLStreamException
* @throws IOException
* @throws SignatureException
* @throws InvalidKeyException
*/
@Deprecated
private Collection updateCollection(Collection oldCollection, LinkedList<LinkReference> references,
PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws XMLStreamException, IOException,
InvalidKeyException, SignatureException {
LinkReference[] newReferences = new LinkReference[references.size()];
references.toArray(newReferences);
Collection updatedCollection = createCollection(VersioningProfile.updateVersion(oldCollection.name()),
newReferences, publisher, locator, signingKey);
put(updatedCollection);
return updatedCollection;
}
@Deprecated
public Link createLink(
ContentName name,
ContentName linkName, PublisherPublicKeyDigest publisher, KeyLocator locator,
PrivateKey signingKey) throws IOException, SignatureException,
XMLStreamException, InvalidKeyException {
if (null == signingKey)
signingKey = keyManager().getDefaultSigningKey();
if (null == locator)
locator = keyManager().getKeyLocator(signingKey);
if (null == publisher) {
publisher = keyManager().getPublisherKeyID(signingKey);
}
return new Link(name, linkName, publisher, locator, signingKey);
}
/**
* Return the link itself, not the content
* pointed to by a link.
* @param name the identifier for the link to work on
* @return returns null if not a link, or name refers to more than one object
* @throws IOException
* @throws SignatureException
* @throws IOException
*/
@Deprecated
public Link getLink(ContentName name, long timeout) throws IOException {
ContentObject co = getLatestVersion(name, null, timeout);
if (co.signedInfo().getType() != ContentType.LINK)
throw new IOException("Content is not a link reference");
Link reference = new Link();
try {
reference.decode(co.content());
} catch (XMLStreamException e) {
// Shouldn't happen
e.printStackTrace();
}
return reference;
}
/**
* Turn ContentObject of type link into a LinkReference
* @param co ContentObject
* @return
* @throws IOException
*/
@Deprecated
public Link decodeLinkReference(ContentObject co) throws IOException {
if (co.signedInfo().getType() != ContentType.LINK)
throw new IOException("Content is not a collection");
Link reference = new Link();
try {
reference.decode(co.content());
} catch (XMLStreamException e) {
// Shouldn't happen
e.printStackTrace();
}
return reference;
}
/**
* Deference links and collections
* DKS TODO -- should it dereference collections?
* @param content
* @param timeout
* @return
* @throws IOException
* @throws XMLStreamException
*/
@Deprecated
public ArrayList<ContentObject> dereference(ContentObject content, long timeout) throws IOException, XMLStreamException {
ArrayList<ContentObject> result = new ArrayList<ContentObject>();
if (null == content)
return null;
if (content.signedInfo().getType() == ContentType.LINK) {
Link link = Link.contentToLinkReference(content);
ContentObject linkCo = dereferenceLink(link, content.signedInfo().getPublisherKeyID(), timeout);
if (linkCo == null) {
return null;
}
result.add(linkCo);
} else if (content.signedInfo().getType() == ContentType.DATA) {
try {
Collection collection = Collection.contentToCollection(content);
if (null != collection) {
LinkedList<LinkReference> al = collection.contents();
for (LinkReference lr : al) {
ContentObject linkCo = dereferenceLink(lr, content.signedInfo().getPublisherKeyID(), timeout);
if (linkCo != null)
result.add(linkCo);
}
if (result.size() == 0)
return null;
} else { // else, not a collection
result.add(content);
}
} catch (XMLStreamException xe) {
// not a collection
result.add(content);
}
} else {
result.add(content);
}
return result;
}
/**
* Try to get the content referenced by the link. If it doesn't exist directly,
* try to get the latest version below the name.
*
* @param reference
* @param publisher
* @param timeout
* @return
* @throws IOException
*/
@Deprecated
private ContentObject dereferenceLink(LinkReference reference, PublisherPublicKeyDigest publisher, long timeout) throws IOException {
ContentObject linkCo = get(reference.targetName(), timeout);
if (linkCo == null)
linkCo = getLatestVersion(reference.targetName(), publisher, timeout);
return linkCo;
}
@Deprecated
private ContentObject dereferenceLink(Link reference, PublisherPublicKeyDigest publisher, long timeout) throws IOException {
ContentObject linkCo = get(reference.getTargetName(), timeout);
if (linkCo == null)
linkCo = getLatestVersion(reference.getTargetName(), publisher, timeout);
return linkCo;
}
/**
* Gets the latest version using a single interest/response. There may be newer versions available
* if you ask again passing in the version found.
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that. If the name does not end in a version then this call just looks for the latest version.
* @param publisher Currently unused
* @param timeout
* @return A ContentObject with the latest version, or null if the query timed out. Note - the content
* returned could be any name under this new version - the last (rightmost) name is asked for, but
* depending on where the answer came from it may not necessarily be the last (rightmost) available.
* @throws IOException
* DKS TODO -- doesn't use publisher
* DKS TODO -- specify separately latest version known?
*/
public ContentObject getLatestVersion(ContentName name, PublisherPublicKeyDigest publisher, long timeout) throws IOException {
if (VersioningProfile.hasTerminalVersion(name)) {
return getVersionInternal(SegmentationProfile.segmentRoot(name), timeout);
} else {
ContentName firstVersionName = VersioningProfile.addVersion(name, VersioningProfile.baseVersion());
return getVersionInternal(firstVersionName, timeout);
}
}
/**
* We are only called by getLatestVersion, which has already ensured that we
* either have a user-supplied version or a terminal version marker at the end of name; we have
* also previously stripped any segment marker. So we know we have a name terminated
* by the last version we know about (which could be 0).
*/
private ContentObject getVersionInternal(ContentName name, long timeout) throws InvalidParameterException, IOException {
byte [] versionComponent = name.lastComponent();
// initially exclude name components just before the first version, whether that is the
// 0th version or the version passed in
while (true) {
ContentObject co = getLatest(name, VersioningProfile.acceptVersions(versionComponent), timeout);
if (co == null) {
Library.logger().info("Null returned from getLatest for name: " + name);
return null;
}
// What we get should be a block representing a later version of name. It might
// be an actual segment of a versioned object, but it might also be an ancillary
// object - e.g. a repo message -- which starts with a particular version of name.
if (VersioningProfile.startsWithLaterVersionOf(co.name(), name)) {
// we got a valid version!
// DKS TODO should we see if it's actually later than name?
Library.logger().info("Got latest version: " + co.name());
return co;
} else {
Library.logger().info("Rejected potential candidate version: " + co.name() + " not a later version of " + name);
}
versionComponent = co.name().component(name.count()-1);
}
}
public ContentObject get(ContentName name, long timeout) throws IOException {
Interest interest = new Interest(name);
return get(interest, timeout);
}
/**
* Return data the specified number of levels below us in the
* hierarchy
*
* @param name
* @param level
* @param timeout
* @return
* @throws IOException
*/
public ContentObject getLower(ContentName name, int level, long timeout) throws IOException {
Interest interest = new Interest(name);
interest.additionalNameComponents(level);
return get(interest, timeout);
}
/**
* Return data the specified number of levels below us in the
* hierarchy, with order preference leftmost.
* DKS -- this might need to move to Interest.
* @param name
* @param level
* @param timeout
* @return
* @throws IOException
*/
public ContentObject getLeftmostLower(ContentName name, int level, long timeout) throws IOException {
Interest interest = new Interest(name);
interest.additionalNameComponents(level);
interest.orderPreference(Interest.ORDER_PREFERENCE_ORDER_NAME | Interest.ORDER_PREFERENCE_LEFT);
return get(interest, timeout);
}
/**
* Enumerate matches below query name in the hierarchy
* TODO: maybe filter out fragments, possibly other metadata.
* TODO: add in communication layer to talk just to
* local repositories for v 2.0 protocol.
* @param query
* @param timeout - microseconds
* @return
* @throws IOException
*/
public ArrayList<ContentObject> enumerate(Interest query, long timeout) throws IOException {
ArrayList<ContentObject> result = new ArrayList<ContentObject>();
Integer prefixCount = query.nameComponentCount() == null ? query.name().components().size()
: query.nameComponentCount();
// This won't work without a correct order preference
query.orderPreference(Interest.ORDER_PREFERENCE_ORDER_NAME | Interest.ORDER_PREFERENCE_LEFT);
while (true) {
ContentObject co = null;
co = get(query, timeout == NO_TIMEOUT ? 5000 : timeout);
if (co == null)
break;
Library.logger().info("enumerate: retrieved " + co.name() +
" digest: " + ContentName.componentPrintURI(co.contentDigest()) + " on query: " + query.name() + " prefix count: " + prefixCount);
result.add(co);
query = Interest.next(co, prefixCount);
}
Library.logger().info("enumerate: retrieved " + result.size() + " objects.");
return result;
}
/**
* Approaches to read and write content. Low-level CCNBase returns
* a specific piece of content from the repository (e.g.
* if you ask for a fragment, you get a fragment). Library
* customers want the actual content, independent of
* fragmentation. Can implement this in a variety of ways;
* could verify fragments and reconstruct whole content
* and return it all at once. Could (better) implement
* file-like API -- open opens the header for a piece of
* content, read verifies the necessary fragments to return
* that much data and reads the corresponding content.
* Open read/write or append does?
*
* DKS: TODO -- state-based put() analogous to write()s in
* blocks; also state-based read() that verifies. Start
* with state-based read.
*
* Nothing uses this method for anything that couldn't easily be replaced.
*/
@Deprecated
public RepositoryOutputStream repoOpen(ContentName name,
KeyLocator locator, PublisherPublicKeyDigest publisher)
throws IOException, XMLStreamException {
return new RepositoryOutputStream(name, locator, publisher, this);
}
/**
* Medium level interface for retrieving pieces of a file
*
* getNext - get next content after specified content
*
* @param name - ContentName for base of get
* @param prefixCount - next follows components of the name
* through this count.
* @param omissions - ExcludeFilter
* @param timeout - milliseconds
* @return
* @throws MalformedContentNameStringException
* @throws IOException
* @throws InvalidParameterException
*/
public ContentObject getNext(ContentName name, byte[][] omissions, long timeout)
throws IOException {
return get(Interest.next(name, omissions, null), timeout);
}
public ContentObject getNext(ContentName name, long timeout)
throws IOException, InvalidParameterException {
return getNext(name, null, timeout);
}
public ContentObject getNext(ContentName name, int prefixCount, long timeout)
throws IOException, InvalidParameterException {
return get(Interest.next(name, prefixCount), timeout);
}
public ContentObject getNext(ContentObject content, int prefixCount, byte[][] omissions, long timeout)
throws IOException {
return getNext(contentObjectToContentName(content, prefixCount), omissions, timeout);
}
/**
* Get last content that follows name in similar manner to
* getNext
*
* @param name
* @param omissions
* @param timeout
* @return
* @throws MalformedContentNameStringException
* @throws IOException
* @throws InvalidParameterException
*/
public ContentObject getLatest(ContentName name, ExcludeFilter exclude, long timeout)
throws IOException, InvalidParameterException {
return get(Interest.last(name, exclude), timeout);
}
public ContentObject getLatest(ContentName name, long timeout) throws InvalidParameterException,
IOException {
return getLatest(name, null, timeout);
}
public ContentObject getLatest(ContentName name, int prefixCount, long timeout) throws InvalidParameterException,
IOException {
return get(Interest.last(name, prefixCount), timeout);
}
public ContentObject getLatest(ContentObject content, int prefixCount, long timeout) throws InvalidParameterException,
IOException {
return getLatest(contentObjectToContentName(content, prefixCount), null, timeout);
}
/**
*
* @param name
* @param omissions
* @param timeout
* @return
* @throws InvalidParameterException
* @throws MalformedContentNameStringException
* @throws IOException
*/
public ContentObject getExcept(ContentName name, byte[][] omissions, long timeout) throws InvalidParameterException, MalformedContentNameStringException,
IOException {
return get(Interest.exclude(name, omissions), timeout);
}
private ContentName contentObjectToContentName(ContentObject content, int prefixCount) {
ContentName cocn = content.name().clone();
cocn.components().add(content.contentDigest());
return new ContentName(prefixCount, cocn.components());
}
/**
* Shutdown the library and it's associated resources
*/
public void close() {
if (null != _networkManager)
_networkManager.shutdown();
_networkManager = null;
}
/* (non-Javadoc)
* @see com.parc.ccn.data.security.ContentVerifier#verifyBlock(com.parc.ccn.data.ContentObject)
*/
public boolean verifyBlock(ContentObject block) {
boolean result = false;
try {
if (null == block)
return false;
result = block.verify(null);
} catch (Exception ex) {
// DKS TODO -- maybe do something more significant, but will minimize use of the default verifier.
Library.logger().warning("Caught exception of type: " + ex.getClass().getName() + " in verify: " + ex.getMessage());
result = false;
}
return result;
}
/**
* Allow default verification behavior to be replaced.
* @return
*/
public ContentVerifier defaultVerifier() {
return this;
}
}
|
package org.commcare.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.WindowManager;
import org.commcare.engine.references.JavaFileReference;
import org.commcare.logging.AndroidLogger;
import org.commcare.preferences.CommCarePreferences;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.Reference;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import java.io.File;
import java.io.IOException;
/**
* @author ctsims
*/
public class MediaUtil {
public static final String FORM_VIDEO = "video";
public static final String FORM_AUDIO = "audio";
public static final String FORM_IMAGE = "image";
/**
* Attempts to inflate an image from a CommCare UI definition source.
*
* @param jrUri The image to inflate
* @param boundingWidth the width of the container this image is being inflated into, to serve
* as a max width. If passed in as -1, gets set to screen width
* @param boundingHeight the height fo the container this image is being inflated into, to
* serve as a max height. If passed in as -1, gets set to screen height
* @return A bitmap if one could be created. Null if error occurs or the image is unavailable.
*/
public static Bitmap inflateDisplayImage(Context context, String jrUri,
int boundingWidth, int boundingHeight) {
if (jrUri == null || jrUri.equals("")) {
return null;
}
try {
Reference ref = ReferenceManager._().DeriveReference(jrUri);
try {
if (!ref.doesBinaryExist()) {
return null;
}
if (!(ref instanceof JavaFileReference)) {
return BitmapFactory.decodeStream(ref.getStream());
}
} catch (IOException e) {
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "IO Exception loading reference: " + jrUri);
return null;
}
String imageFilename = ref.getLocalURI();
final File imageFile = new File(imageFilename);
if (!imageFile.exists()) {
return null;
}
DisplayMetrics displayMetrics = new DisplayMetrics();
((WindowManager)context.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay()
.getMetrics(displayMetrics);
if (boundingHeight == -1) {
boundingHeight = displayMetrics.heightPixels;
}
if (boundingWidth == -1) {
boundingWidth = displayMetrics.widthPixels;
}
if (CommCarePreferences.isSmartInflationEnabled()) {
// scale based on native density AND bounding dimens
return getBitmapScaledForNativeDensity(
context.getResources().getDisplayMetrics(), imageFile.getAbsolutePath(),
boundingHeight, boundingWidth,
CommCarePreferences.getTargetInflationDensity());
} else {
// just scaling down if the original image is too big for its container
return getBitmapScaledToContainer(imageFile.getAbsolutePath(), boundingHeight,
boundingWidth);
}
} catch (InvalidReferenceException e) {
Log.e("ImageInflater", "image invalid reference exception for " + e.getReferenceString());
e.printStackTrace();
}
return null;
}
public static Bitmap inflateDisplayImage(Context context, String jrUri) {
return inflateDisplayImage(context, jrUri, -1, -1);
}
/**
* Attempt to inflate an image source into a bitmap whose final dimensions are based upon
* 2 factors:
*
* 1) The application of a scaling factor, which is derived from the relative values of the
* target density declared by the app and the current device's actual density
* 2) The absolute dimensions of the bounding container into which this image is being inflated
* (may just be the screen dimens)
*
* @return the bitmap, or null if none could be created from the source
*/
public static Bitmap getBitmapScaledForNativeDensity(DisplayMetrics metrics, String imageFilepath,
int containerHeight, int containerWidth,
int targetDensity) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inScaled = false;
BitmapFactory.decodeFile(imageFilepath, o);
int imageHeight = o.outHeight;
int imageWidth = o.outWidth;
double scaleFactor = computeInflationScaleFactor(metrics, targetDensity);
int calculatedHeight = Math.round((float)(imageHeight * scaleFactor));
int calculatedWidth = Math.round((float)(imageWidth * scaleFactor));
if (containerHeight < imageHeight || containerWidth < imageWidth || calculatedHeight < imageHeight) {
// If either the container dimens or calculated dimens impose a smaller dimension,
// scale down
return getBitmapScaledByTargetOrContainer(imageFilepath, imageHeight, imageWidth,
calculatedHeight, calculatedWidth, containerHeight, containerWidth, false);
} else {
return attemptBoundedScaleUp(imageFilepath, calculatedHeight, calculatedWidth,
containerHeight, containerWidth);
}
}
public static double computeInflationScaleFactor(DisplayMetrics metrics, int targetDensity) {
final int SCREEN_DENSITY = metrics.densityDpi;
double actualNativeScaleFactor = metrics.density;
// The formula below is what Android *usually* uses to compute the value of metrics.density
// for a device. If this is in fact the value being used, we are not interested in it.
// However, if the actual value differs at all from the standard calculation, it means
// Android is taking other factors into consideration (such as straight up screen size),
// and we want to incorporate that proportionally into our own version of the scale factor
double standardNativeScaleFactor = (double)SCREEN_DENSITY / DisplayMetrics.DENSITY_DEFAULT;
double proportionalAdjustmentFactor = 1;
if (actualNativeScaleFactor > standardNativeScaleFactor) {
proportionalAdjustmentFactor = 1 +
((actualNativeScaleFactor - standardNativeScaleFactor) / standardNativeScaleFactor);
} else if (actualNativeScaleFactor < standardNativeScaleFactor) {
proportionalAdjustmentFactor = actualNativeScaleFactor / standardNativeScaleFactor;
}
// Get our custom scale factor, based on this device's density and what the image's target
// density was
double customDpiScaleFactor = (double)SCREEN_DENSITY / targetDensity;
return customDpiScaleFactor * proportionalAdjustmentFactor;
}
/**
* @return A bitmap representation of the given image file, scaled down to the smallest
* size that still fills the container
*
* More precisely, preserves the following 2 conditions:
* 1. The larger of the 2 sides takes on the size of the corresponding container dimension
* (e.g. if its width is larger than its height, then the new width should = containerWidth)
* 2. The aspect ratio of the original image is maintained (so the height would get scaled
* down proportionally with the width)
*/
public static Bitmap getBitmapScaledToContainer(String imageFilepath, int containerHeight,
int containerWidth) {
// Determine dimensions of original image
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFilepath, o);
int imageHeight = o.outHeight;
int imageWidth = o.outWidth;
return getBitmapScaledByTargetOrContainer(imageFilepath, imageHeight, imageWidth, -1, -1,
containerHeight, containerWidth, true);
}
public static Bitmap getBitmapScaledToContainer(File imageFile, int containerHeight,
int containerWidth) {
return getBitmapScaledToContainer(imageFile.getAbsolutePath(), containerHeight,
containerWidth);
}
/**
* @param scaleByContainerOnly If true, means that we're just trying to ensure that our bitmap
* isn't way bigger than necessary, rather than creating a bitmap
* of an exact size based on a target width and height. In this
* case, targetWidth and targetHeight are ignored and the 2nd case
* above is used.
* @return A bitmap representation of the given image file, scaled down such that the new
* dimensions of the image are the SMALLER of the following 2 options:
* 1) targetHeight and targetWidth
* 2) the largest dimensions for which the original aspect ratio is maintained, without
* exceeding either boundingWidth or boundingHeight
*/
private static Bitmap getBitmapScaledByTargetOrContainer(String imageFilepath,
int originalHeight, int originalWidth,
int targetHeight, int targetWidth,
int boundingHeight, int boundingWidth,
boolean scaleByContainerOnly) {
Pair<Integer, Integer> dimensImposedByContainer = getDimensImposedByContainer(
originalHeight, originalWidth, boundingHeight, boundingWidth);
int newWidth, newHeight;
if (scaleByContainerOnly) {
newWidth = dimensImposedByContainer.first;
newHeight = dimensImposedByContainer.second;
} else {
newWidth = Math.min(dimensImposedByContainer.first, targetWidth);
newHeight = Math.min(dimensImposedByContainer.second, targetHeight);
}
int approximateScaleFactor = getApproxScaleFactor(newWidth, originalWidth);
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = approximateScaleFactor;
// Decode the bitmap with the largest integer scale down factor that will not make it
// smaller than the final desired size
Bitmap originalBitmap = BitmapFactory.decodeFile(imageFilepath, o);
if (scaleByContainerOnly) {
// Not worth performance loss of creating an exact scaled bitmap in this case
return originalBitmap;
} else {
// Here we want to be more precise because we had a target width and height
return Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);
}
} catch (OutOfMemoryError e) {
// OOM encountered trying to decode the bitmap, so we know we need to scale down by
// a larger factor
return performSafeScaleDown(imageFilepath, approximateScaleFactor + 1, 0);
}
}
private static int getApproxScaleFactor(int newWidth, int originalWidth) {
if (newWidth == 0) {
return 1;
} else {
int scale = originalWidth / newWidth;
if (scale == 0) {
return 1;
}
return scale;
}
}
/**
* @return The original dimens if they both fit within the bounds. Otherwise, return the
* smallest dimensions that both preserve the original aspect ratio, and still fill the
* container
*/
private static Pair<Integer, Integer> getDimensImposedByContainer(int originalHeight,
int originalWidth,
int boundingHeight,
int boundingWidth) {
if (originalHeight < boundingHeight && originalWidth < boundingWidth) {
return new Pair<>(originalWidth, originalHeight);
}
double heightScaleDownFactor = (double)boundingHeight / originalHeight;
double widthScaleDownFactor = (double)boundingWidth / originalWidth;
// Choosing the larger of the scale down factors, so that the image still fills the entire
// container
double dominantScaleDownFactor = Math.max(heightScaleDownFactor, heightScaleDownFactor);
int widthImposedByContainer = (int)Math.round(originalWidth * dominantScaleDownFactor);
int heightImposedByContainer = (int)Math.round(originalHeight * dominantScaleDownFactor);
return new Pair<>(widthImposedByContainer, heightImposedByContainer);
}
/**
* @return A bitmap representation of the given image file, scaled up as close as possible to
* desiredWidth and desiredHeight, without exceeding either boundingHeight or boundingWidth
*/
private static Bitmap attemptBoundedScaleUp(String imageFilepath,
int desiredHeight, int desiredWidth,
int boundingHeight, int boundingWidth) {
if (boundingHeight < desiredHeight || boundingWidth < desiredWidth) {
Pair<Integer, Integer> dimensForScaleUp = boundedScaleUpHelper(
desiredHeight, desiredWidth, boundingHeight, boundingWidth);
desiredWidth = dimensForScaleUp.first;
desiredHeight = dimensForScaleUp.second;
}
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
Bitmap originalBitmap = BitmapFactory.decodeFile(imageFilepath, o);
try {
return Bitmap.createScaledBitmap(originalBitmap, desiredWidth, desiredHeight, false);
} catch (OutOfMemoryError e) {
return originalBitmap;
}
} catch (OutOfMemoryError e) {
// Just inflating the image at its original size caused an OOM error, don't have a
// choice but to scale down
return performSafeScaleDown(imageFilepath, 2, 1);
}
}
/**
* @return A (width, height) pair representing the largest possible dimensions that both:
* a) do not exceed boundingHeight or boundingWidth, and
* b) maintain the aspect ratio given by originalHeight and originalWidth
*/
private static Pair<Integer, Integer> boundedScaleUpHelper(int originalHeight,
int originalWidth,
int boundingHeight,
int boundingWidth) {
double heightScaleFactor = (double)boundingHeight / originalHeight;
double widthScaleFactor = (double)boundingWidth / originalWidth;
double dominantScaleFactor = Math.min(heightScaleFactor, widthScaleFactor);
int scaledUpWidthImposedByContainer = (int)Math.round(originalWidth * dominantScaleFactor);
int scaledUpHeightImposedByContainer = (int)Math.round(originalHeight * dominantScaleFactor);
return new Pair<>(scaledUpWidthImposedByContainer, scaledUpHeightImposedByContainer);
}
/**
* @return A scaled-down bitmap for the given image file, progressively increasing the
* scale-down factor by 1 until allocating memory for the bitmap does not cause an OOM error
*/
private static Bitmap performSafeScaleDown(String imageFilepath, int scale, int depth) {
if (depth == 5) {
// Limit the number of recursive calls
return null;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scale;
try {
return BitmapFactory.decodeFile(imageFilepath, options);
} catch (OutOfMemoryError e) {
return performSafeScaleDown(imageFilepath, scale + 1, depth + 1);
}
}
}
|
package oap.media.postprocessing;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import oap.json.Binder;
import oap.media.Media;
import oap.media.MediaInfo;
import oap.media.MediaProcessing;
import org.apache.commons.io.IOUtils;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
public class FFProbeMediaProcessing implements MediaProcessing {
private final List<String> command;
private final long timeout;
public FFProbeMediaProcessing( List<String> command, long timeout ) {
this.command = command;
this.timeout = timeout;
}
@Override
@SneakyThrows
public Media process( Media media, MediaInfo mediaInfo ) {
log.debug( "ffprobe {}...", media.path );
final ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream( true );
final ArrayList<String> cmd = new ArrayList<>( command );
cmd.add( media.path.toString() );
Files.copy( media.path, Paths.get("/tmp/1.mpg") );
builder.command( cmd );
log.trace( "cmd = {}", cmd );
Process p = builder.start();
try {
final String json = IOUtils.toString( p.getInputStream(), StandardCharsets.UTF_8 );
log.trace( "ffprobe: {}", json );
final Map<String, Object> info = Binder.json.unmarshal( new TypeReference<Map<String, Object>>() {}, json );
mediaInfo.put( "ffprobe", info );
p.waitFor( timeout, TimeUnit.MILLISECONDS );
} finally {
p.destroy();
}
return media;
}
}
|
package org.opencb.opencga.analysis;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.opencb.hpg.bigdata.analysis.exceptions.AnalysisToolException;
import org.opencb.hpg.bigdata.analysis.tools.ToolManager;
import org.opencb.hpg.bigdata.analysis.tools.manifest.Param;
import org.opencb.opencga.catalog.db.api.FileDBAdaptor;
import org.opencb.opencga.catalog.db.api.JobDBAdaptor;
import org.opencb.opencga.catalog.db.api.StudyDBAdaptor;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.managers.CatalogManager;
import org.opencb.opencga.catalog.managers.FileManager;
import org.opencb.opencga.catalog.managers.JobManager;
import org.opencb.opencga.core.config.Configuration;
import org.opencb.opencga.core.models.File;
import org.opencb.opencga.core.models.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ToolAnalysis {
private Logger logger = LoggerFactory.getLogger(ToolAnalysis.class);
private CatalogManager catalogManager;
private ToolManager toolManager;
private JobManager jobManager;
private FileManager fileManager;
public ToolAnalysis(Configuration configuration) throws CatalogException, AnalysisToolException {
this.catalogManager = new CatalogManager(configuration);
this.toolManager = new ToolManager(Paths.get(configuration.getToolDir()));
this.jobManager = catalogManager.getJobManager();
this.fileManager = catalogManager.getFileManager();
}
/**
* Execute a command tool.
* @param jobId jobId of the job containing the relevant information.
* @param sessionId session id of the user that will execute the tool.
*/
public void execute(long jobId, String sessionId) {
try {
// We get the job information.
Query query = new Query();
query.put(JobDBAdaptor.QueryParams.UID.key(), jobId);
Job job = jobManager.get(null, query, QueryOptions.empty(), sessionId).first();
long studyUid = jobManager.getStudyId(jobId);
// get the study FQN we need
query = new Query();
query.put(StudyDBAdaptor.QueryParams.UID.key(), studyUid);
String studyFqn = catalogManager.getStudyManager().get(query, QueryOptions.empty(), sessionId).first().getFqn();
String outDir = (String) job.getAttributes().get(Job.OPENCGA_TMP_DIR);
Path outDirPath = Paths.get(outDir);
String tool = job.getToolId();
String execution = job.getExecution();
// Create the OpenCGA output folder
fileManager.createFolder(studyFqn, (String) job.getAttributes().get(Job.OPENCGA_OUTPUT_DIR),
new File.FileStatus(), true, "", QueryOptions.empty(), sessionId);
// Convert the input and output files to uris in the filesystem
Map<String, String> params = new HashMap<>(job.getParams());
List<Param> inputParams = toolManager.getInputParams(tool, execution);
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.URI.key());
for (Param inputParam : inputParams) {
if (inputParam.isRequired() && !params.containsKey(inputParam.getName())) {
throw new CatalogException("Missing mandatory input parameter " + inputParam.getName());
}
if (params.containsKey(inputParam.getName())) {
// Get the file uri
String fileString = params.get(inputParam.getName());
QueryResult<File> fileQueryResult = fileManager.get(studyFqn, fileString, options, sessionId);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("File " + fileString + " not found");
}
params.put(inputParam.getName(), fileQueryResult.first().getUri().getPath());
}
}
// Convert output file params to be stored in the output directory specified
List<Param> outputParams = toolManager.getOutputParams(tool, execution);
for (Param outputParam : outputParams) {
if (outputParam.isRequired() && !params.containsKey(outputParam.getName())) {
throw new CatalogException("Missing mandatory output parameter " + outputParam.getName());
}
if (params.containsKey(outputParam.getName())) {
// Contextualise the file name in the uri where it should be written. /jobs/jobX/file.txt where /jobs/jobX = outDir and
// file.txt = outputFileName
Path name = Paths.get(params.get(outputParam.getName()));
String absolutePath = outDirPath.resolve(name.toFile().getName()).toString();
params.put(outputParam.getName(), absolutePath);
}
}
// Execute the tool
String commandLine = toolManager.createCommandLine(tool, execution, params);
toolManager.runCommandLine(commandLine, Paths.get(outDir), false);
} catch (CatalogException | AnalysisToolException e) {
logger.error("{}", e.getMessage(), e);
}
}
}
|
package com.limegroup.gnutella.gui;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Locale;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.net.InetAddress;
import java.net.BindException;
import com.limegroup.gnutella.URN;
import com.limegroup.gnutella.RouterService;
import com.limegroup.gnutella.FileDesc;
import com.limegroup.gnutella.IncompleteFileDesc;
import com.limegroup.gnutella.util.CommonUtils;
import com.limegroup.gnutella.util.NetworkUtils;
import com.limegroup.gnutella.util.FileUtils;
import com.limegroup.gnutella.util.ManagedThread;
import com.limegroup.gnutella.settings.DaapSettings;
import com.limegroup.gnutella.FileManagerEvent;
import com.limegroup.gnutella.filters.IPFilter;
import com.limegroup.gnutella.gui.GUIMediator;
import com.limegroup.gnutella.gui.FinalizeListener;
import com.limegroup.gnutella.xml.LimeXMLDocument;
import com.limegroup.gnutella.xml.LimeXMLReplyCollection;
import com.limegroup.gnutella.xml.SchemaReplyCollectionMapper;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import de.kapsi.net.daap.Song;
import de.kapsi.net.daap.Playlist;
import de.kapsi.net.daap.Library;
import de.kapsi.net.daap.DaapServer;
import de.kapsi.net.daap.DaapServerFactory;
import de.kapsi.net.daap.SimpleConfig;
import de.kapsi.net.daap.DaapFilter;
import de.kapsi.net.daap.DaapStreamSource;
import de.kapsi.net.daap.DaapAuthenticator;
import de.kapsi.net.daap.DaapThreadFactory;
/**
* This class handles the mDNS registration and acts as an
* interface between LimeWire and DAAP.
*/
public final class DaapMediator implements FinalizeListener {
private static final Log LOG = LogFactory.getLog(DaapMediator.class);
private static final DaapMediator INSTANCE = new DaapMediator();
private static final String AUDIO_SCHEMA = "http:
public static DaapMediator instance() {
return INSTANCE;
}
private SongURNMap map;
private Library library;
private Playlist whatsNew;
private DaapServer server;
private RendezvousService rendezvous;
private UpdateWorker updateWorker;
private boolean annotateEnabled = false;
private DaapMediator() {
if (isSupportedPlatform()) {
GUIMediator.addFinalizeListener(this);
}
}
/**
* Initializes the Library
*/
public synchronized void init() {
if (isSupportedPlatform() && isServerRunning()) {
setAnnotateEnabled(annotateEnabled);
}
}
/**
* Starts the DAAP Server
*/
public synchronized void start() throws IOException {
if (isSupportedPlatform() && !isServerRunning()) {
try {
map = new SongURNMap();
library = new Library(DaapSettings.DAAP_LIBRARY_NAME.getValue());
whatsNew = new Playlist(GUIMediator.getStringResource("SEARCH_TYPE_WHATSNEW"));
whatsNew.setSmartPlaylist(true);
library.open();
library.add(whatsNew);
library.close();
updateWorker = new UpdateWorker();
// Reset PORT to default value to prevent increasing
// it to infinity
DaapSettings.DAAP_PORT.revertToDefault();
SimpleConfig config = new SimpleConfig(CommonUtils.getHttpServer(), DaapSettings.DAAP_PORT.getValue());
config.setMaxConnections(DaapSettings.DAAP_MAX_CONNECTIONS.getValue());
final boolean NIO = DaapSettings.DAAP_USE_NIO.getValue();
server = DaapServerFactory.createServer(library, config, NIO);
server.setAuthenticator(new LimeAuthenticator());
server.setStreamSource(new LimeStreamSource());
server.setFilter(new LimeFilter());
if (!NIO) {
server.setThreadFactory(new LimeThreadFactory());
}
final int maxAttempts = 10;
for(int i = 0; i < maxAttempts; i++) {
try {
server.bind();
break;
} catch (BindException bindErr) {
if (i < (maxAttempts-1)) {
// try next port...
int port = DaapSettings.DAAP_PORT.getValue()+1;
config.setInetSocketAddress(port);
DaapSettings.DAAP_PORT.setValue(port);
} else {
throw bindErr;
}
}
}
Thread serverThread = new ManagedThread(server, "DaapServerThread");
serverThread.setDaemon(true);
serverThread.start();
Thread updateWorkerThread = new ManagedThread(updateWorker, "UpdateWorkerThread");
updateWorkerThread.setDaemon(true);
updateWorkerThread.setPriority(Thread.MIN_PRIORITY+2);
updateWorkerThread.start();
rendezvous = new RendezvousService();
rendezvous.registerService();
} catch (IOException err) {
stop();
throw err;
}
}
}
/**
* Stops the DAAP Server and releases all resources
*/
public synchronized void stop() {
if (isSupportedPlatform()) {
if (updateWorker != null)
updateWorker.stop();
if (rendezvous != null)
rendezvous.close();
if (server != null)
server.stop();
if (map != null)
map.clear();
rendezvous = null;
server = null;
updateWorker = null;
map = null;
library = null;
whatsNew = null;
}
}
/**
* Restarts the DAAP server and re-registers it via mDNS.
* This is equivalent to:<p>
*
* <code>
* stop();
* start();
* init();
* </code>
*/
public synchronized void restart() throws IOException {
if (isSupportedPlatform()) {
if (isServerRunning())
stop();
start();
init();
}
}
/**
* Shutdown the DAAP service properly. In this case
* is the main focus on mDNS (Rendezvous) as in
* some rare cases iTunes doesn't recognize that
* LimeWire/DAAP is no longer online.
*/
public void doFinalize() {
stop();
}
/**
* Updates the multicast-DNS servive info
*/
public synchronized void updateService() throws IOException {
if (isSupportedPlatform() && isServerRunning()) {
rendezvous.updateService();
updateWorker.setName(DaapSettings.DAAP_LIBRARY_NAME.getValue());
}
}
/**
* Disconnects all clients
*/
public synchronized void disconnectAll() {
if (isSupportedPlatform() && isServerRunning()) {
server.disconnectAll();
}
}
/**
* Returns <tt>true</tt> if server is running
*/
public synchronized boolean isServerRunning() {
if (server != null) {
return server.isRunning();
}
return false;
}
/**
* A helper method.
*/
private static boolean isSupportedPlatform() {
return CommonUtils.isJava14OrLater();
}
/**
* Returns true if the extension of name is a supported file type.
*/
private static boolean isSupportedFormat(String name) {
String[] types = DaapSettings.DAAP_SUPPORTED_FILE_TYPES.getValue();
for(int i = 0; i < types.length; i++) {
if (name.endsWith(types[i])) {
return true;
}
}
return false;
}
/**
* Called by VisualConnectionCallback
*/
public void handleFileManagerEvent(FileManagerEvent evt) {
if (isSupportedPlatform() && isServerRunning()) {
if (evt.isChangeEvent()) {
FileDesc oldDesc = evt.getFileDesc()[0];
Song song = map.remove(oldDesc.getSHA1Urn());
if (song != null) {
FileDesc newDesc = evt.getFileDesc()[1];
map.put(song, newDesc.getSHA1Urn());
String format = song.getFormat();
// Any changes in the meta data?
if ( updateSongMeta(song, newDesc) ) {
updateWorker.update(song);
}
}
} else if (evt.isAddEvent()) {
FileDesc file = evt.getFileDesc()[0];
if (!(file instanceof IncompleteFileDesc)) {
String name = file.getName().toLowerCase(Locale.US);
if (isSupportedFormat(name)) {
Song song = createSong(file);
map.put(song, file.getSHA1Urn());
updateWorker.add(song, true);
}
}
} else if (evt.isRenameEvent()) {
FileDesc oldDesc = evt.getFileDesc()[0];
Song song = map.remove(oldDesc.getSHA1Urn());
if (song != null) {
FileDesc newDesc = evt.getFileDesc()[1];
map.put(song, newDesc.getSHA1Urn());
}
} else if (evt.isRemoveEvent()) {
FileDesc file = evt.getFileDesc()[0];
Song song = map.remove(file.getSHA1Urn());
if (song != null) {
updateWorker.remove(song);
}
}
}
}
/**
* Called by VisualConnectionCallback/MetaFileManager.
*/
public synchronized void setAnnotateEnabled(boolean enabled) {
this.annotateEnabled = enabled;
if (isSupportedPlatform() && isServerRunning() && enabled) {
// disable updateWorker
updateWorker.setEnabled(false);
SongURNMap tmpMap = new SongURNMap();
FileDesc[] files = RouterService.getFileManager().getAllSharedFileDescriptors();
for(int i = 0; i < files.length; i++) {
FileDesc file = files[i];
if (!(file instanceof IncompleteFileDesc)) {
String name = file.getName().toLowerCase(Locale.US);
if (isSupportedFormat(name)) {
URN urn = file.getSHA1Urn();
// _Remove_ URN from the current 'map'...
Song song = map.remove(urn);
// Check if URN is already in the tmpMap.
// If so do nothing as we don't want add
// the same file multible times...
if (tmpMap.contains(urn) == false) {
// This URN was already mapped with a Song.
// Save the Song (again) and update the meta
// data if necessary
if (song != null) {
tmpMap.put(song, urn);
// Any changes in the meta data?
if ( updateSongMeta(song, file) ) {
updateWorker.update(song);
}
} else {
// URN was unknown and we must create a
// new Song for this URN...
song = createSong(file);
tmpMap.put(song, urn);
updateWorker.add(song, false);
}
}
}
}
}
// See 1)
// As all known URNs were removed from 'map' and only
// deleted FileDesc URNs can be leftover and we
// must remove the associated Songs from the Library
Iterator it = map.getSongIterator();
while(it.hasNext()) {
Song song = (Song)it.next();
updateWorker.remove(song);
}
map.clear();
map = tmpMap; // tempMap is the new 'map'
// enable updateWorker
updateWorker.setEnabled(true);
}
}
/**
* Create a Song and sets its meta data with
* the data which is retrieved from the FileDesc
*/
private Song createSong(FileDesc desc) {
Song song = new Song(desc.getName());
song.setSize((int)desc.getSize());
song.setDateAdded((int)(System.currentTimeMillis()/1000));
File file = desc.getFile();
String ext = FileUtils.getFileExtension(file);
if (ext != null) {
// Note: This is required for formats other than MP3
// For example AAC (.m4a) files won't play if no
// format is set. As far as I can tell from the iTunes
// 'Get Info' dialog are Songs assumed as MP3 until
// a format is set explicit.
song.setFormat(ext.toLowerCase(Locale.US));
updateSongMeta(song, desc);
}
return song;
}
/**
* Sets the meta data
*/
private boolean updateSongMeta(Song song, FileDesc desc) {
SchemaReplyCollectionMapper map = SchemaReplyCollectionMapper.instance();
LimeXMLReplyCollection collection = map.getReplyCollection(AUDIO_SCHEMA);
LimeXMLDocument doc = collection.getDocForHash(desc.getSHA1Urn());
if (doc == null)
return false;
boolean update = false;
String title = doc.getValue("audios__audio__title__");
String track = doc.getValue("audios__audio__track__");
String artist = doc.getValue("audios__audio__artist__");
String album = doc.getValue("audios__audio__album__");
String genre = doc.getValue("audios__audio__genre__");
String bitrate = doc.getValue("audios__audio__bitrate__");
String comments = doc.getValue("audios__audio__comments__");
String time = doc.getValue("audios__audio__seconds__");
String year = doc.getValue("audios__audio__year__");
if (title != null) {
String currentTitle = song.getName();
if (currentTitle == null || !title.equals(currentTitle)) {
update = true;
song.setName(title);
}
}
int currentTrack = song.getTrackNumber();
if (track != null) {
try {
int num = Integer.parseInt(track);
if (num > 0 && num != currentTrack) {
update = true;
song.setTrackNumber(num);
}
} catch (NumberFormatException err) {}
} else if (currentTrack != 0) {
update = true;
song.setTrackNumber(0);
}
String currentArtist = song.getArtist();
if (artist != null) {
if (currentArtist == null || !artist.equals(currentArtist)) {
update = true;
song.setArtist(artist);
}
} else if (currentArtist != null) {
update = true;
song.setArtist(null);
}
String currentAlbum = song.getAlbum();
if (album != null) {
if (currentAlbum == null || !album.equals(currentAlbum)) {
update = true;
song.setAlbum(album);
}
} else if (currentAlbum != null) {
update = true;
song.setAlbum(null);
}
String currentGenre = song.getGenre();
if (genre != null) {
if (currentGenre == null || !genre.equals(currentGenre)) {
update = true;
song.setGenre(genre);
}
} else if (currentGenre != null) {
update = true;
song.setGenre(null);
}
String currentComments = song.getComment();
if (comments != null) {
if (currentComments == null || !comments.equals(currentComments)) {
update = true;
song.setComment(comments);
}
} else if (currentComments != null) {
update = true;
song.setComment(null);
}
int currentBitrate = song.getBitrate();
if (bitrate != null) {
try {
int num = Integer.parseInt(bitrate);
if (num > 0 && num != currentBitrate) {
update = true;
song.setBitrate(num);
}
} catch (NumberFormatException err) {}
} else if (currentBitrate != 0) {
update = true;
song.setBitrate(0);
}
int currentTime = song.getTime();
if (time != null) {
try {
// iTunes expects the song length in milli seconds
int num = (int)Integer.parseInt(time)*1000;
if (num > 0 && num != currentTime) {
update = true;
song.setTime(num);
}
} catch (NumberFormatException err) {}
} else if (currentTime != 0) {
update = true;
song.setTime(0);
}
int currentYear = song.getYear();
if (year != null) {
try {
int num = Integer.parseInt(year);
if (num > 0 && num != currentYear) {
update = true;
song.setYear(num);
}
} catch (NumberFormatException err) {}
} else if (currentYear != 0) {
update = true;
song.setYear(0);
}
// iTunes expects the date/time in seconds
int mod = (int)(desc.lastModified()/1000);
if (song.getDateModified() != mod) {
update = true;
song.setDateModified(mod);
}
return update;
}
private final class LimeThreadFactory implements DaapThreadFactory {
public LimeThreadFactory() {
}
public Thread createDaapThread(Runnable runner, String name) {
Thread thread = new ManagedThread(runner, name);
thread.setDaemon(true);
return thread;
}
}
/**
* Handles the audio stream
*/
private final class LimeStreamSource implements DaapStreamSource {
public LimeStreamSource() {
}
public FileInputStream getSource(Song song) throws IOException {
URN urn = map.get(song);
if (urn != null) {
FileDesc fileDesc = RouterService.getFileManager().getFileDescForUrn(urn);
if (fileDesc != null) {
File file = fileDesc.getFile();
FileInputStream in = new FileInputStream(file);
return in;
}
}
return null;
}
}
/**
* Implements the DaapAuthenticator
*/
private final class LimeAuthenticator implements DaapAuthenticator {
public LimeAuthenticator() {
}
public boolean requiresAuthentication() {
return DaapSettings.DAAP_REQUIRES_PASSWORD.getValue();
}
/**
* Returns true if username and password are correct.<p>
* Note: iTunes does not support usernames (i.e. it's
* don't care)!
*/
public boolean authenticate(String username, String password) {
return password.equals(DaapSettings.DAAP_PASSWORD.getValue());
}
}
/**
* The DAAP Library should be only accessable from the LAN
* as we can not guarantee for the required bandwidth and it
* could be used to bypass Gnutella etc. Note: iTunes can't
* connect to DAAP Libraries outside of the LAN but certain
* iTunes download tools can.
*/
private final class LimeFilter implements DaapFilter {
public LimeFilter() {
}
/**
* Returns true if <tt>address</tt> is a private address
*/
public boolean accept(InetAddress address) {
try {
// Is address a private address?
if ( ! NetworkUtils.isPrivateAddress(address))
return false;
} catch (IllegalArgumentException err) {
LOG.error(err);
return false;
}
// Is it a annoying fellow? >:-)
return IPFilter.instance().allow(address.getAddress());
}
}
/**
* Helps us to publicize and update the DAAP Service via
* multicast-DNS (aka Rendezvous or Zeroconf)
*/
private final class RendezvousService {
private static final String VERSION = "Version";
private static final String MACHINE_NAME = "Machine Name";
private static final String PASSWORD = "Password";
private JmDNS zeroConf;
private ServiceInfo service;
public RendezvousService() throws IOException {
zeroConf = new JmDNS();
}
public boolean isRegistered() {
return (service != null);
}
private ServiceInfo createServiceInfo() {
String type = DaapSettings.DAAP_TYPE_NAME.getValue();
String name = DaapSettings.DAAP_SERVICE_NAME.getValue();
int port = DaapSettings.DAAP_PORT.getValue();
int weight = DaapSettings.DAAP_WEIGHT.getValue();
int priority = DaapSettings.DAAP_PRIORITY.getValue();
boolean password = DaapSettings.DAAP_REQUIRES_PASSWORD.getValue();
java.util.Hashtable props = new java.util.Hashtable();
// Greys the share and the playlist names when iTunes's
// protocol version is different from this version. It's
// only a nice visual effect and has no impact to the
// ability to connect this server! Disabled because
// iTunes 4.2 is still widespread...
//props.put(VERSION, Integer.toString(DaapUtil.VERSION_3));
// This is the inital share name
props.put(MACHINE_NAME, name);
// shows the small lock if Service is protected
// by a password!
props.put(PASSWORD, Boolean.toString(password));
String qualifiedName = null;
// This isn't really required but as iTunes
// does it in this way I'm doing it too...
if (password) {
qualifiedName = name + "_PW." + type;
} else {
qualifiedName = name + "." + type;
}
ServiceInfo service = new ServiceInfo(type, qualifiedName, port,
weight, priority, props);
return service;
}
public void registerService() throws IOException {
if (isRegistered())
throw new IOException();
ServiceInfo service = createServiceInfo();
zeroConf.registerService(service);
this.service = service;
}
public void unregisterService() {
if (!isRegistered())
return;
zeroConf.unregisterService(service);
service = null;
}
public void updateService() throws IOException {
if (!isRegistered())
throw new IOException();
if (service.getPort() != DaapSettings.DAAP_PORT.getValue())
unregisterService();
ServiceInfo service = createServiceInfo();
zeroConf.registerService(service);
this.service = service;
}
public void close() {
unregisterService();
zeroConf.close();
}
}
/**
* The job of UpdateWorker is to collect Library operations
* and to perform them as one single operation on the Library.
* This reduces the overall network/cpu load to notify the
* clients about the changes and reduces the risk to run out
* of revisions in principle to zero.
*/
private final class UpdateWorker implements Runnable {
private static final int SLEEP = 5*1000; // 5 seconds
private final Object LOCK = new Object();
private String name = null;
private HashMap /* of Song -> Boolean */ add = new HashMap();
private HashSet /* of Song */ remove = new HashSet();
private HashSet /* of Song */ update = new HashSet();
private boolean running = false;
private boolean enabled = true;
public UpdateWorker() {
}
public void setName(String name) {
synchronized(LOCK) {
this.name = name;
}
}
public void add(Song song, boolean isNew) {
synchronized(LOCK) {
add.put(song, new Boolean(isNew));
remove.remove(song);
update.remove(song);
}
}
public void remove(Song song) {
synchronized(LOCK) {
remove.add(song);
add.remove(song);
update.remove(song);
}
}
public void update(Song song) {
synchronized(LOCK) {
if (!add.containsKey(song) &&
!remove.contains(song)) {
update.add(song);
}
}
}
public void run() {
running = true;
try {
do {
Thread.sleep(SLEEP);
if (running && enabled) {
boolean extraSleep = false;
synchronized(LOCK) {
if (add.size() != 0 ||
remove.size() != 0 ||
update.size() != 0 ||
name != null) {
synchronized(library) {
library.open();
if (name != null) {
library.setName(name);
name = null;
}
// It makes no sense to remove or update
// songs if Library is empty...
if (library.size() != 0) {
Iterator it = remove.iterator();
while(it.hasNext() && running) {
library.remove((Song)it.next());
}
it = update.iterator();
while(it.hasNext() && running) {
((Song)it.next()).update();
}
}
final int MAX_SIZE = DaapSettings.DAAP_MAX_LIBRARY_SIZE.getValue();
Iterator it = add.keySet().iterator();
while(it.hasNext() && running && library.size() < MAX_SIZE) {
Song song = (Song)it.next();
Boolean bool = (Boolean)add.get(song);
if (bool.booleanValue()) {
// add to What's New playlist
whatsNew.add(song);
} else {
// add to master playlist
library.add(song);
}
}
library.close();
}
if (running)
server.update();
add.clear();
remove.clear();
update.clear();
// OK, we've updated the Library
// Let's take an additional sleep
if (running)
extraSleep = true;
}
}
if (extraSleep && running)
Thread.sleep(SLEEP);
}
} while(running);
} catch (InterruptedException err) {
} finally {
stop();
}
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isRunning() {
return running;
}
public void clear() {
synchronized(LOCK) {
add.clear();
remove.clear();
update.clear();
name = null;
}
}
public void stop() {
running = false;
clear();
}
}
/**
* A simple wrapper for a two way mapping as we have to
* deal in both directions with FileManager and DaapServer
* <p>
* Song -> URN
* URN -> Song
*/
private final class SongURNMap {
private HashMap /* Song -> URN */ songToUrn = new HashMap();
private HashMap /* URN -> Song */ urnToSong = new HashMap();
public SongURNMap() {
}
public void put(Song song, URN urn) {
songToUrn.put(song, urn);
urnToSong.put(urn, song);
}
public URN get(Song song) {
return (URN)songToUrn.get(song);
}
public Song get(URN urn) {
return (Song)urnToSong.get(urn);
}
public Song remove(URN urn) {
Song song = (Song)urnToSong.remove(urn);
if (song != null)
songToUrn.remove(song);
return song;
}
public URN remove(Song song) {
URN urn = (URN)songToUrn.remove(song);
if (urn != null)
urnToSong.remove(urn);
return urn;
}
public boolean contains(URN urn) {
return urnToSong.containsKey(urn);
}
public boolean contains(Song song) {
return songToUrn.containsKey(song);
}
public Iterator getSongIterator() {
return songToUrn.keySet().iterator();
}
public Iterator getURNIterator() {
return urnToSong.keySet().iterator();
}
public void clear() {
urnToSong.clear();
songToUrn.clear();
}
public int size() {
// NOTE: songToUrn.size() == urnToSong.size()
return songToUrn.size();
}
}
}
|
package org.opencb.opencga.server.ws;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.opencb.cellbase.core.lib.dbquery.DBObjectMap;
import org.opencb.cellbase.core.lib.dbquery.QueryResult;
import org.opencb.opencga.lib.common.Config;
import org.opencb.opencga.lib.common.StringUtils;
import org.opencb.opencga.lib.common.networks.Layout;
import org.opencb.opencga.lib.common.networks.Layout.LayoutResp;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
@Path("/utils")
public class UtilsWSServer extends GenericWSServer {
Layout layout;
public UtilsWSServer(@Context UriInfo uriInfo,
@Context HttpServletRequest httpServletRequest) throws IOException {
super(uriInfo, httpServletRequest);
layout = new Layout();
}
// @GET
// @Path("/job_status")
// public Response indexStatus(@DefaultValue("") @QueryParam("jobId") String jobId) throws Exception {
// try {
// return createOkResponse(SgeManager.status(jobId));
// } catch (Exception e) {
// logger.error(e.toString());
// return createErrorResponse("job id not found.");
@POST
@Path("/network/layout/{algorithm}.{format}")
public Response layout(@PathParam("algorithm") String layoutAlgorithm, @PathParam("format") String outputFormat, @FormParam("dot") String dotData, @DefaultValue("output") @FormParam("filename") String filename, @DefaultValue("false") @FormParam("base64") String base64, @FormParam("jsonp") String jsonpCallback) {
LayoutResp resp = layout.layout(layoutAlgorithm, outputFormat, dotData, filename, base64, jsonpCallback);
return processResp(resp);
}
@POST
@Path("/network/layout/{algorithm}.coords")
public Response coordinates(@PathParam("algorithm") String layoutAlgorithm, @FormParam("dot") String dotData, @FormParam("jsonp") String jsonpCallback) {
LayoutResp resp = layout.coordinates(layoutAlgorithm, dotData, jsonpCallback);
return processResp(resp);
}
private Response processResp(LayoutResp resp) {
MediaType type;
if (resp.getType().equals("json")) {
type = MediaType.APPLICATION_JSON_TYPE;
if (resp.getFileName() == null) {
return createOkResponse((String) resp.getData(), type);
} else {
return createOkResponse((String) resp.getData(), type, resp.getFileName());
}
} else if (resp.getType().equals("bytes")) {
type = MediaType.APPLICATION_OCTET_STREAM_TYPE;
if (resp.getFileName() == null) {
return createOkResponse((byte[]) resp.getData(), type);
} else {
return createOkResponse((byte[]) resp.getData(), type, resp.getFileName());
}
} else {
type = MediaType.TEXT_PLAIN_TYPE;
if (resp.getFileName() == null) {
return createOkResponse((String) resp.getData(), type);
} else {
return createOkResponse((String) resp.getData(), type, resp.getFileName());
}
}
}
@GET
@Path("/test/{message}")
public Response etest(@PathParam("message") String message) {
logger.info(sessionId);
logger.info(of);
return createOkResponse(message);
}
@POST
@Path("/network/community")
public Response community(@FormParam("sif") String sifData,
@DefaultValue("F") @FormParam("directed") String directed,
@DefaultValue("F") @FormParam("weighted") String weighted,
@DefaultValue("infomap") @FormParam("method") String method) throws IOException {
String home = Config.getGcsaHome();
Properties analysisProperties = Config.getAnalysisProperties();
Properties accountProperties = Config.getAccountProperties();
String scriptName = "communities-structure-detection";
java.nio.file.Path scriptPath = Paths.get(home, analysisProperties.getProperty("OPENCGA.ANALYSIS.BINARIES.PATH"), scriptName, scriptName + ".r");
// creating a random tmp folder
String rndStr = StringUtils.randomString(20);
java.nio.file.Path randomFolder = Paths.get(accountProperties.getProperty("OPENCGA.TMP.PATH"), rndStr);
Files.createDirectory(randomFolder);
java.nio.file.Path inFilePath = randomFolder.resolve("file.sif");
java.nio.file.Path outFilePath = randomFolder.resolve("result.comm");
Files.write(inFilePath, sifData.getBytes(), StandardOpenOption.CREATE_NEW);
String command = "Rscript " + scriptPath.toString() + " " + method + " " + directed + " " + weighted + " " + inFilePath.toString() + " " + randomFolder.toString() + "/";
logger.info(command);
String result = "error";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
int exitValue = process.exitValue();
BufferedReader br = Files.newBufferedReader(outFilePath, Charset.defaultCharset());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
result = sb.toString();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return createOkResponse(result);
}
@POST
@Path("/network/topological-study")
public Response topology(@FormParam("sif") String sifData,
@DefaultValue("F") @FormParam("directed") String directed,
@DefaultValue("F") @FormParam("weighted") String weighted) throws IOException {
String home = Config.getGcsaHome();
Properties analysisProperties = Config.getAnalysisProperties();
Properties accountProperties = Config.getAccountProperties();
String scriptName = "topological-study";
java.nio.file.Path scriptPath = Paths.get(home, analysisProperties.getProperty("OPENCGA.ANALYSIS.BINARIES.PATH"), scriptName, scriptName + ".r");
// creating a random tmp folder
String rndStr = StringUtils.randomString(20);
java.nio.file.Path randomFolder = Paths.get(accountProperties.getProperty("OPENCGA.TMP.PATH"), rndStr);
Files.createDirectory(randomFolder);
java.nio.file.Path inFilePath = randomFolder.resolve("file.sif");
java.nio.file.Path outFilePath = randomFolder.resolve("result.local");
java.nio.file.Path outFilePath2 = randomFolder.resolve("result.global.json");
Files.write(inFilePath, sifData.getBytes(), StandardOpenOption.CREATE_NEW);
String command = "Rscript " + scriptPath.toString() + " " + directed + " " + weighted + " " + inFilePath.toString() + " " + randomFolder.toString() + "/";
logger.info(command);
DBObjectMap result = new DBObjectMap();
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
int exitValue = process.exitValue();
BufferedReader br = Files.newBufferedReader(outFilePath, Charset.defaultCharset());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
result.put("local", sb.toString());
br = Files.newBufferedReader(outFilePath2, Charset.defaultCharset());
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jp = factory.createParser(br);
JsonNode jsonNode = mapper.readTree(jp);
result.put("global", jsonNode);
br.close();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
result.put("error", "could not read result files");
}
return createOkResponse(result);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.