answer
stringlengths 17
10.2M
|
|---|
/*
* JsonGeneratorVisitor.java
*
*/
package de.uni_stuttgart.vis.vowl.owl2vowl.export;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Standard_Iris;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.data.VowlData;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.annotation.Annotation;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.VowlClass;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.VowlThing;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.VowlDatatype;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.VowlLiteral;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.properties.VowlDatatypeProperty;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.properties.VowlObjectProperty;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.semanticweb.owlapi.model.IRI;
import java.util.*;
import java.util.stream.Collectors;
/**
* TODO Gemeinsamkeiten auslagern
*/
public class JsonGeneratorVisitorImpl implements JsonGeneratorVisitor {
private final VowlData vowlData;
private final Map<String, Object> root;
private Map<String, Object> header;
private Map<String, Object> metrics;
private List<Object> namespace;
private List<Object> _class;
private List<Object> classAttribute;
private List<Object> datatype;
private List<Object> datatypeAttribute;
private List<Object> objectProperty;
private List<Object> objectPropertyAttribute;
private Logger logger = LogManager.getLogger(JsonGeneratorVisitorImpl.class);
public JsonGeneratorVisitorImpl(VowlData vowlData, Map<String, Object> root) {
this.vowlData = vowlData;
this.root = root;
populateJsonRoot();
}
protected void populateJsonRoot() {
header = new LinkedHashMap<>();
metrics = new LinkedHashMap<>();
namespace = new ArrayList<>();
_class = new ArrayList<>();
classAttribute = new ArrayList<>();
datatype = new ArrayList<>();
datatypeAttribute = new ArrayList<>();
objectProperty = new ArrayList<>();
objectPropertyAttribute = new ArrayList<>();
root.put("header", header);
root.put("namespace", namespace);
root.put("metrics", metrics);
root.put("class", _class);
root.put("classAttribute", classAttribute);
root.put("datatype", datatype);
root.put("datatypeAttribute", datatypeAttribute);
root.put("property", objectProperty);
root.put("propertyAttribute", objectPropertyAttribute);
namespace.add(new HashMap<>());
}
@Override
public void visit(VowlThing vowlThing) {
Map<String, Object> thingObject = new HashMap<>();
thingObject.put("id", vowlData.getIdForEntity(vowlThing));
thingObject.put("type", vowlThing.getType());
_class.add(thingObject);
Map<String, Object> thingAttributeObject = new HashMap<>();
// TODO
thingAttributeObject.put("id", vowlData.getIdForEntity(vowlThing));
thingAttributeObject.put("label", 0);
thingAttributeObject.put("iri", Standard_Iris.OWL_THING_CLASS_URI);
classAttribute.add(thingAttributeObject);
}
@Override
public void visit(VowlClass vowlClass) {
Map<String, Object> classObject = new HashMap<>();
classObject.put("id", vowlData.getIdForEntity(vowlClass));
classObject.put("type", vowlClass.getType());
_class.add(classObject);
Map<String, Object> classAttributeObject = new HashMap<>();
// TODO
classAttributeObject.put("id", vowlData.getIdForEntity(vowlClass));
classAttributeObject.put("label", getLabelsFromAnnotations(vowlClass.getAnnotations().getLabels()));
classAttributeObject.put("iri", vowlClass.getIri().toString());
classAttributeObject.put("description", getLabelsFromAnnotations(vowlClass.getAnnotations().getDescription()));
classAttributeObject.put("comment", getLabelsFromAnnotations(vowlClass.getAnnotations().getComments()));
classAttributeObject.put("isDefinedBy", 0);
classAttributeObject.put("owlVersion", 0);
classAttributeObject.put("attributes", 0);
classAttributeObject.put("superClasses", getListWithIds(vowlClass.getSuperEntities()));
classAttributeObject.put("subClasses", getListWithIds(vowlClass.getSubEntities()));
classAttributeObject.put("annotations", vowlClass.getAnnotations().getIdentifierToAnnotation());
classAttributeObject.put("union", getListWithIds(vowlClass.getElementsOfUnion()));
classAttributeObject.put("intersection", getListWithIds(vowlClass.getElementOfIntersection()));
classAttributeObject.put("attributes", vowlClass.getAttributes());
classAttributeObject.put("equivalent", getListWithIds(vowlClass.getEquivalentElements()));
// TODO can a complement not be a list?
//lassAttributeObject.put("complement", 0);
classAttribute.add(classAttributeObject);
}
@Override
public void visit(VowlLiteral vowlLiteral) {
Map<String, Object> object = new HashMap<>();
//object.put("id", vowlData.getIdForEntity(vowlLiteral));
//object.put("type", vowlLiteral.getType());
datatype.add(object);
}
@Override
public void visit(VowlDatatype vowlDatatype) {
Map<String, Object> object = new HashMap<>();
//object.put("id", vowlData.getIdForEntity(vowlDatatype));
//object.put("type", vowlDatatype.getType());
datatype.add(object);
}
@Override
public void visit(VowlObjectProperty vowlObjectProperty) {
if (vowlObjectProperty.getDomain() == null || vowlObjectProperty.getRange() == null) {
logger.info("Domain or range is null in object property: " + vowlObjectProperty);
return;
}
Map<String, Object> object = new HashMap<>();
object.put("id", vowlData.getIdForEntity(vowlObjectProperty));
object.put("type", vowlObjectProperty.getType());
objectProperty.add(object);
Map<String, Object> propertyAttributes = new HashMap<>();
propertyAttributes.put("domain", vowlData.getIdForIri(vowlObjectProperty.getDomain()));
propertyAttributes.put("range", vowlData.getIdForIri(vowlObjectProperty.getRange()));
propertyAttributes.put("id", vowlData.getIdForEntity(vowlObjectProperty));
propertyAttributes.put("label", getLabelsFromAnnotations(vowlObjectProperty.getAnnotations().getLabels()));
propertyAttributes.put("iri", vowlObjectProperty.getIri().toString());
propertyAttributes.put("description", getLabelsFromAnnotations(vowlObjectProperty.getAnnotations().getDescription()));
propertyAttributes.put("comment", getLabelsFromAnnotations(vowlObjectProperty.getAnnotations().getComments()));
propertyAttributes.put("attributes", vowlObjectProperty.getAttributes());
propertyAttributes.put("annotations", vowlObjectProperty.getAnnotations().getIdentifierToAnnotation());
propertyAttributes.put("inverse", getIdForIri(vowlObjectProperty.getInverse()));
propertyAttributes.put("superproperty", getListWithIds(vowlObjectProperty.getSuperEntities()));
propertyAttributes.put("subproperty", getListWithIds(vowlObjectProperty.getSubEntities()));
propertyAttributes.put("equivalent", getListWithIds(vowlObjectProperty.getEquivalentElements()));
propertyAttributes.put("minCardinality", getCardinality(vowlObjectProperty.getMinCardinality()));
propertyAttributes.put("maxCardinality", getCardinality(vowlObjectProperty.getMaxCardinality()));
propertyAttributes.put("cardinality", getCardinality(vowlObjectProperty.getExactCardinality()));
objectPropertyAttribute.add(propertyAttributes);
}
@Override
public void visit(VowlDatatypeProperty vowlDatatypeProperty) {
Map<String, Object> object = new HashMap<>();
//object.put("id", vowlData.getIdForEntity(vowlDatatypeProperty));
//object.put("type", vowlDatatypeProperty.getType());
objectProperty.add(object);
}
protected List<String> getListWithIds(Collection<IRI> iriList) {
List<String> idList = iriList.stream().map(iri -> String.valueOf(vowlData.getIdForIri(iri))).collect(Collectors.toList());
return idList;
}
protected String getIdForIri(IRI iri) {
if (iri == null) {
return null;
}
return vowlData.getIdForIri(iri);
}
protected Map<String, String> getLabelsFromAnnotations(Collection<Annotation> annotations) {
Map<String, String> languageToValue = new HashMap<>();
for (Annotation annotation : annotations) {
languageToValue.put(annotation.getLanguage(), annotation.getValue());
}
return languageToValue;
}
/**
*
* @return Empty string if value is <= 0 else the value.
*/
protected String getCardinality(Integer value) {
if (value <= 0) {
return StringUtils.EMPTY;
}
return value.toString();
}
}
|
package de.unibremen.opensores.controller.tutorial;
import de.unibremen.opensores.model.Course;
import de.unibremen.opensores.model.Log;
import de.unibremen.opensores.model.Role;
import de.unibremen.opensores.model.Tutorial;
import de.unibremen.opensores.model.TutorialEvent;
import de.unibremen.opensores.model.User;
import de.unibremen.opensores.service.CourseService;
import de.unibremen.opensores.service.LogService;
import de.unibremen.opensores.service.TutorialService;
import de.unibremen.opensores.service.UserService;
import de.unibremen.opensores.util.Constants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.TimeZone;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The controller for managing tutorial events.
* @author Kevin Scheck.
*/
@ManagedBean
@ViewScoped
public class TutorialEventController {
/**
* The log4j logger for debug, errors logs from log4j.
* These logs are not related to actions in the exmatrikulator business domain.
*/
private static Logger log = LogManager.getLogger(TutorialEventController.class);
/**
* The tutorial which events get edited.
*/
private Tutorial tutorial;
/**
* The course in which the tutorial is located.
*/
private Course course;
/**
* The currently logged in user user the page backed by this bean.
*/
private User loggedInUser;
/**
* The LogService for adding logs related to the exmatrikulator actions.
*/
private LogService logService;
/**
* The TutorialService for database transactions related to tutorials.
*/
private TutorialService tutorialService;
/**
* The CourseService for database transactions related to courses.
*/
private CourseService courseService;
/**
* The UserService for database transactions related to users.
*/
private UserService userService;
/**
* The schedule model used by PrimeFaces for managing tutorial events.
*/
private ScheduleModel tutorialEventModel;
/**
* The currently selected tutorial event.
*/
private TutorialEvent event;
/**
* A list of users which get notified by mail that a tutorialEvent has changed.
* Includes all tutors and students from the tutorial excluding the logged in user.
*/
private List<User> mailList;
/**
* Boolean value whether the logged in user is a tutor in the tutorial.
*/
private boolean isUserTutor;
/**
* Boolean value whether the loged in user is a lecturer in the tutorial.
*/
private boolean isUserLecturer;
/**
* The old start date of a selected event.
*/
private Date oldEventStartDate;
/**
* The old end date of a selected event.
*/
private Date oldEventEndDate;
/**
* Formats the dates of tutEvents to the timezone of the exmatrikulator.
*/
private SimpleDateFormat dateFormatter;
/**
* Initialises the bean and gets the related tutorial.
*/
@PostConstruct
public void init() {
log.debug("init() called");
if (tutorialEventModel == null) {
tutorialEventModel = new DefaultScheduleModel();
}
HttpServletRequest req =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
course = courseService.findCourseById(
req.getParameter(Constants.HTTP_PARAM_COURSE_ID));
tutorial = tutorialService.findTutorialById(
req.getParameter(Constants.HTTP_PARAM_TUTORIAL_ID));
log.debug("Course: " + course);
log.debug("Tutorial: " + tutorial);
boolean validationPassed = false;
try {
loggedInUser = (User) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get(Constants.SESSION_MAP_KEY_USER);
} catch (ClassCastException e) {
log.error(e);
}
log.debug("Logged in User: " + loggedInUser);
if (course != null && tutorial != null && loggedInUser != null
&& course.getTutorials().contains(tutorial)) {
isUserLecturer = userService.hasCourseRole(loggedInUser,
Role.LECTURER.name(), course);
log.debug("Checking if user is tutor");
isUserTutor = tutorialService.getTutorOf(tutorial, loggedInUser) != null;
log.debug("User is tutor: " + isUserTutor);
validationPassed = isUserLecturer || isUserTutor
|| tutorialService.getStudentOf(tutorial, loggedInUser) != null;
}
if (!validationPassed) {
log.debug("Validation hasn't passed");
try {
FacesContext.getCurrentInstance()
.getExternalContext().redirect(FacesContext
.getCurrentInstance().getExternalContext()
.getApplicationContextPath() + Constants.PATH_TO_COURSE_OVERVIEW);
return;
} catch (IOException e) {
e.printStackTrace();
log.fatal("Could not redirect to " + Constants.PATH_TO_COURSE_OVERVIEW);
return;
}
}
mailList = getMailList();
for (TutorialEvent event: tutorial.getEvents()) {
if (isUserTutor && loggedInUser.getUserId() == event.getCreatorId()) {
event.setEditable(true);
}
tutorialEventModel.addEvent(event);
}
dateFormatter = new SimpleDateFormat("dd.MM.yyyy' 'HH:mm");
dateFormatter.setTimeZone(TimeZone.getTimeZone(Constants.SYSTEM_TIMEZONE));
}
/**
* Adds a new event to the tutorial event.
* @param actionEvent The actionEvent triggered by the PrimeFaces scheduler.
*/
public void addEvent(ActionEvent actionEvent) {
log.debug("addEvent called with " + actionEvent);
if (event.getId() == null) {
tutorialEventModel.addEvent(event);
log.debug("Event gets added");
logEventCreated(event);
} else {
tutorialEventModel.updateEvent(event);
log.debug("Event gets updated");
if (event.getStartDate() != oldEventStartDate
|| event.getEndDate() != oldEventEndDate) {
log.debug("The event dates have changed");
logEventMoved(event);
mailEventMoved(event, oldEventStartDate, oldEventEndDate);
} else {
logEventUpdated(event);
}
}
updateTutorialEvents();
event = new TutorialEvent();
}
/**
* Removes the selected tutorial event.
* @param actionEvent The actionEvent triggered by the PrimeFaces scheduler.
*/
public void removeEvent(ActionEvent actionEvent) {
log.debug("removeEvent called with " + actionEvent);
if (event == null || event.getId() == null) {
log.debug("The PrimeFaces string id of the event is null");
} else if (tutorialEventModel.getEvents().contains(event)) {
log.debug("Removing the event from the EventModel");
tutorialEventModel.deleteEvent(event);
logEventRemoved(event);
}
updateTutorialEvents();
event = new TutorialEvent();
}
/**
* Selects an event to the currently edited event.
* @param selectEvent The selectEvent triggered by the PrimeFaces scheduler.
*/
public void onEventSelect(SelectEvent selectEvent) {
log.debug("onEventSelect called with " + selectEvent);
event = (TutorialEvent) selectEvent.getObject();
oldEventStartDate = event.getStartDate();
oldEventEndDate = event.getEndDate();
}
/**
* Triggered when a date is selected. Creates a new tutorialEvent
* @param selectEvent The selectEvent triggered by the PrimeFaces scheduler.
*/
public void onDateSelect(SelectEvent selectEvent) {
log.debug("onDateSelect called with " + selectEvent);
event = new TutorialEvent(tutorial,
loggedInUser.getUserId(),
(Date) selectEvent.getObject(),
(Date) selectEvent.getObject());
}
/**
* Method triggered when a dialog is cancelled.
*/
public void onDialogCancel() {
log.debug("onDialogCancel() called");
}
/**
* Gets the current locale string.
* @return The current locale string.
*/
public String getLocaleCountry() {
return FacesContext.getCurrentInstance().getViewRoot().getLocale().toLanguageTag();
}
/*
* Private Methods
*/
/**
* Mails to every associated user of the tutorial that an event has been moved.
* @param event The moved event.
*/
private void mailEventMoved(TutorialEvent event, Date oldEventStartDate, Date oldEventEndDate) {
ResourceBundle bundle = ResourceBundle.getBundle("messages",
FacesContext.getCurrentInstance().getViewRoot().getLocale());
String emailFailMessage = bundle.getString("tutEvent.failMessageNoMail");
for (User user: mailList) {
try {
sendEventMoveEvent(user, oldEventStartDate,oldEventEndDate,
event.getStartDate(), event.getEndDate());
} catch (MessagingException | IOException e) {
log.debug(e);
addFailMessage(emailFailMessage);
return;
}
}
}
/**
* Sends a newly registered user an email that they are registered now.
*/
private void sendEventMoveEvent(User user, Date oldStartDate, Date oldEndDate,
Date newStartDate, Date newEndDate)
throws MessagingException, IOException {
String moverName = loggedInUser.getFirstName()
+ loggedInUser.getLastName();
ResourceBundle bundle = ResourceBundle.getBundle("messages",
FacesContext.getCurrentInstance().getViewRoot().getLocale());
String textFormat = bundle.getString("tutEvent.formatMailEventMoved");
String text = new MessageFormat(textFormat).format(new Object[]{
user.getFirstName(), moverName, tutorial.getName(), course.getName(),
dateFormatter.format(oldStartDate), dateFormatter.format(oldEndDate),
dateFormatter.format(newStartDate), dateFormatter.format(newEndDate)
});
String subjectFormat = bundle.getString("tutEvent.subjectMailEventMoved");
String subject = new MessageFormat(subjectFormat).format(new Object[] {
tutorial.getName(), course.getName()
});
user.sendEmail(subject, text);
}
/**
* Logs that an tutorial event has been created.
* @param event The created event.
*/
private void logEventCreated(TutorialEvent event) {
String descr = String.format("Has created a tutorial event from %s to "
+ " %s for the tutorial %s in the course %s.",
event.getStartDate().toString(), event.getEndDate().toString(),
tutorial.getName(), course.getName());
logAction(descr);
}
/**
* Logs that an tutorial event has been removed.
* @param event The removed event.
*/
private void logEventRemoved(TutorialEvent event) {
String descr = String.format("Has removed a tutorial event from %s to "
+ " %s for the tutorial %s in the course %s.",
event.getStartDate().toString(), event.getEndDate().toString(),
tutorial.getName(), course.getName());
logAction(descr);
}
/**
* Logs that an tutorial event has been updated, but the dates havent changed.
* @param event The removed event.
*/
private void logEventUpdated(TutorialEvent event) {
String descr = String.format("Has updated a tutorial event in the tutorial"
+ "%s of the course %s. The dates of the event haven't changed.",
tutorial.getName(), course.getName());
logAction(descr);
}
/**
* Logs that an tutorial event has been moved (the dates of the event have changed).
* @param event The removed event.
*/
private void logEventMoved(TutorialEvent event) {
String descr = String.format("Has moved a tutorial event to the dates from %s to "
+ " %s for the tutorial %s of the course %s."
+ " The old dates were: From %s to %s",
dateFormatter.format(event.getStartDate()),
dateFormatter.format(event.getEndDate()),
tutorial.getName(), course.getName(),
dateFormatter.format(oldEventStartDate),
dateFormatter.format(oldEventEndDate));
logAction(descr);
}
/**
* Adds a fail message to the FacesContext.
* @param message the message to be displayed.
*/
private void addFailMessage(String message) {
ResourceBundle bundle = ResourceBundle.getBundle("messages",
FacesContext.getCurrentInstance().getViewRoot().getLocale());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_FATAL,
bundle.getString("common.error"),
message));
}
/**
* Logs that an action has occured with the logged in user and the selected
* course.
* @param description The description of the action
*/
private void logAction(String description) {
logService.persist(Log.from(loggedInUser, course.getCourseId(), description));
}
/**
* Gets a List of Users which are not the logged in user from the tutorial.
* @return The list of users which are not the logged in user.
*/
private List<User> getMailList() {
return Stream.concat(
tutorial.getStudents().stream().map(student -> student.getUser()),
tutorial.getTutors().stream().map(tutor -> tutor.getUser()))
.filter(user -> !user.equals(loggedInUser))
.collect(Collectors.toList());
}
/**
* Checks whether the logged in user can edit the current event.
* The event can be edited if the user is a tutor and has the same user id
* as the creator id of the event.
* @return True if the user has the rights to edit the tutorial, false otherwise.
*/
public boolean canUserEditEvent() {
return canUserEditEvent(event);
}
/**
* Checks whether the logged in user can edit the current event.
* The event can be edited if the user is a tutor and has the same user id
* as the creator id of the event.
* @param event The tutorial event which should be checked for.
* @return True if the user has the rights to edit the tutorial, false otherwise.
*/
public boolean canUserEditEvent(TutorialEvent event) {
return event != null && (isUserTutor || isUserLecturer)
&& (event.getId() == null
|| loggedInUser.getUserId() == event.getCreatorId());
}
/**
* Updates the events of the tutorial in the database.
*/
private void updateTutorialEvents() {
tutorial.getEvents().clear();
for (ScheduleEvent event: tutorialEventModel.getEvents()) {
TutorialEvent tutEvent = (TutorialEvent) event;
tutEvent.setEditable(false);
tutorial.getEvents().add(tutEvent);
}
tutorial = tutorialService.update(tutorial);
for (ScheduleEvent scheduleEvent: tutorialEventModel.getEvents()) {
TutorialEvent tutEvent = (TutorialEvent) scheduleEvent;
tutEvent.setEditable(canUserEditEvent(tutEvent));
}
}
/*
* Getters and Setters
*/
@EJB
public void setTutorialService(TutorialService tutorialService) {
this.tutorialService = tutorialService;
}
@EJB
public void setLogService(LogService logService) {
this.logService = logService;
}
@EJB
public void setCourseService(CourseService courseService) {
this.courseService = courseService;
}
@EJB
public void setUserService(UserService userService) {
this.userService = userService;
}
public ScheduleModel getTutorialEventModel() {
return tutorialEventModel;
}
public void setTutorialEventModel(ScheduleModel tutorialEventModel) {
this.tutorialEventModel = tutorialEventModel;
}
public User getLoggedInUser() {
return loggedInUser;
}
public Tutorial getTutorial() {
return tutorial;
}
public void setTutorial(Tutorial tutorial) {
this.tutorial = tutorial;
}
public boolean isUserTutor() {
return isUserTutor;
}
public Course getCourse() {
return course;
}
public TutorialEvent getEvent() {
return event;
}
public void setEvent(TutorialEvent event) {
this.event = event;
}
public boolean isUserLecturer() {
return isUserLecturer;
}
}
|
package edu.harvard.iq.dataverse.engine.command.impl;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.FileMetadata;
import edu.harvard.iq.dataverse.IndexServiceBean;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.dataaccess.DataAccessObject;
import edu.harvard.iq.dataverse.engine.command.AbstractVoidCommand;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.RequiredPermissions;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.exception.CommandExecutionException;
import edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
/**
* Deletes a data file, both DB entity and filesystem object.
*
* @author michael
*/
@RequiredPermissions(Permission.DestructiveEdit)
public class DeleteDataFileCommand extends AbstractVoidCommand {
private static final Logger logger = Logger.getLogger(DeleteDataFileCommand.class.getCanonicalName());
private final DataFile doomed;
public DeleteDataFileCommand(DataFile doomed, User aUser) {
super(aUser, doomed);
this.doomed = doomed;
}
@Override
protected void executeImpl(CommandContext ctxt) throws CommandException {
if (doomed.isReleased()) {
logger.fine("Delete command called on a released (published) DataFile "+doomed.getId());
/*
If the file has been released but also previously published handle here.
In this case we're only removing the link to the current version
we're not deleting the underlying data file
*/
if (ctxt.files().isPreviouslyPublished(doomed.getId())) {
//if previously published leave physical file alone for prior versions
FileMetadata fmr = doomed.getFileMetadatas().get(0);
for (FileMetadata testfmd : doomed.getFileMetadatas()) {
if (testfmd.getDatasetVersion().getId() > fmr.getDatasetVersion().getId()) {
fmr = testfmd;
}
}
FileMetadata doomedAndMerged = ctxt.em().merge(fmr);
ctxt.em().remove(doomedAndMerged);
String indexingResult = ctxt.index().removeSolrDocFromIndex(IndexServiceBean.solrDocIdentifierFile + doomed.getId() + "_draft");
return;
}
throw new IllegalCommandException("Cannot delete a released file", this);
}
// We need to delete a bunch of files from the file system;
// First we try to delete the data file itself; if that
// fails, we throw an exception and abort the command without
// trying to remove the object from the database:
logger.fine("Delete command called on an unpublished DataFile "+doomed.getId());
String fileSystemName = doomed.getFileSystemName();
logger.fine("Storage identifier for the file: "+fileSystemName);
DataAccessObject dataAccess = null;
try {
dataAccess = doomed.getAccessObject();
} catch (IOException ioex) {
throw new CommandExecutionException("Failed to initialize physical access driver.", ioex, this);
}
if (dataAccess != null) {
try {
dataAccess.delete();
} catch (IOException ex) {
throw new CommandExecutionException("Error deleting physical file object while deleting DataFile " + doomed.getId() + " from the database.", ex, this);
}
logger.fine("Successfully deleted physical storage object (file) for the DataFile " + doomed.getId());
// Destroy the dataAccess object - we will need to purge the
// DataFile from the database (below), so we don't want to have any
// objects in this transaction that reference it:
dataAccess = null;
// We may also have a few extra files associated with this object -
// preserved original that was used in the tabular data ingest,
// cached R data frames, image thumbnails, etc.
// We need to delete these too; failures however are less
// important with these. If we fail to delete any of these
// auxiliary files, we'll just leave an error message in the
// log file and proceed deleting the database object.
// Note that the assumption here is that all these auxiliary
// files - saved original, cached format conversions, etc., are
// all stored on the physical filesystem locally.
// TODO: revisit and review this assumption! -- L.A. 4.0
List<Path> victims = new ArrayList<>();
// 1. preserved original:
Path filePath = doomed.getSavedOriginalFile();
if (filePath != null) {
victims.add(filePath);
}
// 2. Cached files:
victims.addAll(listCachedFiles(doomed));
// Delete them all:
List<String> failures = new ArrayList<>();
for (Path deadFile : victims) {
try {
logger.fine("Deleting cached file "+deadFile.toString());
Files.delete(deadFile);
} catch (IOException ex) {
failures.add(deadFile.toString());
}
}
if (!failures.isEmpty()) {
String failedFiles = StringUtils.join(failures, ",");
Logger.getLogger(DeleteDataFileCommand.class.getName()).log(Level.SEVERE, "Error deleting physical file(s) " + failedFiles + " while deleting DataFile " + doomed.getName());
}
DataFile doomedAndMerged = ctxt.em().merge(doomed);
ctxt.em().remove(doomedAndMerged);
/**
* @todo consider adding an em.flush here (despite the performance
* impact) if you need to operate on the dataset below. Without the
* flush, the dataset still thinks it has the file that was just
* deleted.
*/
// ctxt.em().flush();
String indexingResult = ctxt.index().removeSolrDocFromIndex(IndexServiceBean.solrDocIdentifierFile + doomed.getId() + "_draft");
}
}
private List<Path> listCachedFiles(DataFile dataFile) {
List<Path> victims = new ArrayList<>();
// cached files for a given datafiles are stored on the filesystem
// as <filesystemname>.*; for example, <filename>.thumb64 or
// <filename>.RData.
final String baseName = dataFile.getFileSystemName();
if (baseName == null || baseName.equals("")) {
return null;
}
Path datasetDirectory = dataFile.getOwner().getFileSystemDirectory();
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path file) throws IOException {
return (file.getFileName() != null
&& file.getFileName().toString().startsWith(baseName + "."));
}
};
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(datasetDirectory, filter)) {
for (Path filePath : dirStream) {
victims.add(filePath);
}
} catch (IOException ex) {
}
return victims;
}
}
|
package com.intellij.sh.rename;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
class ShTextRenameRefactoring {
private static final String PRIMARY_VARIABLE_NAME = "PrimaryVariable";
private static final String OTHER_VARIABLE_NAME = "OtherVariable";
private final Editor myEditor;
private final Project myProject;
private final PsiFile myPsiFile;
private final Collection<TextRange> myOccurrenceRanges;
private final String myOccurrenceText;
private final TextRange myOccurrenceRangeAtCaret;
private RangeMarker myCaretRangeMarker;
private List<RangeHighlighter> myHighlighters;
private ShTextRenameRefactoring(@NotNull Editor editor,
@NotNull Project project,
@NotNull PsiFile psiFile,
@NotNull String occurrenceText,
@NotNull Collection<TextRange> occurrenceRanges,
@NotNull TextRange occurrenceRangeAtCaret) {
myEditor = editor;
myProject = project;
myPsiFile = psiFile;
myOccurrenceText = occurrenceText;
myOccurrenceRanges = occurrenceRanges;
myOccurrenceRangeAtCaret = occurrenceRangeAtCaret;
}
@Nullable
static ShTextRenameRefactoring create(@NotNull Editor editor,
@NotNull Project project,
@NotNull String occurrenceText,
@NotNull Collection<TextRange> occurrenceRanges,
@NotNull TextRange occurrenceRangeAtCaret) {
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (psiFile != null) {
return new ShTextRenameRefactoring(editor, project, psiFile, occurrenceText, occurrenceRanges, occurrenceRangeAtCaret);
}
return null;
}
void start() {
TemplateBuilderImpl builder = new TemplateBuilderImpl(myPsiFile);
for (TextRange occurrence : myOccurrenceRanges) {
if (occurrence.equals(myOccurrenceRangeAtCaret)) {
builder.replaceElement(myPsiFile, occurrence, PRIMARY_VARIABLE_NAME, new MyExpression(myOccurrenceText), true);
}
else {
builder.replaceElement(myPsiFile, occurrence, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
}
}
createCaretRangeMarker();
WriteCommandAction.writeCommandAction(myProject).withName("Rename " + myOccurrenceText).run(() -> startTemplate(builder));
}
private void createCaretRangeMarker() {
int offset = myEditor.getCaretModel().getOffset();
myCaretRangeMarker = myEditor.getDocument().createRangeMarker(offset, offset);
myCaretRangeMarker.setGreedyToLeft(true);
myCaretRangeMarker.setGreedyToRight(true);
}
private void startTemplate(TemplateBuilderImpl builder) {
int caretOffset = myEditor.getCaretModel().getOffset();
TextRange range = myPsiFile.getTextRange();
assert range != null;
RangeMarker rangeMarker = myEditor.getDocument().createRangeMarker(range);
Template template = builder.buildInlineTemplate();
template.setToShortenLongNames(false);
template.setToReformat(false);
myEditor.getCaretModel().moveToOffset(rangeMarker.getStartOffset());
TemplateManager.getInstance(myProject).startTemplate(myEditor, template, new MyTemplateListener());
restoreOldCaretPositionAndSelection(caretOffset);
myHighlighters = new ArrayList<>();
highlightTemplateVariables(template);
}
private void highlightTemplateVariables(@NotNull Template template) {
if (myHighlighters != null) { // can be null if finish is called during testing
Map<TextRange, TextAttributes> rangesToHighlight = new HashMap<>();
TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor);
if (templateState != null) {
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
for (int i = 0; i < templateState.getSegmentsCount(); i++) {
TextRange segmentOffset = templateState.getSegmentRange(i);
TextAttributes attributes = getAttributes(colorsManager, template.getSegmentName(i));
if (attributes != null) {
rangesToHighlight.put(segmentOffset, attributes);
}
}
}
addHighlights(rangesToHighlight, myHighlighters);
}
}
@Nullable
private static TextAttributes getAttributes(@NotNull EditorColorsManager colorsManager, @NotNull String segmentName) {
if (segmentName.equals(PRIMARY_VARIABLE_NAME)) {
return colorsManager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
}
if (segmentName.equals(OTHER_VARIABLE_NAME)) {
return colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
}
return null;
}
private void addHighlights(@NotNull Map<TextRange, TextAttributes> ranges,
@NotNull Collection<RangeHighlighter> highlighters) {
HighlightManager highlightManager = HighlightManager.getInstance(myProject);
for (Map.Entry<TextRange, TextAttributes> entry : ranges.entrySet()) {
TextRange range = entry.getKey();
TextAttributes attributes = entry.getValue();
highlightManager.addOccurrenceHighlight(myEditor, range.getStartOffset(), range.getEndOffset(), attributes, 0, highlighters, null);
}
for (RangeHighlighter highlighter : highlighters) {
highlighter.setGreedyToLeft(true);
highlighter.setGreedyToRight(true);
}
}
private void clearHighlights() {
if (myHighlighters != null) {
if (!myProject.isDisposed()) {
HighlightManager highlightManager = HighlightManager.getInstance(myProject);
for (RangeHighlighter highlighter : myHighlighters) {
highlightManager.removeSegmentHighlighter(myEditor, highlighter);
}
}
myHighlighters = null;
}
}
private void restoreOldCaretPositionAndSelection(int offset) {
Runnable runnable = () -> myEditor.getCaretModel().moveToOffset(restoreCaretOffset(offset));
LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myEditor);
if (lookup != null && lookup.getLookupStart() <= (restoreCaretOffset(offset))) {
lookup.setFocusDegree(LookupImpl.FocusDegree.UNFOCUSED);
lookup.performGuardedChange(runnable);
}
else {
runnable.run();
}
}
private int restoreCaretOffset(int offset) {
return myCaretRangeMarker.isValid() ? myCaretRangeMarker.getEndOffset() : offset;
}
private static class MyExpression extends Expression {
private final String myInitialText;
private MyExpression(@NotNull String initialText) {
myInitialText = initialText;
}
@Override
public Result calculateResult(ExpressionContext context) {
Editor editor = context.getEditor();
if (editor != null) {
TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
TextResult insertedValue = templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null;
if (insertedValue != null && !insertedValue.getText().isEmpty()) {
return insertedValue;
}
}
return new TextResult(myInitialText);
}
@Override
public Result calculateQuickResult(ExpressionContext context) {
return calculateResult(context);
}
@Override
public LookupElement[] calculateLookupItems(ExpressionContext context) {
return LookupElement.EMPTY_ARRAY;
}
}
private class MyTemplateListener extends TemplateEditingAdapter {
@Override
public void beforeTemplateFinished(@NotNull TemplateState templateState, Template template) {
clearHighlights();
}
@Override
public void templateCancelled(Template template) {
clearHighlights();
}
}
}
|
package nl.bstoi.poiparser.core.strategy.annotation;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nl.bstoi.poiparser.api.strategy.annotations.Cell;
import nl.bstoi.poiparser.core.InitialWritePoiParserException;
import nl.bstoi.poiparser.core.ReadPoiParserException;
import nl.bstoi.poiparser.core.ReadPoiParserRuntimeException;
import nl.bstoi.poiparser.core.RequiredFieldPoiParserException;
import nl.bstoi.poiparser.core.WritePoiParserException;
import nl.bstoi.poiparser.core.strategy.AbstractPoiFileParser;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class AnnotatedPoiFileParser<T> extends AbstractPoiFileParser<T>{
/**
* Default constructor
*/
public AnnotatedPoiFileParser() {
// Default constructor
}
/**
* Use a different column field mapping and ignore the @Cell values in class.
* @param columnFieldNameMapping
*/
public AnnotatedPoiFileParser(Map<String,Integer> columnFieldNameMapping) {
super(columnFieldNameMapping);
}
/**
* Use a different column field mapping and ignore the @Cell values in class.
* @param columnFieldNameMapping
*/
public AnnotatedPoiFileParser(Map<String,Integer> columnFieldNameMapping,Set<Integer> requiredColumnNumbers) {
super(columnFieldNameMapping,requiredColumnNumbers);
}
@Override
public List<T> readExcelFile(File excelFile,String sheetName,Class<T> clazz) throws IOException,FileNotFoundException, InstantiationException, IllegalAccessException, RequiredFieldPoiParserException,ReadPoiParserException{
FileInputStream fis = null;
fis = new FileInputStream(excelFile);
List<T> dimensionList = null;
try {
dimensionList = readExcelFile(fis, sheetName, clazz);
} finally {
fis.close(); // Close file stream
}
if(null==dimensionList) throw new ReadPoiParserRuntimeException();
return dimensionList;
}
@Override
public List<T> readExcelFile(File excelFile, String sheetName,Class<T> clazz, int startRow, int endRow) throws IOException,FileNotFoundException, InstantiationException,IllegalAccessException, RequiredFieldPoiParserException,ReadPoiParserException {
FileInputStream fis = null;
fis = new FileInputStream(excelFile);
List<T> dimensionList = null;
try {
dimensionList = readExcelFile(fis, sheetName, clazz,startRow,endRow);
} finally {
fis.close(); // Close file stream
}
if(null==dimensionList) throw new ReadPoiParserRuntimeException();
return dimensionList;
}
@Override
public List<T> readExcelFile(File excelFile, String sheetName,Class<T> clazz, int startRow) throws IOException,FileNotFoundException, InstantiationException,IllegalAccessException, RequiredFieldPoiParserException,ReadPoiParserException {
FileInputStream fis = null;
fis = new FileInputStream(excelFile);
List<T> dimensionList = null;
try {
dimensionList = readExcelFile(fis, sheetName, clazz,startRow);
} finally {
fis.close(); // Close file stream
}
if(null==dimensionList) throw new ReadPoiParserRuntimeException();
return dimensionList;
}
@Override
public List<T> readExcelFile(InputStream inputStream,String sheetName,Class<T> clazz) throws IOException,FileNotFoundException, InstantiationException, IllegalAccessException, RequiredFieldPoiParserException,ReadPoiParserException{
Sheet sheet = getSheetFromInputStream(inputStream, sheetName, clazz);
return readSheet(sheet, clazz);
}
@Override
public List<T> readExcelFile(InputStream inputStream, String sheetName,Class<T> clazz, int startRow, int endRow) throws IOException,FileNotFoundException, InstantiationException,IllegalAccessException, RequiredFieldPoiParserException,ReadPoiParserException {
Sheet sheet = getSheetFromInputStream(inputStream, sheetName, clazz);
return readSheet(sheet, clazz,startRow,endRow);
}
@Override
public List<T> readExcelFile(InputStream inputStream, String sheetName,Class<T> clazz, int startRow) throws IOException,FileNotFoundException, InstantiationException,IllegalAccessException, RequiredFieldPoiParserException,ReadPoiParserException {
Sheet sheet = getSheetFromInputStream(inputStream, sheetName, clazz);
return readSheet(sheet, clazz,startRow);
}
private Sheet getSheetFromInputStream(InputStream inputStream,String sheetName, Class<T> clazz) throws IOException {
// Get mapping for classfile
if(getColumnFieldNameMapping().isEmpty()) parseExcelMappingForClass(clazz);
// Open excel file
// Read work book
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(inputStream);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
// Get correct sheet.
Sheet sheet=workbook.getSheet(sheetName);
return sheet;
}
@Override
public void writeExcelFile(OutputStream outputStream,LinkedHashMap<String, List<T>> excelDataMap,Class<T> clazz) throws IOException, InitialWritePoiParserException,WritePoiParserException{
if(getColumnFieldNameMapping().isEmpty()) parseExcelMappingForClass(clazz);
writeWorkbook(excelDataMap).write(outputStream);
}
/**
* Recursive read of super classes that have excel parser information
* @param clazz
* @param excelMapping
*/
protected void parseExcelMappingForClass(Class clazz){
final Set<String> uniquePropertiesForClass = new HashSet<String>();
// Parse super class first and override configuration when needed
if(clazz.getSuperclass()!=Object.class) parseExcelMappingForClass(clazz.getSuperclass());
for(PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(clazz)){
if(!new String("class").equals(propertyDescriptor.getName())){
Cell cell = null;
try {
Field field = clazz.getDeclaredField(propertyDescriptor.getDisplayName());
cell = field.getAnnotation(Cell.class);
if(cell==null){
// When field has no annotation then check method
Method method = propertyDescriptor.getReadMethod();
if(null!=method)cell = method.getAnnotation(Cell.class);
}
} catch (SecurityException e) {
throw e; // Rethrow security exception
} catch (NoSuchFieldException e) {
// If field does not exist try to get value from getter(method)
Method method = propertyDescriptor.getReadMethod();
if(null!=method)cell = method.getAnnotation(Cell.class);
}
// If annotation is set then add column field mapping
if(cell!=null){
boolean ignoreRead = (null==propertyDescriptor.getWriteMethod()||cell.readIgnore()); // Whether the property can be read from excel and be written to the bean
boolean ignoreWrite = (null==propertyDescriptor.getReadMethod()||cell.writeIgnore()); // Whether the property can be written excel and be read to from bean
if(!uniquePropertiesForClass.contains(propertyDescriptor.getName())){
uniquePropertiesForClass.add(propertyDescriptor.getName());
addColumnFieldMapping(propertyDescriptor.getName(), cell.columnNumber(), cell.required(), ignoreRead, ignoreWrite, cell.regex());
}else{
// Throw exception when field
throw new IllegalStateException("Field name ["+propertyDescriptor.getName()+"] is defined more than once for parsing");
}
}
}
}
}
/**
* Adds a new field to the abstract excel parser.
* @param fieldName
* @param columnNumber
* @param required
* @param readIgnore
* @param writeIgnore
* @param fieldRegex
*/
private void addColumnFieldMapping(String fieldName,Integer columnNumber,boolean required,boolean readIgnore,boolean writeIgnore,String fieldRegex){
addColumnFieldNameMapping(fieldName, columnNumber);
if(required)addRequiredField(columnNumber);
if(readIgnore)addReadIgnoreColumn(columnNumber);
if(writeIgnore)addWriteIgnoreColumn(columnNumber);
if(null!=fieldRegex&&!fieldRegex.isEmpty()) addColumnFieldRegex(fieldName, fieldRegex);
}
}
|
package org.anyline.jdbc.config.db.impl.oracle;
import org.anyline.dao.AnylineDao;
import org.anyline.entity.DataRow;
import org.anyline.entity.DataSet;
import org.anyline.entity.PageNavi;
import org.anyline.jdbc.config.db.OrderStore;
import org.anyline.jdbc.config.db.SQLCreater;
import org.anyline.jdbc.config.db.impl.BasicSQLCreaterImpl;
import org.anyline.jdbc.config.db.run.RunSQL;
import org.anyline.util.BasicUtil;
import org.anyline.util.ConfigTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("anyline.jdbc.creater.oracle")
public class SQLCreaterImpl extends BasicSQLCreaterImpl implements SQLCreater{
@Autowired(required = false)
@Qualifier("anyline.dao")
protected AnylineDao dao;
public DB_TYPE type(){
return DB_TYPE.ORACLE;
}
public SQLCreaterImpl(){
delimiterFr = "";
delimiterTo = "";
}
@Override
public String getDelimiterFr(){
return delimiterFr;
}
@Override
public String getDelimiterTo(){
return delimiterTo;
}
@Override
public String parseFinalQueryTxt(RunSQL run){
StringBuilder builder = new StringBuilder();
String cols = run.getFetchColumns();
PageNavi navi = run.getPageNavi();
String sql = run.getBaseQueryTxt();
OrderStore orders = run.getOrderStore();
int first = 0;
int last = 0;
String order = "";
if(null != orders){
order = orders.getRunText(getDelimiterFr()+getDelimiterTo());
}
if(null != navi){
first = navi.getFirstRow();
last = navi.getLastRow();
}
if(null == navi){
builder.append(sql).append("\n").append(order);
}else{
builder.append("SELECT "+cols+" FROM( \n");
builder.append("SELECT TAB_I.* ,ROWNUM AS ROW_NUMBER \n");
builder.append("FROM( \n");
builder.append(sql);
builder.append("\n").append(order);
builder.append(") TAB_I \n");
builder.append(") TAB_O WHERE ROW_NUMBER >= "+(first+1)+" AND ROW_NUMBER <= "+(last+1));
}
return builder.toString();
}
@Override
public String concat(String ... args){
String result = "";
if(null != args && args.length > 0){
int size = args.length;
for(int i=0; i<size; i++){
String arg = args[i];
if(i>0){
result += " || ";
}
result += arg;
}
}
return result;
}
/* INSERT ALL
INTO ORG_DS(ORG_NAME,ORG_CODE) VALUES ('A', 'A')
INTO ORG_DS(ORG_NAME,ORG_CODE) VALUES ('B', 'B')
SELECT 1 FROM DUAL;
INSERT ALL
INTO ORG_DS(ORG_NAME,ORG_CODE)VALUES('A','A')
SELECT 1 FROM DUAL;
INTO ORG_DS(ORG_NAME,ORG_CODE)VALUES('B','B')SELECT 1 FROM DUAL;
*/
@Override
public void createInsertsTxt(StringBuilder builder, String dest, DataSet set, List<String> keys){
builder.append("INSERT ALL \n");
String head = "INTO " + dest + " (";
int keySize = keys.size();
for(int i=0; i<keySize; i++){
String key = keys.get(i);
head += key;
if(i<keySize-1){
head += ", ";
}
}
head += ") ";
int dataSize = set.size();
for(int i=0; i<dataSize; i++){
DataRow row = set.getRow(i);
if(null == row){
continue;
}
if(row.hasPrimaryKeys() && null != primaryCreater && BasicUtil.isEmpty(row.getPrimaryValue())){
String pk = row.getPrimaryKey();
if(null == pk){
pk = ConfigTable.getString("DEFAULT_PRIMARY_KEY");
}
row.put(pk, primaryCreater.createPrimary(type(),dest.replace(getDelimiterFr(), "").replace(getDelimiterTo(), ""), pk, null));
}
builder.append(head).append("VALUES ");
insertValue(builder, row, keys);
builder.append(" \n");
}
builder.append("SELECT 1 FROM DUAL");
}
}
|
package com.genymobile.scrcpy;
import com.genymobile.scrcpy.wrappers.ClipboardManager;
import com.genymobile.scrcpy.wrappers.InputManager;
import com.genymobile.scrcpy.wrappers.ServiceManager;
import com.genymobile.scrcpy.wrappers.SurfaceControl;
import com.genymobile.scrcpy.wrappers.WindowManager;
import android.content.IOnPrimaryClipChangedListener;
import android.graphics.Rect;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.view.IRotationWatcher;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import java.util.concurrent.atomic.AtomicBoolean;
public final class Device {
public static final int POWER_MODE_OFF = SurfaceControl.POWER_MODE_OFF;
public static final int POWER_MODE_NORMAL = SurfaceControl.POWER_MODE_NORMAL;
public static final int INJECT_MODE_ASYNC = InputManager.INJECT_INPUT_EVENT_MODE_ASYNC;
public static final int INJECT_MODE_WAIT_FOR_RESULT = InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT;
public static final int INJECT_MODE_WAIT_FOR_FINISH = InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH;
public static final int LOCK_VIDEO_ORIENTATION_UNLOCKED = -1;
public static final int LOCK_VIDEO_ORIENTATION_INITIAL = -2;
private static final ServiceManager SERVICE_MANAGER = new ServiceManager();
private static final Settings SETTINGS = new Settings(SERVICE_MANAGER);
public interface RotationListener {
void onRotationChanged(int rotation);
}
public interface ClipboardListener {
void onClipboardTextChanged(String text);
}
private final Size deviceSize;
private final Rect crop;
private final int maxSize;
private final int lockVideoOrientation;
private ScreenInfo screenInfo;
private RotationListener rotationListener;
private ClipboardListener clipboardListener;
private final AtomicBoolean isSettingClipboard = new AtomicBoolean();
/**
* Logical display identifier
*/
private final int displayId;
/**
* The surface flinger layer stack associated with this logical display
*/
private final int layerStack;
private final boolean supportsInputEvents;
public Device(Options options) {
displayId = options.getDisplayId();
DisplayInfo displayInfo = SERVICE_MANAGER.getDisplayManager().getDisplayInfo(displayId);
if (displayInfo == null) {
int[] displayIds = SERVICE_MANAGER.getDisplayManager().getDisplayIds();
throw new InvalidDisplayIdException(displayId, displayIds);
}
int displayInfoFlags = displayInfo.getFlags();
deviceSize = displayInfo.getSize();
crop = options.getCrop();
maxSize = options.getMaxSize();
lockVideoOrientation = options.getLockVideoOrientation();
screenInfo = ScreenInfo.computeScreenInfo(displayInfo.getRotation(), deviceSize, crop, maxSize, lockVideoOrientation);
layerStack = displayInfo.getLayerStack();
SERVICE_MANAGER.getWindowManager().registerRotationWatcher(new IRotationWatcher.Stub() {
@Override
public void onRotationChanged(int rotation) {
synchronized (Device.this) {
screenInfo = screenInfo.withDeviceRotation(rotation);
// notify
if (rotationListener != null) {
rotationListener.onRotationChanged(rotation);
}
}
}
}, displayId);
if (options.getControl() && options.getClipboardAutosync()) {
// If control and autosync are enabled, synchronize Android clipboard to the computer automatically
ClipboardManager clipboardManager = SERVICE_MANAGER.getClipboardManager();
if (clipboardManager != null) {
clipboardManager.addPrimaryClipChangedListener(new IOnPrimaryClipChangedListener.Stub() {
@Override
public void dispatchPrimaryClipChanged() {
if (isSettingClipboard.get()) {
// This is a notification for the change we are currently applying, ignore it
return;
}
synchronized (Device.this) {
if (clipboardListener != null) {
String text = getClipboardText();
if (text != null) {
clipboardListener.onClipboardTextChanged(text);
}
}
}
}
});
} else {
Ln.w("No clipboard manager, copy-paste between device and computer will not work");
}
}
if ((displayInfoFlags & DisplayInfo.FLAG_SUPPORTS_PROTECTED_BUFFERS) == 0) {
Ln.w("Display doesn't have FLAG_SUPPORTS_PROTECTED_BUFFERS flag, mirroring can be restricted");
}
// main display or any display on Android >= Q
supportsInputEvents = displayId == 0 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
if (!supportsInputEvents) {
Ln.w("Input events are not supported for secondary displays before Android 10");
}
}
public synchronized ScreenInfo getScreenInfo() {
return screenInfo;
}
public int getLayerStack() {
return layerStack;
}
public Point getPhysicalPoint(Position position) {
// it hides the field on purpose, to read it with a lock
@SuppressWarnings("checkstyle:HiddenField")
ScreenInfo screenInfo = getScreenInfo(); // read with synchronization
// ignore the locked video orientation, the events will apply in coordinates considered in the physical device orientation
Size unlockedVideoSize = screenInfo.getUnlockedVideoSize();
int reverseVideoRotation = screenInfo.getReverseVideoRotation();
// reverse the video rotation to apply the events
Position devicePosition = position.rotate(reverseVideoRotation);
Size clientVideoSize = devicePosition.getScreenSize();
if (!unlockedVideoSize.equals(clientVideoSize)) {
// The client sends a click relative to a video with wrong dimensions,
// the device may have been rotated since the event was generated, so ignore the event
return null;
}
Rect contentRect = screenInfo.getContentRect();
Point point = devicePosition.getPoint();
int convertedX = contentRect.left + point.getX() * contentRect.width() / unlockedVideoSize.getWidth();
int convertedY = contentRect.top + point.getY() * contentRect.height() / unlockedVideoSize.getHeight();
return new Point(convertedX, convertedY);
}
public static String getDeviceName() {
return Build.MODEL;
}
public static boolean supportsInputEvents(int displayId) {
return displayId == 0 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
}
public boolean supportsInputEvents() {
return supportsInputEvents;
}
public static boolean injectEvent(InputEvent inputEvent, int displayId, int injectMode) {
if (!supportsInputEvents(displayId)) {
throw new AssertionError("Could not inject input event if !supportsInputEvents()");
}
if (displayId != 0 && !InputManager.setDisplayId(inputEvent, displayId)) {
return false;
}
return SERVICE_MANAGER.getInputManager().injectInputEvent(inputEvent, injectMode);
}
public boolean injectEvent(InputEvent event, int injectMode) {
return injectEvent(event, displayId, injectMode);
}
public static boolean injectKeyEvent(int action, int keyCode, int repeat, int metaState, int displayId, int injectMode) {
long now = SystemClock.uptimeMillis();
KeyEvent event = new KeyEvent(now, now, action, keyCode, repeat, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD);
return injectEvent(event, displayId, injectMode);
}
public boolean injectKeyEvent(int action, int keyCode, int repeat, int metaState, int injectMode) {
return injectKeyEvent(action, keyCode, repeat, metaState, displayId, injectMode);
}
public static boolean pressReleaseKeycode(int keyCode, int displayId, int injectMode) {
return injectKeyEvent(KeyEvent.ACTION_DOWN, keyCode, 0, 0, displayId, injectMode)
&& injectKeyEvent(KeyEvent.ACTION_UP, keyCode, 0, 0, displayId, injectMode);
}
public boolean pressReleaseKeycode(int keyCode, int injectMode) {
return pressReleaseKeycode(keyCode, displayId, injectMode);
}
public static boolean isScreenOn() {
return SERVICE_MANAGER.getPowerManager().isScreenOn();
}
public synchronized void setRotationListener(RotationListener rotationListener) {
this.rotationListener = rotationListener;
}
public synchronized void setClipboardListener(ClipboardListener clipboardListener) {
this.clipboardListener = clipboardListener;
}
public static void expandNotificationPanel() {
SERVICE_MANAGER.getStatusBarManager().expandNotificationsPanel();
}
public static void expandSettingsPanel() {
SERVICE_MANAGER.getStatusBarManager().expandSettingsPanel();
}
public static void collapsePanels() {
SERVICE_MANAGER.getStatusBarManager().collapsePanels();
}
public static String getClipboardText() {
ClipboardManager clipboardManager = SERVICE_MANAGER.getClipboardManager();
if (clipboardManager == null) {
return null;
}
CharSequence s = clipboardManager.getText();
if (s == null) {
return null;
}
return s.toString();
}
public boolean setClipboardText(String text) {
ClipboardManager clipboardManager = SERVICE_MANAGER.getClipboardManager();
if (clipboardManager == null) {
return false;
}
String currentClipboard = getClipboardText();
if (currentClipboard != null && currentClipboard.equals(text)) {
// The clipboard already contains the requested text.
// Since pasting text from the computer involves setting the device clipboard, it could be set twice on a copy-paste. This would cause
// the clipboard listeners to be notified twice, and that would flood the Android keyboard clipboard history. To workaround this
// problem, do not explicitly set the clipboard text if it already contains the expected content.
return false;
}
isSettingClipboard.set(true);
boolean ok = clipboardManager.setText(text);
isSettingClipboard.set(false);
return ok;
}
/**
* @param mode one of the {@code POWER_MODE_*} constants
*/
public static boolean setScreenPowerMode(int mode) {
IBinder d = SurfaceControl.getBuiltInDisplay();
if (d == null) {
Ln.e("Could not get built-in display");
return false;
}
return SurfaceControl.setDisplayPowerMode(d, mode);
}
public static boolean powerOffScreen(int displayId) {
if (!isScreenOn()) {
return true;
}
return pressReleaseKeycode(KeyEvent.KEYCODE_POWER, displayId, Device.INJECT_MODE_ASYNC);
}
/**
* Disable auto-rotation (if enabled), set the screen rotation and re-enable auto-rotation (if it was enabled).
*/
public static void rotateDevice() {
WindowManager wm = SERVICE_MANAGER.getWindowManager();
boolean accelerometerRotation = !wm.isRotationFrozen();
int currentRotation = wm.getRotation();
int newRotation = (currentRotation & 1) ^ 1; // 0->1, 1->0, 2->1, 3->0
String newRotationString = newRotation == 0 ? "portrait" : "landscape";
Ln.i("Device rotation requested: " + newRotationString);
wm.freezeRotation(newRotation);
// restore auto-rotate if necessary
if (accelerometerRotation) {
wm.thawRotation();
}
}
public static Settings getSettings() {
return SETTINGS;
}
}
|
package org.deeplearning4j.rottentomatoes.data.visualization;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.deeplearning4j.models.word2vec.Word2Vec;
import org.deeplearning4j.plot.Tsne;
import org.deeplearning4j.rottentomatoes.data.SentenceToPhraseMapper;
import org.deeplearning4j.text.sentenceiterator.CollectionSentenceIterator;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class Visualization {
public static void main(String[] args) throws Exception {
ClassPathResource r = new ClassPathResource("/train.tsv");
if(r.exists()) {
InputStream is = r.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("train.tsv")));
IOUtils.copy(is, bos);
bos.flush();
bos.close();
is.close();
}
SentenceIterator docIter = new CollectionSentenceIterator(new SentenceToPhraseMapper(new File("train.tsv")).sentences());
TokenizerFactory factory = new DefaultTokenizerFactory();
Word2Vec vec = new Word2Vec.Builder().iterate(docIter)
.tokenizerFactory(factory).batchSize(10000)
.learningRate(2.5e-2).sampling(5).learningRateDecayWords(10000)
.iterations(3).minWordFrequency(1)
.layerSize(300).windowSize(5).build();
vec.fit();
FileUtils.writeLines(new File("vocab.csv"),vec.getCache().words());
String word = "amusing";
String otherWord = "turd";
System.out.println("Words nearest " + word + " " + vec.wordsNearest(word,10));
System.out.println("Words nearest " + otherWord + " " + vec.wordsNearest(otherWord,10));
/* Tsne t = new Tsne.Builder()
.setMaxIter(100).stopLyingIteration(20).build();
vec.getCache().plotVocab(t);*/
}
}
|
package com.continuuity.internal.app.runtime.batch.inmemory;
import com.continuuity.app.guice.ProgramRunnerRuntimeModule;
import com.continuuity.common.conf.CConfiguration;
import com.continuuity.common.conf.Constants;
import com.continuuity.common.guice.ConfigModule;
import com.continuuity.common.guice.DiscoveryRuntimeModule;
import com.continuuity.common.guice.IOModule;
import com.continuuity.common.guice.LocationRuntimeModule;
import com.continuuity.common.utils.Networks;
import com.continuuity.data.runtime.DataFabricModules;
import com.continuuity.gateway.auth.AuthModule;
import com.continuuity.internal.app.runtime.batch.AbstractMapReduceContextBuilder;
import com.continuuity.logging.guice.LoggingModules;
import com.continuuity.metrics.guice.MetricsClientRuntimeModule;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.name.Named;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import java.net.InetAddress;
import java.net.InetSocketAddress;
/**
* Builds an instance of {@link com.continuuity.internal.app.runtime.batch.BasicMapReduceContext} good for
* in-memory environment
*/
public class InMemoryMapReduceContextBuilder extends AbstractMapReduceContextBuilder {
private final CConfiguration cConf;
private final TaskAttemptContext taskContext;
public InMemoryMapReduceContextBuilder(CConfiguration cConf, TaskAttemptContext taskContext) {
this.cConf = cConf;
this.taskContext = taskContext;
}
@Override
protected Injector prepare() {
// TODO: this logic should go into DataFabricModules. We'll move it once Guice modules are refactored
Constants.InMemoryPersistenceType persistenceType = Constants.InMemoryPersistenceType.valueOf(
cConf.get(Constants.CFG_DATA_INMEMORY_PERSISTENCE, Constants.DEFAULT_DATA_INMEMORY_PERSISTENCE));
if (Constants.InMemoryPersistenceType.MEMORY == persistenceType) {
return createInMemoryModules();
} else {
return createPersistentModules();
}
}
private Injector createInMemoryModules() {
ImmutableList<Module> inMemoryModules = ImmutableList.of(
new ConfigModule(cConf),
new LocalConfigModule(),
new IOModule(),
new AuthModule(),
new LocationRuntimeModule().getInMemoryModules(),
new DiscoveryRuntimeModule().getInMemoryModules(),
new ProgramRunnerRuntimeModule().getInMemoryModules(),
new DataFabricModules().getInMemoryModules(),
new MetricsClientRuntimeModule().getNoopModules(),
new LoggingModules().getInMemoryModules()
);
return Guice.createInjector(inMemoryModules);
}
private Injector createPersistentModules() {
ImmutableList<Module> singleNodeModules = ImmutableList.of(
new ConfigModule(cConf),
new LocalConfigModule(),
new IOModule(),
new AuthModule(),
new LocationRuntimeModule().getSingleNodeModules(),
new DiscoveryRuntimeModule().getSingleNodeModules(),
new ProgramRunnerRuntimeModule().getSingleNodeModules(),
new DataFabricModules().getSingleNodeModules(),
new MetricsClientRuntimeModule().getMapReduceModules(taskContext),
new LoggingModules().getSingleNodeModules()
);
return Guice.createInjector(singleNodeModules);
}
/**
* Provides bindings to configs needed by other modules binding in this class.
*/
private static class LocalConfigModule extends AbstractModule {
@Override
protected void configure() {
// No-op
}
@Provides
@Named(Constants.AppFabric.SERVER_ADDRESS)
public InetAddress providesHostname(CConfiguration cConf) {
return Networks.resolve(cConf.get(Constants.AppFabric.SERVER_ADDRESS),
new InetSocketAddress("localhost", 0).getAddress());
}
}
}
|
package openfoodfacts.github.scrachx.openfood.test;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;
import openfoodfacts.github.scrachx.openfood.BuildConfig;
import tools.fastlane.screengrab.file.Chmod;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Write screennshot files.
*/
public class FileWritingScreenshotCallback implements tools.fastlane.screengrab.ScreenshotCallback {
private static final String LOG_TAG = FileWritingScreenshotCallback.class.getSimpleName();
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
private ScreenshotParameter screenshotParameter;
FileWritingScreenshotCallback() {
}
@Override
public void screenshotCaptured(String screenshotName, Bitmap screenshot) {
try {
File screenshotDirectory = getFilesDirectory();
File screenshotFile = this.getScreenshotFile(screenshotDirectory,
screenshotParameter.getCountryTag() + "_" + screenshotParameter.getLanguage() + "-" + screenshotName);
try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(screenshotFile))) {
screenshot.compress(CompressFormat.PNG, 100, fos);
Chmod.chmodPlusR(screenshotFile);
} finally {
screenshot.recycle();
}
Log.d(LOG_TAG, "Captured screenshot \"" + screenshotFile.getName() + "\"");
} catch (Exception var10) {
throw new RuntimeException("Unable to capture screenshot.", var10);
}
}
private File getScreenshotFile(File screenshotDirectory, String screenshotName) {
String screenshotFileName = screenshotName + "_" + dateFormat.format(new Date()) + ".png";
return new File(screenshotDirectory, screenshotFileName);
}
/* Checks if external storage is available for read and write */
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
private File getFilesDirectory() throws IOException {
if (!isExternalStorageWritable()) {
Log.e(LOG_TAG, "Can't write to external storage check your installation");
throw new IOException("Can't write to external storage");
}
File targetDirectory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), BuildConfig.FLAVOR + "Screenshots");
File internalDir = new File(targetDirectory, screenshotParameter.getCountryTag());
File directory = initializeDirectory(internalDir);
if (directory == null) {
throw new IOException("Unable to get a screenshot storage directory");
} else {
Log.d(LOG_TAG, "Using screenshot storage directory: " + directory.getAbsolutePath());
return directory;
}
}
private static File initializeDirectory(File dir) {
try {
createPathTo(dir);
if (dir.isDirectory() && dir.canWrite()) {
return dir;
}
} catch (IOException exception) {
Log.e(LOG_TAG, "Failed to initialize directory: " + dir.getAbsolutePath(), exception);
}
return null;
}
private static void createPathTo(File dir) throws IOException {
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create output dir: " + dir.getAbsolutePath());
} else {
Chmod.chmodPlusRWX(dir);
}
}
void setScreenshotParameter(ScreenshotParameter screenshotParameter) {
this.screenshotParameter = screenshotParameter;
}
}
|
package org.csstudio.scan.server.internal;
import static org.csstudio.scan.server.app.Application.logger;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.csstudio.java.time.TimestampFormats;
import org.csstudio.scan.ScanSystemPreferences;
import org.csstudio.scan.command.LoopCommand;
import org.csstudio.scan.command.ScanCommand;
import org.csstudio.scan.commandimpl.WaitForDevicesCommand;
import org.csstudio.scan.commandimpl.WaitForDevicesCommandImpl;
import org.csstudio.scan.data.ScanData;
import org.csstudio.scan.device.Device;
import org.csstudio.scan.device.DeviceContext;
import org.csstudio.scan.device.DeviceContextHelper;
import org.csstudio.scan.device.DeviceInfo;
import org.csstudio.scan.log.DataLog;
import org.csstudio.scan.log.DataLogFactory;
import org.csstudio.scan.server.JythonSupport;
import org.csstudio.scan.server.MacroContext;
import org.csstudio.scan.server.MemoryInfo;
import org.csstudio.scan.server.ScanCommandImpl;
import org.csstudio.scan.server.ScanCommandUtil;
import org.csstudio.scan.server.ScanContext;
import org.csstudio.scan.server.ScanInfo;
import org.csstudio.scan.server.ScanState;
/** Scan that can be executed: Commands, device context, state
*
* <p>Combines a {@link DeviceContext} with {@link ScanContextImpl}ementations
* and can execute them.
* When a command is executed, it receives a {@link ScanContext} view
* of the scan for limited access to the devices, data logger etc.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class ExecutableScan extends LoggedScan implements ScanContext, Callable<Object>, AutoCloseable
{
/** Pattern for "java.lang.Exception: ", "java...Exception: " */
private static final Pattern java_exception_pattern = Pattern.compile("java[.a-zA-Z]+Exception: ");
/** Engine that will execute this scan */
private final ScanEngine engine;
/** Jython interpreter that some commands may use.
* Owned by the ExecutableScan, see close()
*/
final private JythonSupport jython;
/** Commands to execute */
final private transient List<ScanCommandImpl<?>> pre_scan, implementations, post_scan;
/** Macros for resolving device names */
final private MacroContext macros;
/** Devices used by the scan */
final protected DeviceContext devices;
/** Log each device access, or require specific log command? */
private volatile boolean automatic_log_mode = false;
/** Data logger, present while executing the scan */
private volatile Optional<DataLog> data_logger = Optional.empty();
/** Total number of commands to execute */
final private long total_work_units;
/** Commands executed so far */
final protected AtomicLong work_performed = new AtomicLong();
/** State of this scan */
private AtomicReference<ScanState> state = new AtomicReference<>(ScanState.Idle);
/** Error message */
private volatile Optional<String> error = Optional.empty();
/** Start time, set when execution starts */
private volatile long start_ms = 0;
/** Actual or estimated end time */
private volatile long end_ms = 0;
/** Currently active commands, empty when nothing executes */
final private Deque<ScanCommandImpl<?>> active_commands = new ConcurrentLinkedDeque<>();
/** {@link Future}, set when scan has been submitted to {@link ExecutorService}. Not reset back to empty. */
private volatile Optional<Future<Object>> future = Optional.empty();
/** Device Names for status PVs.
* They should either all be set or all be empty, so checking one is sufficient.
*/
private Optional<String> device_active = Optional.empty(), device_status = Optional.empty(), device_state = Optional.empty(), device_progress = Optional.empty(), device_finish = Optional.empty();
/** Timeout for updating the state PV
*
* <p>Scan state PV is always updated awaiting completion,
* using this timeout.
*
* <p>This allows additional database logic to for example
* latch scan failures, or to conditionally update a scan alarm PV.
* Scans can check the scan alarm PV in the pre-scan
* to prohibit further scans until alarm has been cleared.
*/
final private static Duration timeout = Duration.ofSeconds(10);
/** Initialize
* @param engine {@link ScanEngine} that executes this scan
* @param jython Jython support
* @param name User-provided name for this scan
* @param devices {@link DeviceContext} to use for scan
* @param pre_scan Commands to execute before the 'main' section of the scan
* @param implementations Commands to execute in this scan
* @param post_scan Commands to execute before the 'main' section of the scan
* @throws Exception on error (cannot access log, ...)
*/
public ExecutableScan(final ScanEngine engine, final JythonSupport jython, final String name, final DeviceContext devices,
final List<ScanCommandImpl<?>> pre_scan,
final List<ScanCommandImpl<?>> implementations,
final List<ScanCommandImpl<?>> post_scan) throws Exception
{
super(DataLogFactory.createDataLog(name));
this.engine = engine;
this.jython = jython;
this.macros = new MacroContext(ScanSystemPreferences.getMacros());
this.devices = devices;
this.pre_scan = pre_scan;
this.implementations = implementations;
this.post_scan = post_scan;
// Assign addresses to all commands,
// determine work units
long address = 0;
long work_units = 0;
for (ScanCommandImpl<?> impl : implementations)
{
address = impl.setAddress(address);
work_units += impl.getWorkUnits();
}
total_work_units = work_units;
}
public void submit(final ExecutorService executor)
{
if (future.isPresent())
throw new IllegalStateException("Already submitted for execution");
future = Optional.of(executor.submit(this));
}
/** @return {@link ScanState} */
@Override
public ScanState getScanState()
{
return state.get();
}
/** @return Info about current state of this scan */
@Override
public ScanInfo getScanInfo()
{
final ScanCommandImpl<?> command = active_commands.peekLast();
final long address = command == null ? -1 : command.getCommand().getAddress();
final String command_name;
final ScanState state = getScanState();
final long runtime;
final long performed_work_units;
if (start_ms <= 0)
{ // Not started
command_name = "";
runtime = 0;
performed_work_units = 0;
}
else if (state.isDone())
{ // Finished, aborted
command_name = "- end -";
runtime = end_ms - start_ms;
performed_work_units = total_work_units;
}
else
{ // Running
command_name = command == null ? "" : command.toString();
final long now = System.currentTimeMillis();
runtime = now - start_ms;
performed_work_units = work_performed.get();
// Estimate end time
final long finish_estimate = performed_work_units <= 0
? now
: start_ms + runtime*total_work_units/performed_work_units;
// Somewhat smoothly update end time w/ estimate
if (end_ms <= 0)
end_ms = finish_estimate;
else
end_ms = 4*(end_ms/5) + finish_estimate/5;
}
return new ScanInfo(this, state, error, runtime, end_ms, performed_work_units, total_work_units, address, command_name);
}
/** @return Commands executed by this scan */
public List<ScanCommand> getScanCommands()
{
// Fetch underlying commands for implementations
final List<ScanCommand> commands = new ArrayList<ScanCommand>(implementations.size());
for (ScanCommandImpl<?> impl : implementations)
commands.add(impl.getCommand());
return commands;
}
/** @param address Command address
* @return ScanCommand with that address
* @throws Exception when not found
*/
public ScanCommand getCommandByAddress(final long address) throws Exception
{
final ScanCommand found = findCommandByAddress(getScanCommands(), address);
if (found == null)
throw new Exception("Invalid command address " + address);
return found;
}
/** Recursively search for command by address
* @param commands Command list
* @param address Desired command address
* @return Command with that address or <code>null</code>
*/
private ScanCommand findCommandByAddress(final List<ScanCommand> commands,
final long address)
{
for (ScanCommand command : commands)
{
if (command.getAddress() == address)
return command;
else if (command instanceof LoopCommand)
{
final LoopCommand loop = (LoopCommand) command;
final ScanCommand found = findCommandByAddress(loop.getBody(), address);
if (found != null)
return found;
}
}
return null;
}
/** Attempt to update a command parameter to a new value
* @param address Address of the command
* @param property_id Property to update
* @param value New value for the property
* @throws Exception on error
*/
public void updateScanProperty(final long address, final String property_id,
final Object value) throws Exception
{
final ScanCommand command = getCommandByAddress(address);
logger.log(Level.WARNING, "Updating running scan, changing " + property_id + " to " + value + " in " + command);
try
{
command.setProperty(property_id, value);
}
catch (Exception ex)
{
throw new Exception("Cannot update " + property_id + " of " +
command.getCommandName(), ex);
}
}
/** {@inheritDoc} */
@Override
public MacroContext getMacros()
{
return macros;
}
/** Obtain devices used by this scan.
*
* <p>Note that the result can differ before and
* after the scan gets executed because devices
* are added to the device context as needed.
*
* @return Devices used by this scan
*/
public Device[] getDevices()
{
return devices.getDevices();
}
/** {@inheritDoc} */
@Override
public Device getDevice(final String name) throws Exception
{
return devices.getDevice(name);
}
/** {@inheritDoc} */
@Override
public void setLogMode(final boolean automatic)
{
automatic_log_mode = automatic;
}
/** {@inheritDoc} */
@Override
public boolean isAutomaticLogMode()
{
return automatic_log_mode;
}
/** {@inheritDoc} */
@Override
public Optional<DataLog> getDataLog()
{
return data_logger;
}
/** {@inheritDoc} */
@Override
public long getLastScanDataSerial() throws Exception
{
final DataLog logger = data_logger.orElse(null);
if (logger == null)
return super.getLastScanDataSerial();
return logger.getLastScanDataSerial();
}
/** {@inheritDoc} */
@Override
public ScanData getScanData() throws Exception
{
final DataLog logger = data_logger.orElse(null);
if (logger == null)
return super.getScanData();
return logger.getScanData();
}
/** Callable for executing all commands on the scan,
* turning exceptions into a 'Failed' scan state.
*/
@Override
public Object call() throws Exception
{
logger.log(Level.CONFIG, "Executing ID {0} \"{1}\" [{2}]", new Object[] { getId(), getName(), new MemoryInfo()});
try
{
// Set logger for execution of scan
data_logger = Optional.of(DataLogFactory.getDataLog(this));
execute_or_die_trying();
// Exceptions will already have been caught within execute_or_die_trying,
// hopefully updating the status PVs, but there could be exceptions
// when connecting or closing devices which we'll catch here
}
catch (InterruptedException ex)
{
state.set(ScanState.Aborted);
error = Optional.of(ScanState.Aborted.name());
}
catch (Exception ex)
{
error = Optional.of(ex.getMessage());
// Scan may have been aborted early on, for example in DataLogFactory.getDataLog()
// Otherwise consider it failed
if (state.get() == ScanState.Aborted)
logger.log(Level.WARNING, "Scan " + getName() + " aborted", ex);
else
{
state.set(ScanState.Failed);
logger.log(Level.WARNING, "Scan " + getName() + " failed", ex);
}
}
// Set actual end time, not estimated
end_ms = System.currentTimeMillis();
// Close data logger
if (data_logger.isPresent())
data_logger.get().close();
data_logger = Optional.empty();
logger.log(Level.CONFIG, "Completed ID {0}: {1}", new Object[] { getId(), state.get().name() });
return null;
}
/** Execute all commands on the scan,
* passing exceptions back up.
* @throws Exception on error
*/
private void execute_or_die_trying() throws Exception
{
// Was scan aborted before it ever got to run?
if (state.get() == ScanState.Aborted)
return;
// Otherwise expect 'Idle'
if (! state.compareAndSet(ScanState.Idle, ScanState.Running))
throw new IllegalStateException("Cannot run Scan that is " + state.get());
start_ms = System.currentTimeMillis();
// Locate devices for status PVs
final String prefix = ScanSystemPreferences.getStatusPvPrefix();
if (prefix != null && !prefix.isEmpty())
{
device_active = Optional.of(prefix + "Active");
devices.addPVDevice(new DeviceInfo(device_active.get()));
device_status = Optional.of(prefix + "Status");
devices.addPVDevice(new DeviceInfo(device_status.get()));
device_state = Optional.of(prefix + "State");
devices.addPVDevice(new DeviceInfo(device_state.get()));
device_progress = Optional.of(prefix + "Progress");
devices.addPVDevice(new DeviceInfo(device_progress.get()));
device_finish = Optional.of(prefix + "Finish");
devices.addPVDevice(new DeviceInfo(device_finish.get()));
}
// Add devices used by commands
DeviceContextHelper.addScanDevices(devices, macros, pre_scan);
DeviceContextHelper.addScanDevices(devices, macros, implementations);
DeviceContextHelper.addScanDevices(devices, macros, post_scan);
// Start Devices
devices.startDevices();
// Execute commands
try
{
// Start all devices, which includes the optional device_state etc.
// This means device_state is not updated until all connect,
// which is probably OK because not really "Running" until they do.
execute(new WaitForDevicesCommandImpl(new WaitForDevicesCommand(devices.getDevices()), null));
// Initialize scan status PVs. Error will prevent scan from starting.
if (device_active.isPresent())
{
getDevice(device_status.get()).write(getName());
ScanCommandUtil.write(this, device_state.get(), getScanState().ordinal());
ScanCommandUtil.write(this, device_active.get(), Double.valueOf(1.0));
ScanCommandUtil.write(this, device_progress.get(), Double.valueOf(0.0));
getDevice(device_finish.get()).write("Starting ...");
}
try
{
// Execute pre-scan commands
execute(pre_scan);
// Reset work step counter to only count the 'main' commands
work_performed.set(0);
// Execute the submitted commands
execute(implementations);
// Successful finish
state.set(ScanState.Finished);
}
finally
{
// Try post-scan commands even if submitted commands ran into problems or were aborted.
// Save the state before going back to Running for post commands.
final long saved_steps = work_performed.get();
final ScanState saved_state = state.getAndSet(ScanState.Running);
execute(post_scan);
// Restore saved state
work_performed.set(saved_steps);
state.set(saved_state);
}
}
catch (Exception ex)
{
if (state.get() == ScanState.Aborted)
error = Optional.of(ScanState.Aborted.name());
else
{
String message = ex.getMessage();
if (message != null)
{ // Remove initial "java..Exception: " because that tends
// to misguide many users in seeing a Java problem instead of
// reading the actual message.
// This tends to happen with nested messages which return
// the 'cause', starting with its class name.
message = java_exception_pattern.matcher(message).replaceFirst("");
error = Optional.of(message);
}
else
error = Optional.of(ex.getClass().getName());
state.set(ScanState.Failed);
logger.log(Level.WARNING, "Scan " + getName() + " failed", ex);
}
}
finally
{
end_ms = System.currentTimeMillis();
// Assert that the state is 'done'
// to exclude this scan from the engine.hasPendingScans() information
state.getAndUpdate(current ->
{
if (current.isDone())
return current;
logger.log(Level.WARNING, "Scan state was %s, changing to Failed", current.toString());
return ScanState.Failed;
});
try
{
// Final status PV update.
if (device_active.isPresent())
{
getDevice(device_status.get()).write("");
ScanCommandUtil.write(this, device_state.get(), getScanState().ordinal(), true, true, device_state.get(), 0.1, timeout);
getDevice(device_finish.get()).write(TimestampFormats.MILLI_FORMAT.format(Instant.now()));
ScanCommandUtil.write(this, device_progress.get(), Double.valueOf(100.0));
// Update to "anything else running?"
final int active = engine.hasPendingScans() ? 1 : 0;
ScanCommandUtil.write(this, device_active.get(), active);
}
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Final Scan status PV update failed", ex);
}
// Stop devices
devices.stopDevices();
}
}
/** {@inheritDoc} */
@Override
public void execute(final List<ScanCommandImpl<?>> commands) throws Exception
{
for (ScanCommandImpl<?> command : commands)
{
final ScanState current_state = state.get();
if (current_state != ScanState.Running &&
current_state != ScanState.Paused)
return;
execute(command);
}
}
/** {@inheritDoc} */
@Override
public void execute(final ScanCommandImpl<?> command) throws Exception
{
active_commands.addLast(command);
try
{
while (state.get() == ScanState.Paused)
{ // Pause until resumed
synchronized (this)
{
wait();
}
}
executeWithRetries(command);
// Try to update Scan PVs on progress. Log errors, but continue scan
if (device_progress.isPresent())
{
final ScanInfo info = getScanInfo();
try
{
ScanCommandUtil.write(this, device_progress.get(), Double.valueOf(info.getPercentage()));
getDevice(device_finish.get()).write(TimestampFormats.formatCompactDateTime(info.getFinishTime()));
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error updating status PVs", ex);
}
}
}
finally
{
active_commands.remove(command);
}
}
/** @param command Command to execute, allowing for error handling and retries
* @throws Exception on error
*/
private void executeWithRetries(final ScanCommandImpl<?> command) throws Exception
{
while (true)
{
try
{
logger.log(Level.INFO, "@{0}: {1}", new Object[] { command.getCommand().getAddress(), command });
command.execute(this);
return; // Command executed without error
}
catch (Exception error)
{ // Was command interrupted on purpose?
// That would typically result in an 'InterruptedException',
// but interrupted command might wrap that into a different type
// of exception
// -> Best way to detect an abort is via the scan state
if (state.get() == ScanState.Aborted)
{
final String message = "Command aborted: " + command.toString();
logger.log(Level.INFO, message, error);
throw error;
}
// Command generated an error
final String message = "Command failed: " + command.toString();
logger.log(Level.WARNING, message, error);
// Error handler determines how to proceed
switch (command.handleError(this, error))
{
case Abort:
// Abort on the original error
throw error;
case Continue:
// Ignore the error, move on
return;
case Retry:
// Stay in 'while' for a retry
}
}
}
}
/** Force transition to next command */
public void next()
{ // Must be running
if (state.get() != ScanState.Running)
return;
// Must have active command
final ScanCommandImpl<?> command = active_commands.peekLast();
if (command == null)
return;
logger.log(Level.INFO, "Forcing transition to next command of " + this);
command.next();
}
/** Pause execution of a currently executing scan */
public void pause()
{
if (! state.compareAndSet(ScanState.Running, ScanState.Paused))
return;
logger.log(Level.INFO, "Pause " + this);
if (device_state.isPresent())
{
try
{
ScanCommandUtil.write(this, device_state.get(), getScanState().ordinal(), true, true, device_state.get(), 0.1, timeout);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error updating state PV", ex);
}
}
}
/** Resume execution of a paused scan */
public void resume()
{
if (! state.compareAndSet(ScanState.Paused, ScanState.Running))
return;
logger.log(Level.INFO, "Resume " + this);
if (device_state.isPresent())
{
try
{
ScanCommandUtil.write(this, device_state.get(), getScanState().ordinal(), true, true, device_state.get(), 0.1, timeout);
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error updating state PV", ex);
}
}
synchronized (this)
{ // Wake thread waiting for Paused state to end
notifyAll();
}
}
/** Ask for execution to stop */
public void abort()
{
// Set state to aborted unless it is already 'done'
final ScanState previous = state.getAndUpdate((current_state) -> current_state.isDone() ? current_state : ScanState.Aborted);
if (! previous.isDone())
logger.log(Level.INFO, "Abort " + this);
if (future.isPresent())
future.get().cancel(true);
synchronized (this)
{
notifyAll();
}
}
/** {@inheritDoc} */
@Override
public void workPerformed(final int work_units)
{
work_performed.addAndGet(work_units);
}
/** Release resources */
@Override
public void close() throws Exception
{
jython.close();
pre_scan.clear();
pre_scan.clear();
implementations.clear();
post_scan.clear();
active_commands.clear();
}
}
|
package org.javamoney.moneybook.chapter.six;
import java.util.stream.Stream;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.convert.ExchangeRateProvider;
import javax.money.convert.MonetaryConversions;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.convert.ConversionOperators;
import org.javamoney.moneta.convert.ExchangeRateType;
import org.javamoney.moneta.function.MonetarySummaryStatistics;
public class AggregateSummaringExchangeRateMonetaryAmount {
public static void main(String[] args) {
CurrencyUnit dollar = Monetary.getCurrency("USD");
CurrencyUnit real = Monetary.getCurrency("BRL");
ExchangeRateProvider provider = MonetaryConversions.getExchangeRateProvider(ExchangeRateType.IMF);
MonetaryAmount money = Money.of(10, dollar);
MonetaryAmount money2 = Money.of(10, real);
MonetaryAmount money3 = Money.of(10, dollar);
MonetaryAmount money4 = Money.of(9, real);
MonetaryAmount money5 = Money.of(25, dollar);
MonetarySummaryStatistics summary = Stream.of(money, money2, money3, money4, money5)
.collect(ConversionOperators.summarizingMonetary(dollar, provider));
MonetaryAmount min = summary.getMin();//USD 2.831248
MonetaryAmount max = summary.getMax();//USD 25
MonetaryAmount average = summary.getAverage();//USD 10.195416
long count = summary.getCount();
MonetaryAmount sum = summary.getSum();//50.97708
}
}
|
package gov.nih.nci.caadapter.hl7.v2v3.tools;
import gov.nih.nci.caadapter.common.function.DateFunction;
import gov.nih.nci.caadapter.common.util.FileUtil;
import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
public class CodeActivationOrDeactivation
{
private String PROTECT_TAG_FILE_NAME = "cloned_caAdapter_by_umkis.txt";
private String CLONED_CAADAPTER_DIR_NAME = "caAdapter_cloned_";
private String CODE_TAG_SOURCE_DEACTIVATE = "//&umkis";
private String CODE_TAG_TARGET_ACTIVATE = "/*&umk*/";
private String CODE_TAG_SOURCE_ACTIVATE = "/*#umk*/";
private String CODE_TAG_TARGET_DEACTIVATE = "//#umkis";
private boolean schemaTag = false;
CodeActivationOrDeactivation(String dirS)
{
doMain(dirS);
}
CodeActivationOrDeactivation(String dirS, boolean schemaTag)
{
this.schemaTag = schemaTag;
doMain(dirS);
}
private void doMain(String dirS)
{
if ((dirS == null)||(dirS.trim().equals("")))
{
System.out.println("Directory is null");
return;
}
dirS = dirS.trim();
File dir = new File(dirS);
if ((!dir.exists())||(!dir.isDirectory()))
{
System.out.println("Directory is not exist. : " + dirS);
return;
}
String dirName = dir.getAbsolutePath();
if (!dirName.endsWith(File.separator)) dirName = dirName + File.separator;
File tagFile = new File(PROTECT_TAG_FILE_NAME);
if ((tagFile.exists())&&(tagFile.isFile()))
{
System.out.println("Source caAdapter dir is already cloned. : ");
return;
}
DateFunction df = new DateFunction();
String currTime = df.getCurrentTime();
dirName = dirName + CLONED_CAADAPTER_DIR_NAME + currTime.substring(0,12);
File dirNew = new File(dirName);
if ((dirNew.exists())&&(dirNew.isDirectory()))
{
System.out.println("This Directory is already exist. : " + dirName);
return;
}
if (!dirNew.mkdir())
{
System.out.println("Directory creation Failure! : " + dirName);
return;
}
dirName = dirName + File.separator;
try
{
saveStringIntoFile(dirName + PROTECT_TAG_FILE_NAME, "Cloned on " + currTime + " from " + FileUtil.getWorkingDirPath());
}
catch(IOException ie)
{
System.out.println("Protect tag file writing error! : " + ie.getMessage());
return;
}
try
{
cloneDirectory(new File(FileUtil.getWorkingDirPath()), dirNew);
String metaInf = FileUtil.searchDir("META-INF", dirNew);
if (metaInf != null)
{
if (!metaInf.endsWith(File.separator)) metaInf = metaInf + File.separator;
File dirNew2 = new File(metaInf + "hl7_home");
if (dirNew2.mkdir()) cloneDirectory(new File(FileUtil.searchDir("hl7_home")), dirNew2);
File dirNew3 = new File(metaInf + "conf");
if (dirNew3.mkdir()) cloneDirectory(new File(FileUtil.searchDir("conf")), dirNew3);
}
}
catch(Exception ie)
{
System.out.println("Error! : " + ie.getMessage());
return;
}
}
private void cloneDirectory(File source, File target) throws IOException
{
if (source == null) throw new IOException("Source dir is null");
if (target == null) throw new IOException("Target dir is null");
if ((!source.exists())||(!source.isDirectory())) throw new IOException("Source dir is not exist.");
if ((!target.exists())||(!target.isDirectory())) throw new IOException("Target dir is not exist.");
File[] list = source.listFiles();
String targetDirName = target.getAbsolutePath();
if (!targetDirName.endsWith(File.separator)) targetDirName = targetDirName + File.separator;
for (File file:list)
{
if (file.isFile())
{
copyFile(file, targetDirName);
continue;
}
else if (!file.isDirectory()) continue;
String dirName = file.getName();
if (dirName.equalsIgnoreCase("cvs")) continue;
if (dirName.equalsIgnoreCase("build")) continue;
if (dirName.equalsIgnoreCase("dist")) continue;
if (dirName.equalsIgnoreCase("dist2")) continue;
if (dirName.equalsIgnoreCase("classes")) continue;
if (dirName.equalsIgnoreCase("gencode")) continue;
if (dirName.equalsIgnoreCase("log")) continue;
//if ((simpleTag)&&(dirName.equalsIgnoreCase("docs"))) continue;
//if ((simpleTag)&&(dirName.equalsIgnoreCase("demo"))) continue;
File newDir = new File(targetDirName + dirName);
if (!newDir.mkdir()) throw new IOException("Sub-Directory creation Failure! : " + targetDirName + dirName);
cloneDirectory(file, newDir);
}
}
private void copyFile(File file, String targetDirName) throws IOException
{
String fileName = file.getName();
if (fileName.equalsIgnoreCase("CodeActivationOrDeactivation.java")) return;
if ((fileName.toLowerCase().startsWith("caadapter"))&&(fileName.toLowerCase().indexOf("_src") > 0)&&(fileName.toLowerCase().endsWith(".zip"))) return;
if ((fileName.toLowerCase().startsWith("caadapter"))&&(fileName.toLowerCase().indexOf("_bin") > 0)&&(fileName.toLowerCase().endsWith(".zip"))) return;
boolean textTag = false;
if (fileName.toLowerCase().endsWith(".java")) textTag = true;
if (fileName.toLowerCase().endsWith(".txt")) textTag = true;
if (fileName.toLowerCase().endsWith(".xml")) textTag = true;
if (fileName.toLowerCase().endsWith(".iml")) textTag = true;
if (fileName.toLowerCase().endsWith(".ipr")) textTag = true;
if (fileName.toLowerCase().endsWith(".iws")) textTag = true;
if (fileName.toLowerCase().endsWith(".properties")) textTag = true;
if (fileName.toLowerCase().endsWith(".property")) textTag = true;
if (fileName.toLowerCase().endsWith(".spp")) textTag = true;
if (fileName.toLowerCase().endsWith(".bat")) textTag = true;
if (fileName.toLowerCase().endsWith(".htm")) textTag = true;
if (fileName.toLowerCase().endsWith(".html")) textTag = true;
if (fileName.toLowerCase().endsWith(".xsd")) textTag = true;
if (fileName.toLowerCase().endsWith(".fls")) textTag = true;
if (fileName.toLowerCase().endsWith(".scs")) textTag = true;
if (fileName.toLowerCase().endsWith(".h3s")) textTag = true;
if (fileName.toLowerCase().endsWith(".map")) textTag = true;
if (fileName.toLowerCase().endsWith(".xmi")) textTag = true;
if (fileName.toLowerCase().endsWith(".vom")) textTag = true;
if (fileName.toLowerCase().endsWith(".dtd")) textTag = true;
if (fileName.toLowerCase().endsWith(".uml")) textTag = true;
if (fileName.toLowerCase().endsWith(".mif")) textTag = true;
if (fileName.toLowerCase().endsWith(".hmd")) textTag = true;
if (fileName.toLowerCase().endsWith(".jsp")) textTag = true;
if (fileName.toLowerCase().endsWith(".csv")) textTag = true;
if (fileName.toLowerCase().endsWith(".js")) textTag = true;
if (fileName.toLowerCase().endsWith(".policy")) textTag = true;
if (fileName.toLowerCase().endsWith(".hl7")) textTag = true;
if (!textTag)
{
if (fileName.equals("mif.zip"))
{
String tempFile = downloadFileFromURL(fileName);
if ((tempFile != null)&&(!tempFile.trim().equals(""))) file = new File(tempFile);
else System.out.println("
}
copyBinaryFile(file, targetDirName);
//copyBinaryFileWithURI(file, targetDirName);
return;
}
boolean downloadTag = false;
//if (fileName.equals("HSMNodePropertiesPane.java")) downloadTag = true;
if (fileName.equals("MapProcessor.java")) downloadTag = true;
if (fileName.equals("DatatypeProcessor.java")) downloadTag = true;
if (fileName.equals("XMLElement.java")) downloadTag = true;
if (fileName.equals("StringFunction.java")) downloadTag = true;
if (fileName.equals("MapProcessorHelper.java")) downloadTag = true;
if (fileName.equals("caAdapterTransformationService.java")) downloadTag = true;
if (fileName.equals("run.bat")) downloadTag = true;
if (fileName.equals("build.properties")) downloadTag = true;
if (fileName.equals("Attribute.java"))
{
if (targetDirName.indexOf("transformation") > 0) downloadTag = true;
}
if (fileName.equals("web.xml")) downloadTag = true;
if (fileName.equals("AddNewScenario.java"))
{
List<String> list = new ArrayList<String>();
String d = targetDirName + "stellar" + File.separator;
File dD = new File(d);
if ((!dD.exists())||(!dD.isDirectory()))
{
if (!dD.mkdirs())
{
System.out.println("
return;
}
}
list.add("CaAdapterUserWorks.java");
list.add("CaadapterWSUtil.java");
list.add("DeleteOutputFile.java");
list.add("DosFileHandler.java");
list.add("FileUploaderWS.java");
list.add("GeneralUtilitiesWS.java");
list.add("ManageCaadapterWSUser.java");
list.add("MultipartRequest.java");
list.add("ScenarioFileRegistration.java");
list.add("TestIPAddress.java");
list.add("TransformationServiceOnWeb.java");
list.add("MenuStart.java");
list.add("TransformationServiceMain.java");
list.add("TransformationServiceWithWSDL.java");
for(String line:list)
{
File f = new File(d + line);
copyFile(f, d);
}
}
if ((!file.exists())||(!file.isFile()))
{
downloadTag = true;
}
String oriFile = "";
if (downloadTag)
{
String tempFile = downloadFileFromURL(fileName);
if ((tempFile == null)||(tempFile.equals("")))
{
System.out.println("
return;
}
else
{
System.out.println("-- Downloaded File : " + fileName);
oriFile = tempFile;
}
}
else oriFile = file.getAbsolutePath();
System.out.println("Copy file (text) : " + targetDirName + fileName);
saveStringIntoFile(targetDirName + fileName, FileUtil.readFileIntoList(oriFile));
}
private String downloadFileFromURL(String fileName)
{
String[] urls = new String[] {"http://10.1.1.61:8080/file_exchange/",
"http://155.230.210.233:8080/file_exchange/"};
String tempFile = null;
for(int i=0;i<urls.length;i++)
{
try
{
tempFile = FileUtil.downloadFromURLtoTempFile(urls[i] + fileName);
}
catch(IOException ie)
{
tempFile = null;
}
if ((tempFile != null)&&(!tempFile.trim().equals("")))
{
tempFile = tempFile.trim();
break;
}
}
return tempFile;
}
private void copyBinaryFileWithURI(File file, String targetDirName) throws IOException
{
String uri = file.toURI().toString();
String url = file.toURI().toURL().toString();
//System.out.println("FFF : " + file.getAbsolutePath() + " : " + uri + " : " + url);
if (url.toLowerCase().startsWith("file:
else if (url.toLowerCase().startsWith("file://")) url = url.replace("file://", "file:///");
else if (url.toLowerCase().startsWith("file:/")) url = url.replace("file:/", "file:
System.out.println("Copy file (binary) : " + url);
String name = FileUtil.downloadFromURLtoTempFile(url);
File r = new File(name);
r.renameTo(new File(targetDirName + file.getName()));
}
private void copyBinaryFile(File file, String targetDirName) throws IOException
{
String fileName = file.getName();
System.out.print("Copy file (binary) : " + targetDirName + fileName);
//DataInputStream distr = null;
FileInputStream fis = null;
FileOutputStream fos = null;
//DataOutputStream dos2 = null;
try
{
fis = new FileInputStream(file);
//distr = new DataInputStream(fis);
fos = new FileOutputStream(targetDirName + fileName);
//dos2 = new DataOutputStream(fos);
byte nn = 0;
boolean endSig = false;
byte[] bytes = new byte[fis.available()];
int n = 0;
while(true)
{
int q = -1;
q = fis.read(bytes);
if (q != bytes.length)
{
System.out.println(" : ERROR => Different length : " + q + " : " + bytes.length);
break;
}
else System.out.println(" : *** GOOD => File length : " + q);
fos.write(bytes);
break;
}
}
catch(IOException cse)
{
throw new IOException("Binary File Input failure... (IOException) " + cse.getMessage());
}
catch(Exception ne)
{
throw new IOException("Binary File Input failure... (Excep) " + ne.getMessage());
}
finally
{
if (fis != null) fis.close();
//if (distr != null) distr.close();
if (fos != null) fos.close();
//if (dos2 != null) dos2.close();
}
if ((schemaTag)&&(fileName.equalsIgnoreCase("schemas.zip"))) extractSchemaZipFile(file, targetDirName);
}
private void extractSchemaZipFile(File file, String targetDirName) throws IOException
{
File f = new File(targetDirName + "schemas");
if (!f.mkdir()) throw new IOException("Schema directory creation failure : " + targetDirName);
String schemaDir = targetDirName + "schemas" + File.separator;
ZipFile xsdZipFile=new ZipFile(file);
if (xsdZipFile == null) throw new IOException("Schema zip file object creation failure : " + targetDirName);
Enumeration<? extends ZipEntry> enumer = xsdZipFile.entries();
while(enumer.hasMoreElements())
{
ZipEntry entry = enumer.nextElement();
String entryName = entry.getName();
if (!File.separator.equals("/"))
{
entryName = entryName.replace("/", File.separator);
}
String name = schemaDir + entryName;
if (entry.isDirectory())
{
File fl = new File(name);
if (!fl.mkdirs()) throw new IOException("Schema zip entry directory creation failure : " + schemaDir + entryName);
else System.out.println(" Success sub directory creation for Schema zip entry 1 : " + schemaDir + entryName);
continue;
}
int idx = name.lastIndexOf(File.separator);
String par = name.substring(0, idx);
File fl = new File(par);
if ((!fl.exists())||(!fl.isDirectory()))
{
if (!fl.mkdirs()) throw new IOException("Schema sub directory creation failure : " + par);
else System.out.println(" Success sub directory creation for Schema zip entry 2 : " + par);
}
FileOutputStream fos = null;
//DataOutputStream dos2 = null;
int cnt =0;
try
{
//byte[] bytes = new byte[(int)entry.getSize()];
InputStream stream = xsdZipFile.getInputStream(entry);
//byte[] bytes = new byte[stream.available()];
//cnt = stream.read(bytes);
//if (cnt != bytes.length) throw new IOException("Unmatched entry size ("+cnt+" : "+bytes.length+") : " + name);
fos = new FileOutputStream(name);
while(true)
{
int bt = 0;
try
{
bt = stream.read();
}
catch(java.io.EOFException ee)
{
break;
}
if (bt < 0) break;
fos.write(bt);
}
}
catch(IOException cse)
{
throw new IOException("Schema zip entry write failure... (IOException) " + cse.getMessage());
}
catch(Exception ne)
{
ne.printStackTrace();
throw new IOException("Schema zip entry write failure... (Excep) " + ne.getMessage());
}
finally
{
if (fos != null) fos.close();
}
System.out.println(" Success writing Schema zip entry : " + name);
}
}
private void copyBinaryFileWithDataStream(File file, String targetDirName) throws IOException
{
String fileName = file.getName();
System.out.println("Copy file (binary) : " + targetDirName + fileName);
DataInputStream distr = null;
FileInputStream fis = null;
FileOutputStream fos = null;
DataOutputStream dos2 = null;
try
{
fis = new FileInputStream(file);
distr = new DataInputStream(fis);
fos = new FileOutputStream(targetDirName + fileName);
dos2 = new DataOutputStream(fos);
byte nn = 0;
boolean endSig = false;
byte[] bytes = new byte[fis.available()];
int n = 0;
while(true)
{
int q = -1;
for(int i=0;i<bytes.length;i++)
{
try
{
bytes[i] = distr.readByte();
}
catch(EOFException ie)
{
endSig = true;
}
if (endSig) break;
q = i;
}
if (q == (bytes.length - 1)) dos2.write(bytes);
else for(int i=0;i<q;i++) dos2.writeByte(bytes[i]);
//dos2.writeByte(nn);
if (endSig) break;
}
}
catch(IOException cse)
{
throw new IOException("Binary File Input failure... (IOException) " + cse.getMessage());
}
catch(Exception ne)
{
throw new IOException("Binary File Input failure... (Excep) " + ne.getMessage());
}
finally
{
if (fis != null) fis.close();
if (distr != null) distr.close();
if (fos != null) fos.close();
if (dos2 != null) dos2.close();
}
}
private void saveStringIntoFile(String fileName, String string) throws IOException
{
List<String> list = new ArrayList<String>();
list.add(string);
saveStringIntoFile(fileName, list);
}
private void saveStringIntoFile(String fileName, List<String> string) throws IOException
{
FileWriter fw = null;
try
{
fw = new FileWriter(fileName);
for (int i=0;i<string.size();i++)
{
String line = string.get(i);
if (fileName.toLowerCase().endsWith(".java"))
{
line = replaceDeactivateTag(line, CODE_TAG_SOURCE_DEACTIVATE);
line = replaceActivateTag(line, CODE_TAG_SOURCE_ACTIVATE, CODE_TAG_TARGET_DEACTIVATE);
}
fw.write(line + "\r\n");
}
}
catch(Exception ie)
{
throw new IOException("File Writing Error(" + fileName + ") : " + ie.getMessage() + ", value : " + string);
}
finally
{
if (fw != null) fw.close();
}
}
private String replaceActivateTag(String line, String from, String to)
{
int idx = line.toLowerCase().indexOf(from);
if (idx < 0) return line;
else if (idx == 0) return to + line.substring(from.length());
return line.substring(0, idx) + to + line.substring(idx + from.length());
}
private String replaceDeactivateTag(String line, String from)
{
int idx = line.toLowerCase().indexOf(from);
if (idx < 0) return line;
else if (idx == 0) return line.substring(from.length()) + " " +from;
return line;
}
public static void main(String[] arg)
{
new CodeActivationOrDeactivation("c:\\clone_caAdapter");
//new CodeActivationOrDeactivation("c:\\clone_caAdapter", true);
}
}
|
package org.jboss.as.clustering.jgroups.subsystem;
import java.util.function.UnaryOperator;
import org.jboss.as.clustering.controller.CapabilityProvider;
import org.jboss.as.clustering.controller.ChildResourceDefinition;
import org.jboss.as.clustering.controller.ManagementResourceRegistration;
import org.jboss.as.clustering.controller.OperationHandler;
import org.jboss.as.clustering.controller.Operations;
import org.jboss.as.clustering.controller.ResourceDescriptor;
import org.jboss.as.clustering.controller.ResourceServiceBuilderFactory;
import org.jboss.as.clustering.controller.ResourceServiceHandler;
import org.jboss.as.clustering.controller.SimpleResourceRegistration;
import org.jboss.as.clustering.controller.UnaryRequirementCapability;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.transform.ResourceTransformationContext;
import org.jboss.as.controller.transform.ResourceTransformer;
import org.jboss.as.controller.transform.description.DiscardAttributeChecker;
import org.jboss.as.controller.transform.description.RejectAttributeChecker;
import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.clustering.jgroups.spi.ChannelFactory;
import org.wildfly.clustering.jgroups.spi.JGroupsRequirement;
import org.wildfly.clustering.service.UnaryRequirement;
public class StackResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> {
public static final PathElement WILDCARD_PATH = pathElement(PathElement.WILDCARD_VALUE);
public static PathElement pathElement(String name) {
return PathElement.pathElement("stack", name);
}
enum Attribute implements org.jboss.as.clustering.controller.Attribute {
STATISTICS_ENABLED(ModelDescriptionConstants.STATISTICS_ENABLED, ModelType.BOOLEAN, builder -> builder.setDefaultValue(new ModelNode(false))),
;
private final AttributeDefinition definition;
Attribute(String name, ModelType type, UnaryOperator<SimpleAttributeDefinitionBuilder> configurator) {
this.definition = configurator.apply(new SimpleAttributeDefinitionBuilder(name, type)
.setRequired(false)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
).build();
}
@Override
public AttributeDefinition getDefinition() {
return this.definition;
}
}
enum Capability implements CapabilityProvider {
JCHANNEL_FACTORY(JGroupsRequirement.CHANNEL_FACTORY),
;
private final org.jboss.as.clustering.controller.Capability capability;
Capability(UnaryRequirement requirement) {
this.capability = new UnaryRequirementCapability(requirement);
}
@Override
public org.jboss.as.clustering.controller.Capability getCapability() {
return this.capability;
}
}
@Deprecated
static final ObjectTypeAttributeDefinition TRANSPORT = ObjectTypeAttributeDefinition.Builder.of(TransportResourceDefinition.WILDCARD_PATH.getKey(), AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.getDefinition(), TransportResourceDefinition.Attribute.SHARED.getDefinition(), TransportResourceDefinition.Attribute.SOCKET_BINDING.getDefinition(), TransportResourceDefinition.Attribute.DIAGNOSTICS_SOCKET_BINDING.getDefinition(), TransportResourceDefinition.ThreadingAttribute.DEFAULT_EXECUTOR.getDefinition(), TransportResourceDefinition.ThreadingAttribute.OOB_EXECUTOR.getDefinition(), TransportResourceDefinition.ThreadingAttribute.TIMER_EXECUTOR.getDefinition(), TransportResourceDefinition.ThreadingAttribute.THREAD_FACTORY.getDefinition(), TransportResourceDefinition.Attribute.SITE.getDefinition(), TransportResourceDefinition.Attribute.RACK.getDefinition(), TransportResourceDefinition.Attribute.MACHINE.getDefinition(), AbstractProtocolResourceDefinition.Attribute.PROPERTIES.getDefinition())
.setDeprecated(JGroupsModel.VERSION_3_0_0.getVersion())
.setRequired(false)
.setSuffix(null)
.build();
@Deprecated
static final ObjectTypeAttributeDefinition PROTOCOL = ObjectTypeAttributeDefinition.Builder.of(ProtocolResourceDefinition.WILDCARD_PATH.getKey(), AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.getDefinition(), GenericProtocolResourceDefinition.DeprecatedAttribute.SOCKET_BINDING.getDefinition(), AbstractProtocolResourceDefinition.Attribute.PROPERTIES.getDefinition())
.setRequired(false)
.setSuffix("protocol")
.build();
@Deprecated
static final AttributeDefinition PROTOCOLS = ObjectListAttributeDefinition.Builder.of("protocols", PROTOCOL)
.setDeprecated(JGroupsModel.VERSION_3_0_0.getVersion())
.setRequired(false)
.build();
static void buildTransformation(ModelVersion version, ResourceTransformationDescriptionBuilder parent) {
ResourceTransformationDescriptionBuilder builder = parent.addChildResource(WILDCARD_PATH);
if (JGroupsModel.VERSION_4_1_0.requiresTransformation(version)) {
builder.getAttributeBuilder()
.setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(true)), Attribute.STATISTICS_ENABLED.getDefinition())
.addRejectCheck(RejectAttributeChecker.UNDEFINED, Attribute.STATISTICS_ENABLED.getDefinition())
.addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, Attribute.STATISTICS_ENABLED.getDefinition())
.addRejectCheck(new RejectAttributeChecker.SimpleRejectAttributeChecker(new ModelNode(false)), Attribute.STATISTICS_ENABLED.getDefinition())
.end();
}
if (JGroupsModel.VERSION_3_0_0.requiresTransformation(version)) {
// Create legacy "protocols" attributes, which lists protocols by name
ResourceTransformer transformer = new ResourceTransformer() {
@Override
public void transformResource(ResourceTransformationContext context, PathAddress address, Resource resource) throws OperationFailedException {
for (String name : resource.getChildrenNames(ProtocolResourceDefinition.WILDCARD_PATH.getKey())) {
resource.getModel().get(PROTOCOLS.getName()).add(name);
}
context.addTransformedResource(PathAddress.EMPTY_ADDRESS, resource).processChildren(resource);
}
};
builder.setCustomResourceTransformer(transformer);
}
if (JGroupsModel.VERSION_2_0_0.requiresTransformation(version)) {
builder.rejectChildResource(RelayResourceDefinition.PATH);
} else {
RelayResourceDefinition.buildTransformation(version, builder);
}
TransportResourceDefinition.buildTransformation(version, builder);
ProtocolRegistration.buildTransformation(version, builder);
}
private final ResourceServiceBuilderFactory<ChannelFactory> builderFactory = address -> new JChannelFactoryBuilder(address);
// registration
public StackResourceDefinition() {
super(WILDCARD_PATH, new JGroupsResourceDescriptionResolver(WILDCARD_PATH));
}
@SuppressWarnings("deprecation")
@Override
public void register(ManagementResourceRegistration parentRegistration) {
ManagementResourceRegistration registration = parentRegistration.registerSubModel(this);
ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver())
.addAttributes(Attribute.class)
.addExtraParameters(TRANSPORT, PROTOCOLS)
.addCapabilities(Capability.class)
.setAddOperationTransformation(handler -> (context, operation) -> {
if (operation.hasDefined(TRANSPORT.getName())) {
PathAddress address = context.getCurrentAddress();
ModelNode transport = operation.get(TRANSPORT.getName());
String type = AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.resolveModelAttribute(context, transport).asString();
PathElement transportPath = TransportResourceDefinition.pathElement(type);
PathAddress transportAddress = address.append(transportPath);
ModelNode transportOperation = Util.createAddOperation(transportAddress);
OperationEntry addOperationEntry = context.getResourceRegistration().getOperationEntry(PathAddress.pathAddress(TransportResourceDefinition.WILDCARD_PATH), ModelDescriptionConstants.ADD);
for (AttributeDefinition attribute : addOperationEntry.getOperationDefinition().getParameters()) {
String name = attribute.getName();
if (transport.hasDefined(name)) {
transportOperation.get(name).set(transport.get(name));
}
}
context.addStep(transportOperation, addOperationEntry.getOperationHandler(), OperationContext.Stage.MODEL);
}
if (operation.hasDefined(PROTOCOLS.getName())) {
PathAddress address = context.getCurrentAddress();
for (ModelNode protocol : operation.get(PROTOCOLS.getName()).asList()) {
String type = AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.resolveModelAttribute(context, protocol).asString();
PathElement protocolPath = ProtocolResourceDefinition.pathElement(type);
PathAddress protocolAddress = address.append(protocolPath);
ModelNode protocolOperation = Util.createAddOperation(protocolAddress);
OperationEntry addOperationEntry = context.getResourceRegistration().getOperationEntry(PathAddress.pathAddress(ProtocolResourceDefinition.WILDCARD_PATH), ModelDescriptionConstants.ADD);
for (AttributeDefinition attribute : addOperationEntry.getOperationDefinition().getParameters()) {
String name = attribute.getName();
if (protocol.hasDefined(name)) {
protocolOperation.get(name).set(protocol.get(name));
}
}
context.addStep(protocolOperation, addOperationEntry.getOperationHandler(), OperationContext.Stage.MODEL);
}
}
handler.execute(context, operation);
})
;
ResourceServiceHandler handler = new StackServiceHandler(this.builderFactory);
new SimpleResourceRegistration(descriptor, handler).register(registration);
OperationDefinition legacyAddProtocolOperation = new SimpleOperationDefinitionBuilder("add-protocol", this.getResourceDescriptionResolver())
.setParameters(SocketBindingProtocolResourceDefinition.Attribute.SOCKET_BINDING.getDefinition())
.addParameter(AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.getDefinition())
.addParameter(AbstractProtocolResourceDefinition.Attribute.PROPERTIES.getDefinition())
.setDeprecated(JGroupsModel.VERSION_3_0_0.getVersion())
.build();
// Transform legacy /subsystem=jgroups/stack=*:add-protocol() operation -> /subsystem=jgroups/stack=*/protocol=*:add()
OperationStepHandler legacyAddProtocolHandler = new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) {
operationDeprecated(context, operation);
PathAddress address = context.getCurrentAddress();
String protocol = operation.require(AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.getName()).asString();
PathElement protocolPath = ProtocolResourceDefinition.pathElement(protocol);
PathAddress protocolAddress = address.append(protocolPath);
ModelNode protocolOperation = Util.createAddOperation(protocolAddress);
OperationEntry addOperationEntry = context.getResourceRegistration().getOperationEntry(PathAddress.pathAddress(ProtocolResourceDefinition.WILDCARD_PATH), ModelDescriptionConstants.ADD);
for (AttributeDefinition attribute : addOperationEntry.getOperationDefinition().getParameters()) {
String name = attribute.getName();
if (operation.hasDefined(name)) {
protocolOperation.get(name).set(operation.get(name));
}
}
context.addStep(protocolOperation, addOperationEntry.getOperationHandler(), OperationContext.Stage.MODEL);
}
};
registration.registerOperationHandler(legacyAddProtocolOperation, legacyAddProtocolHandler);
OperationDefinition legacyRemoveProtocolOperation = new SimpleOperationDefinitionBuilder("remove-protocol", this.getResourceDescriptionResolver())
.setParameters(AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.getDefinition())
.setDeprecated(JGroupsModel.VERSION_3_0_0.getVersion())
.build();
// Transform legacy /subsystem=jgroups/stack=*:remove-protocol() operation -> /subsystem=jgroups/stack=*/protocol=*:remove()
OperationStepHandler legacyRemoveProtocolHandler = new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) {
operationDeprecated(context, operation);
PathAddress address = context.getCurrentAddress();
String protocol = operation.require(AbstractProtocolResourceDefinition.DeprecatedAttribute.TYPE.getName()).asString();
PathElement protocolPath = ProtocolResourceDefinition.pathElement(protocol);
PathAddress protocolAddress = address.append(protocolPath);
ModelNode removeOperation = Util.createRemoveOperation(protocolAddress);
context.addStep(removeOperation, context.getResourceRegistration().getOperationHandler(PathAddress.pathAddress(ProtocolResourceDefinition.WILDCARD_PATH), ModelDescriptionConstants.REMOVE), context.getCurrentStage());
}
};
registration.registerOperationHandler(legacyRemoveProtocolOperation, legacyRemoveProtocolHandler);
if (registration.isRuntimeOnlyRegistrationValid()) {
new OperationHandler<>(new StackOperationExecutor(), StackOperation.class).register(registration);
}
new TransportRegistration(this.builderFactory).register(registration);
new ProtocolRegistration(this.builderFactory).register(registration);
new RelayResourceDefinition(this.builderFactory).register(registration);
}
static void operationDeprecated(OperationContext context, ModelNode operation) {
ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(Operations.getName(operation), context.getCurrentAddress().toCLIStyleString());
}
}
|
package org.chromium.sdk.wip;
/**
* Abstract interface to WIP implementation, that is delivered in a separate library.
* It allows to have several versions of implementation in the system at the same time,
* which may be needed because WIP is not stable yet and is evolving quite rapidly.
* <p>
* A particular set-up should choose it's own way to get backed instances. For example
* Eclipse may use its extension point mechanism. Other frameworks can dynamically instantiate
* {@link Factory}.
*/
public interface WipBackend {
/**
* @return a unique name of backend implementation
*/
String getId();
/**
* @return a human-readable implementation description that should help to tell what protocol
* version it supports
*/
String getDescription();
/**
* Used to dynamically instantiate {@link WipBackend}. Instance of {@link Factory} should be
* available via {@link ClassLoader}.
*/
interface Factory {
WipBackend create();
}
}
|
package toxi.processing;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Logger;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
import toxi.geom.AABB;
import toxi.geom.AxisAlignedCylinder;
import toxi.geom.Cone;
import toxi.geom.Ellipse;
import toxi.geom.Line2D;
import toxi.geom.Line3D;
import toxi.geom.Plane;
import toxi.geom.Ray2D;
import toxi.geom.Ray3D;
import toxi.geom.Rect;
import toxi.geom.Sphere;
import toxi.geom.Triangle;
import toxi.geom.Triangle2D;
import toxi.geom.Vec2D;
import toxi.geom.Vec3D;
import toxi.geom.mesh.TriangleMesh;
/**
* In addition to providing new drawing commands, this class provides wrappers
* for using datatypes of the toxiclibs core package directly with Processing's
* drawing commands. The class can be configured to work with any PGraphics
* instance (incl. offscreen buffers).
*/
public class ToxiclibsSupport {
protected static final Logger logger =
Logger.getLogger(ToxiclibsSupport.class.getName());
protected PApplet app;
protected PGraphics gfx;
public ToxiclibsSupport(PApplet app) {
this(app, app.g);
}
public ToxiclibsSupport(PApplet app, PGraphics gfx) {
this.app = app;
this.gfx = gfx;
}
public final void box(AABB box) {
mesh(box.toMesh(), false, 0);
}
public final void box(AABB box, boolean smooth) {
TriangleMesh mesh = box.toMesh();
if (smooth) {
mesh.computeVertexNormals();
}
mesh(mesh, smooth, 0);
}
public final void cone(Cone cone) {
mesh(cone.toMesh(6), false, 0);
}
public final void cone(Cone cone, int res, boolean smooth) {
TriangleMesh mesh = cone.toMesh(res);
if (smooth) {
mesh.computeVertexNormals();
}
mesh(mesh, smooth, 0);
}
public final void cylinder(AxisAlignedCylinder cylinder) {
mesh(cylinder.toMesh(), false, 0);
}
public final void cylinder(AxisAlignedCylinder cylinder, int res,
boolean smooth) {
TriangleMesh mesh = cylinder.toMesh(res, 0);
if (smooth) {
mesh.computeVertexNormals();
}
mesh(mesh, smooth, 0);
}
public final void ellipse(Ellipse e) {
Vec2D r = e.getRadii();
switch (gfx.ellipseMode) {
case PConstants.CENTER:
gfx.ellipse(e.x, e.y, r.x * 2, r.y * 2);
break;
case PConstants.RADIUS:
gfx.ellipse(e.x, e.y, r.x, r.y);
break;
case PConstants.CORNER:
case PConstants.CORNERS:
gfx.ellipse(e.x - r.x, e.y - r.y, r.x * 2, r.y * 2);
break;
default:
logger.warning("invalid ellipse mode: " + gfx.ellipseMode);
}
}
/**
* @return the gfx
*/
public PGraphics getGraphics() {
return gfx;
}
public final void line(Line2D line) {
gfx.line(line.a.x, line.a.y, line.b.x, line.b.y);
}
public final void line(Line3D line) {
gfx.line(line.a.x, line.a.y, line.a.z, line.b.x, line.b.y, line.b.z);
}
public final void lineStrip2D(ArrayList<Vec2D> points) {
boolean isFilled = gfx.fill;
gfx.fill = false;
processVertices2D(points.iterator(), PConstants.POLYGON);
gfx.fill = isFilled;
}
public final void lineStrip3D(ArrayList<? extends Vec3D> points) {
boolean isFilled = gfx.fill;
gfx.fill = false;
processVertices3D(points.iterator(), PConstants.POLYGON);
gfx.fill = isFilled;
}
public final void mesh(TriangleMesh mesh) {
mesh(mesh, false, 0);
}
public final void mesh(TriangleMesh mesh, boolean smooth) {
mesh(mesh, smooth, 0);
}
public void mesh(TriangleMesh mesh, boolean smooth, float normalLength) {
gfx.beginShape(PConstants.TRIANGLES);
if (smooth) {
for (TriangleMesh.Face f : mesh.faces) {
gfx.normal(f.a.normal.x, f.a.normal.y, f.a.normal.z);
gfx.vertex(f.a.x, f.a.y, f.a.z);
gfx.normal(f.b.normal.x, f.b.normal.y, f.b.normal.z);
gfx.vertex(f.b.x, f.b.y, f.b.z);
gfx.normal(f.c.normal.x, f.c.normal.y, f.c.normal.z);
gfx.vertex(f.c.x, f.c.y, f.c.z);
}
} else {
for (TriangleMesh.Face f : mesh.faces) {
gfx.normal(f.normal.x, f.normal.y, f.normal.z);
gfx.vertex(f.a.x, f.a.y, f.a.z);
gfx.vertex(f.b.x, f.b.y, f.b.z);
gfx.vertex(f.c.x, f.c.y, f.c.z);
}
}
gfx.endShape();
if (normalLength > 0) {
int strokeCol = 0;
boolean isStroked = gfx.stroke;
if (isStroked) {
strokeCol = gfx.strokeColor;
}
if (smooth) {
for (TriangleMesh.Vertex v : mesh.vertices.values()) {
Vec3D w = v.add(v.normal.scale(normalLength));
Vec3D n = v.normal.scale(127);
gfx.stroke(n.x + 128, n.y + 128, n.z + 128);
gfx.line(v.x, v.y, v.z, w.x, w.y, w.z);
}
} else {
float third = 1f / 3;
for (TriangleMesh.Face f : mesh.faces) {
Vec3D c = f.a.add(f.b).addSelf(f.c).scaleSelf(third);
Vec3D d = c.add(f.normal.scale(normalLength));
Vec3D n = f.normal.scale(127);
gfx.stroke(n.x + 128, n.y + 128, n.z + 128);
gfx.line(c.x, c.y, c.z, d.x, d.y, d.z);
}
}
if (isStroked) {
gfx.stroke(strokeCol);
} else {
gfx.noStroke();
}
}
}
public final void plane(Plane plane, float size) {
mesh(plane.toMesh(size), false, 0);
}
public final void point(Vec2D v) {
gfx.point(v.x, v.y);
}
public final void point(Vec3D v) {
gfx.point(v.x, v.y, v.z);
}
public final void points2D(ArrayList<? extends Vec2D> points) {
processVertices2D(points.iterator(), PConstants.POINTS);
}
public final void points2D(Iterator<? extends Vec2D> iterator) {
processVertices2D(iterator, PConstants.POINTS);
}
public final void points3D(ArrayList<? extends Vec3D> points) {
processVertices3D(points.iterator(), PConstants.POINTS);
}
public final void points3D(Iterator<? extends Vec3D> iterator) {
processVertices3D(iterator, PConstants.POINTS);
}
protected void processVertices2D(Iterator<? extends Vec2D> iterator,
int shapeID) {
gfx.beginShape(shapeID);
while (iterator.hasNext()) {
Vec2D v = iterator.next();
gfx.vertex(v.x, v.y);
}
gfx.endShape();
}
public final void processVertices3D(Iterator<? extends Vec3D> iterator,
int shapeID) {
gfx.beginShape(shapeID);
while (iterator.hasNext()) {
Vec3D v = iterator.next();
gfx.vertex(v.x, v.y, v.z);
}
gfx.endShape();
}
public final void ray(Ray2D ray, float length) {
Vec2D e = ray.getPointAtDistance(length);
gfx.line(ray.x, ray.y, e.x, e.y);
}
public final void ray(Ray3D ray, float length) {
Vec3D e = ray.getPointAtDistance(length);
gfx.line(ray.x, ray.y, ray.z, e.x, e.y, e.z);
}
public final void rect(Rect r) {
switch (gfx.rectMode) {
case PConstants.CORNER:
gfx.rect(r.x, r.y, r.width, r.height);
break;
case PConstants.CORNERS:
gfx.rect(r.x, r.y, r.x + r.width, r.y + r.height);
break;
case PConstants.CENTER:
gfx.rect(r.x + r.width * 0.5f, r.y + r.height * 0.5f, r.width,
r.height);
break;
case PConstants.RADIUS:
float rw = r.width * 0.5f;
float rh = r.height * 0.5f;
gfx.rect(r.x + rw, r.y + rh, rw, rh);
break;
default:
logger.warning("invalid rect mode: " + gfx.rectMode);
}
}
/**
* @param gfx
* the gfx to set
*/
public void setGraphics(PGraphics gfx) {
this.gfx = gfx;
}
// TODO replace with mesh drawing, blocked by issue
public final void sphere(Sphere sphere) {
gfx.pushMatrix();
gfx.translate(sphere.x, sphere.y, sphere.z);
gfx.sphere(sphere.radius);
gfx.popMatrix();
}
public final void triangle(Triangle tri, boolean isFullShape) {
if (isFullShape) {
gfx.beginShape(PConstants.TRIANGLES);
}
Vec3D n = tri.computeNormal();
gfx.normal(n.x, n.y, n.z);
gfx.vertex(tri.a.x, tri.a.y, tri.a.z);
gfx.vertex(tri.b.x, tri.b.y, tri.b.z);
gfx.vertex(tri.c.x, tri.c.y, tri.c.z);
if (isFullShape) {
gfx.endShape();
}
}
public final void triangle(Triangle2D tri, boolean isFullShape) {
if (isFullShape) {
gfx.beginShape(PConstants.TRIANGLES);
}
gfx.vertex(tri.a.x, tri.a.y);
gfx.vertex(tri.b.x, tri.b.y);
gfx.vertex(tri.c.x, tri.c.y);
if (isFullShape) {
gfx.endShape();
}
}
public final void vertex(Vec2D v) {
gfx.vertex(v.x, v.y);
}
public final void vertex(Vec3D v) {
gfx.vertex(v.x, v.y, v.z);
}
}
|
package services.player;
import intents.GalacticIntent;
import intents.PlayerEventIntent;
import intents.ZoneInIntent;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import main.ProjectSWG;
import network.packets.Packet;
import network.packets.soe.SessionRequest;
import network.packets.swg.login.AccountFeatureBits;
import network.packets.swg.login.ClientIdMsg;
import network.packets.swg.login.ClientPermissionsMessage;
import network.packets.swg.login.ServerId;
import network.packets.swg.login.ServerString;
import network.packets.swg.login.creation.ClientVerifyAndLockNameRequest;
import network.packets.swg.login.creation.ClientVerifyAndLockNameResponse;
import network.packets.swg.login.creation.ClientCreateCharacter;
import network.packets.swg.login.creation.ClientVerifyAndLockNameResponse.ErrorMessage;
import network.packets.swg.login.creation.CreateCharacterFailure;
import network.packets.swg.login.creation.CreateCharacterFailure.NameFailureReason;
import network.packets.swg.login.creation.CreateCharacterSuccess;
import network.packets.swg.login.creation.RandomNameRequest;
import network.packets.swg.login.creation.RandomNameResponse;
import network.packets.swg.zone.CmdSceneReady;
import network.packets.swg.zone.GalaxyLoopTimesRequest;
import network.packets.swg.zone.GalaxyLoopTimesResponse;
import network.packets.swg.zone.HeartBeatMessage;
import network.packets.swg.zone.ParametersMessage;
import network.packets.swg.zone.SetWaypointColor;
import network.packets.swg.zone.ShowBackpack;
import network.packets.swg.zone.ShowHelmet;
import network.packets.swg.zone.UpdatePvpStatusMessage;
import network.packets.swg.zone.chat.ChatOnConnectAvatar;
import network.packets.swg.zone.chat.ChatSystemMessage;
import network.packets.swg.zone.chat.VoiceChatStatus;
import network.packets.swg.zone.insertion.ChatServerStatus;
import network.packets.swg.zone.insertion.CmdStartScene;
import resources.Galaxy;
import resources.Location;
import resources.Race;
import resources.Terrain;
import resources.client_info.ClientFactory;
import resources.client_info.visitors.ProfTemplateData;
import resources.config.ConfigFile;
import resources.control.Intent;
import resources.control.Service;
import resources.objects.SWGObject;
import resources.objects.creature.CreatureMood;
import resources.objects.creature.CreatureObject;
import resources.objects.player.PlayerObject;
import resources.objects.tangible.TangibleObject;
import resources.objects.waypoint.WaypointObject;
import resources.objects.waypoint.WaypointObject.WaypointColor;
import resources.player.AccessLevel;
import resources.player.Player;
import resources.player.PlayerEvent;
import resources.player.PlayerFlags;
import resources.player.PlayerState;
import resources.server_info.Config;
import resources.server_info.Log;
import resources.zone.NameFilter;
import services.objects.ObjectManager;
import utilities.namegen.SWGNameGenerator;
public class ZoneService extends Service {
private final Map <String, Player> lockedNames;
private final Map <String, ProfTemplateData> profTemplates;
private final NameFilter nameFilter;
private final SWGNameGenerator nameGenerator;
private final CharacterCreationRestriction creationRestriction;
private PreparedStatement createCharacter;
private PreparedStatement getCharacter;
private PreparedStatement getLikeCharacterName;
private String commitHistory;
public ZoneService() {
lockedNames = new HashMap<String, Player>();
profTemplates = new ConcurrentHashMap<String, ProfTemplateData>();
nameFilter = new NameFilter("namegen/bad_word_list.txt", "namegen/reserved_words.txt", "namegen/fiction_reserved.txt");
nameGenerator = new SWGNameGenerator(nameFilter);
creationRestriction = new CharacterCreationRestriction(2);
commitHistory = "";
}
@Override
public boolean initialize() {
String createCharacterSql = "INSERT INTO characters (id, name, race, userId, galaxyId) VALUES (?, ?, ?, ?, ?)";
createCharacter = getLocalDatabase().prepareStatement(createCharacterSql);
getCharacter = getLocalDatabase().prepareStatement("SELECT * FROM characters WHERE name == ?");
getLikeCharacterName = getLocalDatabase().prepareStatement("SELECT name FROM characters WHERE name ilike ?"); //NOTE: ilike is not SQL standard. It is an extension for postgres only.
nameGenerator.loadAllRules();
loadProfTemplates();
loadCommitHistory();
if (!nameFilter.load())
System.err.println("Failed to load name filter!");
registerForIntent(ZoneInIntent.TYPE);
return super.initialize();
}
@Override
public boolean start() {
creationRestriction.setCreationsPerPeriod(getConfig(ConfigFile.PRIMARY).getInt("GALAXY-MAX-CHARACTERS", 2));
return super.start();
}
@Override
public void onIntentReceived(Intent i) {
if (i instanceof ZoneInIntent) {
ZoneInIntent zii = (ZoneInIntent) i;
zoneInPlayer(zii.getPlayer(), zii.getCreature(), zii.getGalaxy());
}
}
public void handlePacket(GalacticIntent intent, Player player, long networkId, Packet p) {
if (p instanceof SessionRequest)
sendServerInfo(intent.getGalaxy(), networkId);
if (p instanceof ClientIdMsg)
handleClientIdMsg(player, (ClientIdMsg) p);
if (p instanceof RandomNameRequest)
handleRandomNameRequest(player, (RandomNameRequest) p);
if (p instanceof ClientVerifyAndLockNameRequest)
handleApproveNameRequest(intent.getPlayerManager(), player, (ClientVerifyAndLockNameRequest) p);
if (p instanceof ClientCreateCharacter)
handleCharCreation(intent.getObjectManager(), player, (ClientCreateCharacter) p);
if (p instanceof GalaxyLoopTimesRequest)
handleGalaxyLoopTimesRequest(player, (GalaxyLoopTimesRequest) p);
if (p instanceof CmdSceneReady)
handleCmdSceneReady(player, (CmdSceneReady) p);
if (p instanceof SetWaypointColor)
handleSetWaypointColor(player, (SetWaypointColor) p);
if(p instanceof ShowBackpack)
handleShowBackpack(player, (ShowBackpack) p);
if(p instanceof ShowHelmet)
handleShowHelmet(player, (ShowHelmet) p);
}
private void zoneInPlayer(Player player, CreatureObject creature, String galaxy) {
PlayerObject playerObj = creature.getPlayerObject();
player.setPlayerState(PlayerState.ZONING_IN);
player.setCreatureObject(creature);
creature.setOwner(player);
sendZonePackets(player, creature);
initPlayerBeforeZoneIn(player, creature, playerObj);
creature.createObject(player);
System.out.printf("[%s] %s is zoning in%n", player.getUsername(), player.getCharacterName());
Log.i("ObjectManager", "Zoning in %s with character %s", player.getUsername(), player.getCharacterName());
sendCommitHistory(player);
new PlayerEventIntent(player, galaxy, PlayerEvent.PE_ZONE_IN).broadcast();
}
private void loadCommitHistory() {
File repoDir = new File("./" + Constants.DOT_GIT); // Ziggy: Get the git directory
Git git = null;
Repository repo = null;
int commitCount = 3;
int iterations = 0;
try {
git = Git.open(repoDir);
repo = git.getRepository();
try {
commitHistory = "The " + commitCount + " most recent commits in branch '" + repo.getBranch() + "':\n";
for(RevCommit commit : git.log().setMaxCount(commitCount).call()) {
commitHistory += commit.getName().substring(0, 7) + " " + commit.getShortMessage();
if(commitCount > iterations++)
commitHistory += "\n";
}
} catch (Throwable t) {
t.printStackTrace();
}
} catch (IOException e) {
// Ziggy: An exception is thrown if bash isn't installed
// It works fine anyways.
}
}
private void sendCommitHistory(Player player) {
player.sendPacket(new ChatSystemMessage(ChatSystemMessage.SystemChatType.CHAT, commitHistory));
}
private void sendZonePackets(Player player, CreatureObject creature) {
long objId = creature.getObjectId();
Race race = creature.getRace();
Location l = creature.getLocation();
long time = (long)(ProjectSWG.getCoreTime()/1E3);
sendPacket(player, new HeartBeatMessage());
sendPacket(player, new ChatServerStatus(true));
sendPacket(player, new VoiceChatStatus());
sendPacket(player, new ParametersMessage());
sendPacket(player, new ChatOnConnectAvatar());
sendPacket(player, new CmdStartScene(false, objId, race, l, time));
sendPacket(player, new UpdatePvpStatusMessage(creature.getPvpType(), creature.getPvpFactionId(), creature.getObjectId()));
}
private void initPlayerBeforeZoneIn(Player player, CreatureObject creatureObj, PlayerObject playerObj) {
playerObj.setStartPlayTime((int) System.currentTimeMillis());
creatureObj.setMoodId(CreatureMood.NONE.getMood());
playerObj.clearFlagBitmask(PlayerFlags.LD); // Ziggy: Clear the LD flag in case it wasn't already.
}
private void handleShowBackpack(Player player, ShowBackpack p) {
player.getPlayerObject().setShowBackpack(p.showingBackpack());
}
private void handleShowHelmet(Player player, ShowHelmet p) {
player.getPlayerObject().setShowHelmet(p.showingHelmet());
}
private void handleSetWaypointColor(Player player, SetWaypointColor p) {
// TODO Should move this to a different service, maybe make a service for other packets similar to this (ie misc.)
PlayerObject ghost = (PlayerObject) player.getPlayerObject();
WaypointObject waypoint = ghost.getWaypoint(p.getObjId());
if (waypoint == null)
return;
switch(p.getColor()) {
case "blue": waypoint.setColor(WaypointColor.BLUE); break;
case "green": waypoint.setColor(WaypointColor.GREEN); break;
case "orange": waypoint.setColor(WaypointColor.ORANGE); break;
case "yellow": waypoint.setColor(WaypointColor.YELLOW); break;
case "purple": waypoint.setColor(WaypointColor.PURPLE); break;
case "white": waypoint.setColor(WaypointColor.WHITE); break;
default: System.err.println("Don't know color " + p.getColor());
}
ghost.updateWaypoint(waypoint);
}
private void sendServerInfo(Galaxy galaxy, long networkId) {
Config c = getConfig(ConfigFile.NETWORK);
String name = c.getString("ZONE-SERVER-NAME", galaxy.getName());
int id = c.getInt("ZONE-SERVER-ID", galaxy.getId());
sendPacket(networkId, new ServerString(name + ":" + id));
sendPacket(networkId, new ServerId(id));
}
private void handleCmdSceneReady(Player player, CmdSceneReady p) {
player.setPlayerState(PlayerState.ZONED_IN);
player.sendPacket(p);
System.out.println("[" + player.getUsername() +"] " + player.getCharacterName() + " zoned in");
Log.i("ZoneService", "%s with character %s zoned in from %s:%d", player.getUsername(), player.getCharacterName(), p.getAddress(), p.getPort());
}
private void handleClientIdMsg(Player player, ClientIdMsg clientId) {
System.out.println("[" + player.getUsername() + "] Connected to the zone server. IP: " + clientId.getAddress() + ":" + clientId.getPort());
Log.i("ZoneService", "%s connected to the zone server from %s:%d", player.getUsername(), clientId.getAddress(), clientId.getPort());
sendPacket(player.getNetworkId(), new HeartBeatMessage());
sendPacket(player.getNetworkId(), new AccountFeatureBits());
sendPacket(player.getNetworkId(), new ClientPermissionsMessage());
}
private void handleRandomNameRequest(Player player, RandomNameRequest request) {
RandomNameResponse response = new RandomNameResponse(request.getRace(), "");
String race = Race.getRaceByFile(request.getRace()).getSpecies();
response.setRandomName(nameGenerator.generateRandomName(race));
sendPacket(player.getNetworkId(), response);
}
private void handleApproveNameRequest(PlayerManager playerMgr, Player player, ClientVerifyAndLockNameRequest request) {
String name = request.getName();
ErrorMessage err = getNameValidity(name, player.getAccessLevel() != AccessLevel.PLAYER);
if (err == ErrorMessage.NAME_APPROVED_MODIFIED)
name = nameFilter.cleanName(name);
if (err == ErrorMessage.NAME_APPROVED || err == ErrorMessage.NAME_APPROVED_MODIFIED) {
if (!lockName(name, player)) {
err = ErrorMessage.NAME_DECLINED_IN_USE;
}
}
sendPacket(player.getNetworkId(), new ClientVerifyAndLockNameResponse(name, err));
}
private void handleCharCreation(ObjectManager objManager, Player player, ClientCreateCharacter create) {
ErrorMessage err = getNameValidity(create.getName(), player.getAccessLevel() != AccessLevel.PLAYER);
if (!creationRestriction.isAbleToCreate(player))
err = ErrorMessage.NAME_DECLINED_TOO_FAST;
if (err == ErrorMessage.NAME_APPROVED) {
long characterId = createCharacter(objManager, player, create);
if (createCharacterInDb(characterId, create.getName(), player)) {
creationRestriction.createdCharacter(player);
System.out.println("[" + player.getUsername() + "] Create Character: " + create.getName() + ". IP: " + create.getAddress() + ":" + create.getPort());
Log.i("ZoneService", "%s created character %s from %s:%d", player.getUsername(), create.getName(), create.getAddress(), create.getPort());
sendPacket(player, new CreateCharacterSuccess(characterId));
new PlayerEventIntent(player, PlayerEvent.PE_CREATE_CHARACTER).broadcast();
return;
}
Log.e("ZoneService", "Failed to create character %s for user %s with server error from %s:%d", create.getName(), player.getUsername(), create.getAddress(), create.getPort());
objManager.deleteObject(characterId);
}
sendCharCreationFailure(player, create, err);
}
private void sendCharCreationFailure(Player player, ClientCreateCharacter create, ErrorMessage err) {
NameFailureReason reason = NameFailureReason.NAME_SYNTAX;
switch (err) {
case NAME_APPROVED:
err = ErrorMessage.NAME_DECLINED_INTERNAL_ERROR;
reason = NameFailureReason.NAME_RETRY;
break;
case NAME_DECLINED_FICTIONALLY_INAPPROPRIATE:
reason = NameFailureReason.NAME_FICTIONALLY_INAPPRORIATE;
break;
case NAME_DECLINED_IN_USE: reason = NameFailureReason.NAME_IN_USE; break;
case NAME_DECLINED_EMPTY: reason = NameFailureReason.NAME_DECLINED_EMPTY; break;
case NAME_DECLINED_RESERVED: reason = NameFailureReason.NAME_DEV_RESERVED; break;
case NAME_DECLINED_TOO_FAST: reason = NameFailureReason.NAME_TOO_FAST; break;
default:
break;
}
System.err.println("ZoneService: Unable to create character [Name: " + create.getName() + " User: " + player.getUsername() + "] and put into database! Reason: " + err);
Log.e("ZoneService", "Failed to create character %s for user %s with error %s and reason %s from %s:%d", create.getName(), player.getUsername(), err, reason, create.getAddress(), create.getPort());
sendPacket(player, new CreateCharacterFailure(reason));
}
private boolean createCharacterInDb(long characterId, String name, Player player) {
if (characterExistsForName(name))
return false;
synchronized (createCharacter) {
try {
createCharacter.setLong(1, characterId);
createCharacter.setString(2, name);
createCharacter.setString(3, player.getCreatureObject().getRace().getFilename());
createCharacter.setInt(4, player.getUserId());
createCharacter.setInt(5, player.getGalaxyId());
return createCharacter.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
private ErrorMessage getNameValidity(String name, boolean admin) {
String modified = nameFilter.cleanName(name);
if (nameFilter.isEmpty(modified)) // Empty name
return ErrorMessage.NAME_DECLINED_EMPTY;
if (nameFilter.containsBadCharacters(modified)) // Has non-alphabetic characters
return ErrorMessage.NAME_DECLINED_SYNTAX;
if (nameFilter.isProfanity(modified)) // Contains profanity
return ErrorMessage.NAME_DECLINED_PROFANE;
if (nameFilter.isFictionallyInappropriate(modified))
return ErrorMessage.NAME_DECLINED_SYNTAX;
if (nameFilter.isReserved(modified) && !admin)
return ErrorMessage.NAME_DECLINED_RESERVED;
if (characterExistsForName(modified)) // User already exists.
return ErrorMessage.NAME_DECLINED_IN_USE;
if (nameFilter.isFictionallyReserved(modified))
return ErrorMessage.NAME_DECLINED_FICTIONALLY_RESERVED;
if (!modified.equals(name)) // If we needed to remove double spaces, trim the ends, etc
return ErrorMessage.NAME_APPROVED_MODIFIED;
return ErrorMessage.NAME_APPROVED;
}
private boolean characterExistsForName(String name) {
synchronized (getCharacter) {
ResultSet set = null;
try {
String nameSplitStr[] = name.split(" ");
String charExistsPrepStmtStr = nameSplitStr[0] + "%"; //Only the first name should be unique.
getLikeCharacterName.setString(1, charExistsPrepStmtStr);
set = getLikeCharacterName.executeQuery();
while (set.next()){
String dbName = set.getString("name");
if(nameSplitStr[0].equalsIgnoreCase(dbName.split(" ")[0])){
return true;
}
}
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
try {
if (set != null)
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private long createCharacter(ObjectManager objManager, Player player, ClientCreateCharacter create) {
Location start = getStartLocation(create.getStart());
Race race = Race.getRaceByFile(create.getRace());
CreatureObject creatureObj = createCreature(objManager, race.getFilename(), start);
PlayerObject playerObj = createPlayer(objManager, "object/player/shared_player.iff");
setCreatureObjectValues(objManager, creatureObj, create);
setPlayerObjectValues(playerObj, create);
createHair(objManager, creatureObj, create.getHair(), create.getHairCustomization());
createStarterClothing(objManager, creatureObj, create.getRace(), create.getClothes());
creatureObj.setVolume(0x000F4240);
creatureObj.setOwner(player);
creatureObj.addObject(playerObj); // ghost slot
playerObj.setAdminTag(player.getAccessLevel());
playerObj.setOwner(player);
player.setCreatureObject(creatureObj);
return creatureObj.getObjectId();
}
private CreatureObject createCreature(ObjectManager objManager, String template, Location location) {
SWGObject obj = objManager.createObject(template, location);
if (obj instanceof CreatureObject)
return (CreatureObject) obj;
return null;
}
private PlayerObject createPlayer(ObjectManager objManager, String template) {
SWGObject obj = objManager.createObject(template);
if (obj instanceof PlayerObject)
return (PlayerObject) obj;
return null;
}
private TangibleObject createTangible(ObjectManager objManager, String template) {
SWGObject obj = objManager.createObject(template);
if (obj instanceof TangibleObject)
return (TangibleObject) obj;
return null;
}
private void createHair(ObjectManager objManager, CreatureObject creatureObj, String hair, byte [] customization) {
if (hair.isEmpty())
return;
TangibleObject hairObj = createTangible(objManager, ClientFactory.formatToSharedFile(hair));
hairObj.getContainerPermissions().addDefaultWorldPermissions();
hairObj.setAppearanceData(customization);
creatureObj.addObject(hairObj); // slot = hair
creatureObj.addEquipment(hairObj);
}
private void setCreatureObjectValues(ObjectManager objManager, CreatureObject creatureObj, ClientCreateCharacter create) {
TangibleObject inventory = createTangible(objManager, "object/tangible/inventory/shared_character_inventory.iff");
TangibleObject datapad = createTangible(objManager, "object/tangible/datapad/shared_character_datapad.iff");
TangibleObject apprncInventory = createTangible(objManager, "object/tangible/inventory/shared_appearance_inventory.iff");
creatureObj.setRace(Race.getRaceByFile(create.getRace()));
creatureObj.setAppearanceData(create.getCharCustomization());
creatureObj.setHeight(create.getHeight());
creatureObj.setName(create.getName());
creatureObj.setPvpType(20);
creatureObj.getSkills().add("species_" + creatureObj.getRace().getSpecies());
creatureObj.addObject(inventory); // slot = inventory
creatureObj.addObject(datapad); // slot = datapad
creatureObj.addObject(apprncInventory); // slot = appearance_inventory
creatureObj.addEquipment(inventory);
creatureObj.addEquipment(datapad);
creatureObj.addEquipment(apprncInventory);
creatureObj.getContainerPermissions().addDefaultWorldPermissions();
}
private void setPlayerObjectValues(PlayerObject playerObj, ClientCreateCharacter create) {
playerObj.setProfession(create.getProfession());
Calendar date = Calendar.getInstance();
playerObj.setBornDate(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
playerObj.getContainerPermissions().addDefaultWorldPermissions();
}
private void handleGalaxyLoopTimesRequest(Player player, GalaxyLoopTimesRequest req) {
sendPacket(player, new GalaxyLoopTimesResponse(ProjectSWG.getCoreTime()/1000));
}
private void createStarterClothing(ObjectManager objManager, CreatureObject player, String race, String profession) {
if (player.getSlottedObject("inventory") == null)
return;
for (String template : profTemplates.get(profession).getItems(ClientFactory.formatToSharedFile(race))) {
TangibleObject item = createTangible(objManager, template);
// Move the new item to the player's clothing slots and add to equipment list
item.moveToContainer(player, player);
player.addEquipment(item);
}
}
private void loadProfTemplates() {
profTemplates.put("crafting_artisan", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_crafting_artisan.iff"));
profTemplates.put("combat_brawler", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_combat_brawler.iff"));
profTemplates.put("social_entertainer", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_social_entertainer.iff"));
profTemplates.put("combat_marksman", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_combat_marksman.iff"));
profTemplates.put("science_medic", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_science_medic.iff"));
profTemplates.put("outdoors_scout", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_outdoors_scout.iff"));
profTemplates.put("jedi", (ProfTemplateData) ClientFactory.getInfoFromFile("creation/profession_defaults_jedi.iff"));
}
private boolean lockName(String name, Player player) {
String firstName = name.split(" ", 2)[0].toLowerCase(Locale.ENGLISH);
if (isLocked(firstName))
return false;
synchronized (lockedNames) {
unlockName(player);
lockedNames.put(firstName, player);
Log.i("ZoneService", "Locked name %s for user %s", firstName, player.getUsername());
}
return true;
}
private void unlockName(Player player) {
synchronized (lockedNames) {
String fName = null;
for (Entry <String, Player> e : lockedNames.entrySet()) {
Player locked = e.getValue();
if (locked != null && locked.equals(player)) {
fName = e.getKey();
break;
}
}
if (fName != null) {
if (lockedNames.remove(fName) != null)
Log.i("ZoneService", "Unlocked name %s for user %s", fName, player.getUsername());
}
}
}
private boolean isLocked(String firstName) {
Player player = null;
synchronized (lockedNames) {
player = lockedNames.get(firstName);
}
if (player == null)
return false;
PlayerState state = player.getPlayerState();
return state != PlayerState.DISCONNECTED && state != PlayerState.LOGGED_OUT;
}
private Location getStartLocation(String start) {
return TerrainZoneInsertion.getInsertionForTerrain(Terrain.TATOOINE);
// return TerrainZoneInsertion.getInsertionForArea(Terrain.CORELLIA, -5436, 24, -6211);
}
}
|
package org.ow2.proactive.resourcemanager.nodesource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.InitActive;
import org.objectweb.proactive.RunActive;
import org.objectweb.proactive.Service;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeFactory;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.objectweb.proactive.core.util.wrapper.IntWrapper;
import org.ow2.proactive.resourcemanager.common.event.RMEventType;
import org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent;
import org.ow2.proactive.resourcemanager.core.RMCore;
import org.ow2.proactive.resourcemanager.core.RMCoreInterface;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.exception.AddingNodesException;
import org.ow2.proactive.resourcemanager.exception.RMException;
import org.ow2.proactive.resourcemanager.nodesource.dataspace.DataSpaceNodeConfigurationAgent;
import org.ow2.proactive.resourcemanager.nodesource.infrastructure.InfrastructureManager;
import org.ow2.proactive.resourcemanager.nodesource.policy.NodeSourcePolicy;
import org.ow2.proactive.resourcemanager.rmnode.RMNode;
import org.ow2.proactive.resourcemanager.rmnode.RMNodeImpl;
import org.ow2.proactive.resourcemanager.utils.RMLoggers;
/**
* Abstract class designed to manage a NodeSource. A NodeSource active object is
* designed to manage acquisition, monitoring and removing of a set of
* {@link Node} objects in the Resource Manager. Each node source consists
* of two entities {@link InfrastructureManager} and {@link NodeSourcePolicy}. <BR>
*
* Each particular {@link InfrastructureManager} defines a specific infrastructure and ways
* to manipulate nodes. <BR>
*
* The node source policy {@link NodeSourcePolicy} defines a strategy of nodes acquisition.
* It can be static acquiring nodes once and forever or dynamic where nodes acquisition takes
* into account different external factors such as time, scheduling state, etc.
*
*/
public class NodeSource implements InitActive, RunActive {
private static Logger logger = ProActiveLogger.getLogger(RMLoggers.NODESOURCE);
private static final int NODE_LOOKUP_TIMEOUT = PAResourceManagerProperties.RM_NODELOOKUP_TIMEOUT
.getValueAsInt();
private int pingFrequency = PAResourceManagerProperties.RM_NODE_SOURCE_PING_FREQUENCY.getValueAsInt();
/** Default name */
public static final String GCM_LOCAL = "GCMLocalNodes";
public static final String DEFAULT = "Default";
/** unique name of the source */
private String name;
private InfrastructureManager infrastructureManager;
private NodeSourcePolicy nodeSourcePolicy;
private String description;
private RMCore rmcore;
private boolean toShutdown = false;
// all nodes except down
private HashMap<String, Node> nodes = new HashMap<String, Node>();
private HashMap<String, Node> downNodes = new HashMap<String, Node>();
private static transient ExecutorService networkOperationsThreadPool;
private NodeSource stub;
/**
* Creates a new instance of NodeSource.
* This constructor is used by Proactive as one of requirements for active objects.
*/
public NodeSource() {
}
/**
* Creates a new instance of NodeSource.
*
* @param name node source name
* @param im underlying infrastructure manager
* @param policy nodes acquisition policy
* @param rmcore resource manager core
*/
public NodeSource(String name, InfrastructureManager im, NodeSourcePolicy policy, RMCore rmcore) {
this.name = name;
infrastructureManager = im;
nodeSourcePolicy = policy;
this.rmcore = rmcore;
}
/**
* Initialization of node source. Creates and activates a pinger to monitor nodes.
*
* @param body active object body
*/
public void initActivity(Body body) {
stub = (NodeSource) PAActiveObject.getStubOnThis();
infrastructureManager.setNodeSource(this);
nodeSourcePolicy.setNodeSource((NodeSource) PAActiveObject.getStubOnThis());
try {
// executor service initialization
getExecutorService();
// description could be requested when the policy does not exist anymore
// so initializing it here
description = "Infrastructure:" + infrastructureManager + ", Policy: " + nodeSourcePolicy;
// these methods are called from the rm core
// mark them as immediate services in order to prevent the block of the core
PAActiveObject.setImmediateService("getName");
PAActiveObject.setImmediateService("executeInParallel");
PAActiveObject.setImmediateService("getDescription");
} catch (Exception e) {
e.printStackTrace();
}
}
public void runActivity(Body body) {
Service service = new Service(body);
long timeStamp = System.currentTimeMillis();
long delta = 0;
// recalculating nodes number only once per policy period
while (body.isActive()) {
service.blockingServeOldest(pingFrequency);
delta += System.currentTimeMillis() - timeStamp;
timeStamp = System.currentTimeMillis();
if (delta > pingFrequency) {
logger.info("[" + name + "] Pinging alive nodes");
for (Node node : getAliveNodes()) {
pingNode(node.getNodeInformation().getURL());
}
delta = 0;
}
}
}
/**
* Updates internal node source structures.
*/
private void internalAddNode(Node node) throws RMException {
String nodeUrl = node.getNodeInformation().getURL();
if (this.nodes.containsKey(nodeUrl)) {
throw new RMException("The node " + nodeUrl + " already added to the node source " + name);
}
logger.info("[" + name + "] new node available : " + node.getNodeInformation().getURL());
infrastructureManager.registerAcquiredNode(node);
nodes.put(nodeUrl, node);
}
/**
* Acquires the existing node with specific url. The node have to be up and running.
*
* @param nodeUrl the url of the node
*/
public BooleanWrapper acquireNode(String nodeUrl) {
if (toShutdown) {
throw new AddingNodesException("[" + name +
"] addNode request discarded because node source is shutting down");
}
// lookup for a new Node
Node nodeToAdd = null;
try {
nodeToAdd = lookupNode(nodeUrl, NODE_LOOKUP_TIMEOUT);
} catch (Exception e) {
throw new AddingNodesException(e);
}
// cannot lookup node
if (nodeToAdd == null) {
throw new AddingNodesException("Cannot lookup node " + nodeUrl);
}
// the node with specified url was successfully looked up
// now checking if this node has been registered before in the node source
if (downNodes.containsKey(nodeUrl)) {
// it was registered but detected as down node,
// so basically the node was restarted.
// adding a new node and removing old one from the down list
logger.debug("Removing existing node from down nodes list");
BooleanWrapper result = rmcore.internalRemoveNodeFromCore(nodeUrl);
if (result.booleanValue()) {
if (logger.isDebugEnabled())
logger.debug("[" + name + "] successfully removed node " + nodeUrl + " from the core");
// just removing it from down nodes list
removeNode(nodeUrl);
}
} else if (nodes.containsKey(nodeUrl)) {
// adding a node which exists in node source
Node existingNode = nodes.get(nodeUrl);
if (nodeToAdd.equals(existingNode)) {
// adding the same node twice
// don't do anything
if (logger.isDebugEnabled())
logger.debug("An attempt to add the same node twice " + nodeUrl + " - ignoring");
return new BooleanWrapper(false);
} else {
// adding another node with the same url
// replacing the old node by the new one
logger
.debug("Removing existing node from the RM without request propagation to the infrastructure manager");
BooleanWrapper result = rmcore.internalRemoveNodeFromCore(nodeUrl);
if (result.booleanValue()) {
if (logger.isDebugEnabled())
logger
.debug("[" + name + "] successfully removed node " + nodeUrl +
" from the core");
// removing it from the nodes list but don't propagate
// the request the the infrastructure because the restarted node will be killed
nodes.remove(nodeUrl);
}
}
}
// if any exception occurs in internalAddNode(node) do not add the node to the core
try {
internalAddNode(nodeToAdd);
} catch (RMException e) {
throw new AddingNodesException(e);
}
RMNode rmnode = new RMNodeImpl(nodeToAdd, "noVn", (NodeSource) PAActiveObject.getStubOnThis());
rmcore.internalAddNodeToCore(rmnode);
return new BooleanWrapper(true);
}
/**
* Configure node for dataSpaces
*
* @param node the node to be configured
*/
private void configureForDataSpace(Node node) {
try {
DataSpaceNodeConfigurationAgent conf = (DataSpaceNodeConfigurationAgent) PAActiveObject
.newActive(DataSpaceNodeConfigurationAgent.class.getName(), null, node);
conf.configureNode();
} catch (Throwable t) {
logger.warn("Cannot configure dataSpaces", t);
}
}
/**
* Close dataSpaces node configuration
*
* @param node the node to be unconfigured
*/
private void closeDataSpaceConfiguration(Node node) {
try {
DataSpaceNodeConfigurationAgent conf = (DataSpaceNodeConfigurationAgent) PAActiveObject
.newActive(DataSpaceNodeConfigurationAgent.class.getName(), null, node);
conf.closeNodeConfiguration();
} catch (Throwable t) {
logger.warn("Cannot close dataSpaces configuration", t);
}
}
/**
* Looks up the node
*/
private class NodeLocator implements Callable<Node> {
private String nodeUrl;
public NodeLocator(String url) {
nodeUrl = url;
}
public Node call() throws Exception {
Node node = NodeFactory.getNode(nodeUrl);
configureForDataSpace(node);
return node;
}
}
/**
* Lookups a node with specified timeout.
*
* @param nodeUrl a url of the node
* @param timeout to wait in ms
* @return node if it was successfully obtained, null otherwise
* @throws Exception if node was not looked up
*/
private Node lookupNode(String nodeUrl, long timeout) throws Exception {
if (logger.isDebugEnabled())
logger.debug("Looking up for the node " + nodeUrl + " with " + timeout + " ms timeout");
Future<Node> futureNode = getExecutorService().submit(new NodeLocator(nodeUrl));
try {
return futureNode.get(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
return null;
}
}
/**
* Requests one node to be acquired from the underlying infrastructure.
*/
public void acquireNode() {
if (toShutdown) {
logger.warn("[" + name + "] acquireNode request discarded because node source is shutting down");
return;
}
infrastructureManager.acquireNode();
}
/**
* Requests all nodes to be acquired from the infrastructure.
*/
public void acquireAllNodes() {
if (toShutdown) {
logger.warn("[" + name +
"] acquireAllNodes request discarded because node source is shutting down");
return;
}
infrastructureManager.acquireAllNodes();
}
/**
* Removes the node from the node source.
*
* @param nodeUrl the url of the node to be released
*/
public BooleanWrapper removeNode(String nodeUrl) {
//verifying if node is already in the list,
//node could have fallen between remove request and the confirm
if (this.nodes.containsKey(nodeUrl)) {
logger.info("[" + name + "] removing node : " + nodeUrl);
Node node = nodes.remove(nodeUrl);
try {
// TODO this method call breaks parallel node removal - fix it
closeDataSpaceConfiguration(node);
infrastructureManager.removeNode(node);
} catch (RMException e) {
logger.error(e.getCause().getMessage());
}
} else {
Node downNode = downNodes.remove(nodeUrl);
if (downNode != null) {
logger.info("[" + name + "] removing down node : " + nodeUrl);
} else {
logger.error("[" + name + "] removing node : " + nodeUrl +
" which not belongs to this node source");
return new BooleanWrapper(false);
}
}
if (toShutdown && nodes.size() == 0) {
// shutdown all pending nodes
shutdownNodeSourceServices();
}
return new BooleanWrapper(true);
}
/**
* Shutdowns the node source and releases all its nodes.
*/
public void shutdown() {
logger.info("[" + name + "] removal request");
toShutdown = true;
if (nodes.size() == 0) {
shutdownNodeSourceServices();
}
}
/**
* Gets the ping frequency.
* @return ping frequency
*/
public IntWrapper getPingFrequency() {
return new IntWrapper(pingFrequency);
}
/**
* Sets the ping frequency (in ms)
* @param frequency new value of monitoring period
*/
public void setPingFrequency(int frequency) {
pingFrequency = frequency;
}
/**
* Creates a node source string representation
* @return string representation of the node source
*/
public String getDescription() {
return description;
}
/**
* Gets name of the node source
* @return name of the node source
*/
public String getName() {
return name;
}
/**
* Activates a node source policy.
*/
public void activate() {
logger.info("[" + name + "] Activating the policy " + nodeSourcePolicy);
nodeSourcePolicy.activate();
}
/**
* Initiates node source services shutdown, such as pinger, policy, thread pool.
*/
protected void shutdownNodeSourceServices() {
logger.info("[" + name + "] Shutdown finalization");
nodeSourcePolicy.shutdown();
infrastructureManager.shutDown();
}
/**
* Terminates a node source active object when shutdown confirmation is received from the pinger and the policy.
*/
public void finishNodeSourceShutdown() {
PAFuture.waitFor(rmcore.nodeSourceUnregister(name, new RMNodeSourceEvent(this,
RMEventType.NODESOURCE_REMOVED)));
// got confirmation from pinger and policy
PAActiveObject.terminateActiveObject(false);
}
/**
* Retrieves a list of alive nodes
* @return a list of alive nodes
*/
public LinkedList<Node> getAliveNodes() {
LinkedList<Node> nodes = new LinkedList<Node>();
nodes.addAll(this.nodes.values());
return nodes;
}
/**
* Retrieves a list of down nodes
* @return a list of down nodes
*/
public LinkedList<Node> getDownNodes() {
LinkedList<Node> downNodes = new LinkedList<Node>();
downNodes.addAll(this.downNodes.values());
return downNodes;
}
/**
* Gets the nodes size excluding down nodes.
* @return the node size
*/
public int getNodesCount() {
return this.nodes.values().size();
}
/**
* Marks node as down. Remove it from node source node set. It remains in rmcore nodes list until
* user decides to remove them or node source is shutdown.
* @see org.ow2.proactive.resourcemanager.nodesource.frontend.NodeSource#detectedPingedDownNode(java.lang.String)
*/
public void detectedPingedDownNode(String nodeUrl) {
if (toShutdown) {
logger.warn("[" + name +
"] detectedPingedDownNode request discarded because node source is shutting down");
return;
}
logger.info("[" + name + "] Detected down node " + nodeUrl);
Node downNode = nodes.remove(nodeUrl);
if (downNode != null) {
downNodes.put(nodeUrl, downNode);
}
rmcore.setDownNode(nodeUrl);
}
/**
* Gets resource manager core. Used by policies.
* @return {@link RMCoreInterface}
*/
public RMCoreInterface getRMCore() {
return rmcore;
}
/**
* Executed command in parallel using thread pool
* @param command to execute
*/
public void executeInParallel(Runnable command) {
getExecutorService().execute(command);
}
/**
* Instantiates the threadpool controller if it is null.
*/
private synchronized static ExecutorService getExecutorService() {
if (networkOperationsThreadPool == null) {
networkOperationsThreadPool = Executors
.newFixedThreadPool(PAResourceManagerProperties.RM_NODESOURCE_MAX_THREAD_NUMBER
.getValueAsInt());
}
return networkOperationsThreadPool;
}
/**
* Pings the node with specified url.
* If the node is dead sends the request to the node source.
*/
public void pingNode(final String url) {
executeInParallel(new Runnable() {
public void run() {
try {
Node node = NodeFactory.getNode(url);
node.getNumberOfActiveObjects();
if (logger.isDebugEnabled())
logger.debug("Node " + url + " is alive");
} catch (Throwable t) {
stub.detectedPingedDownNode(url);
}
}
});
}
}
|
package com.boissinot.jenkins.csvexporter.service.extractor.jenkins;
import com.boissinot.jenkins.csvexporter.domain.OutputCSVJobObj;
import com.boissinot.jenkins.csvexporter.domain.jenkins.job.ConfigJob;
import com.boissinot.jenkins.csvexporter.domain.maven.pom.Developer;
import com.boissinot.jenkins.csvexporter.maven.extractor.POMRemoteObj;
import com.boissinot.jenkins.csvexporter.service.extractor.jenkins.command.BuildersElementRetriever;
import com.boissinot.jenkins.csvexporter.service.extractor.jenkins.pom.DeveloperElementRetriever;
import com.boissinot.jenkins.csvexporter.service.extractor.jenkins.scm.SCMElementBuilder;
import com.boissinot.jenkins.csvexporter.service.extractor.maven.pom.POMDeveloperSectionExtractor;
import com.boissinot.jenkins.csvexporter.service.extractor.maven.pom.POMFileInfoExtractor;
import com.boissinot.jenkins.csvexporter.service.http.HttpResourceContentFetcher;
import org.springframework.integration.Message;
import org.springframework.integration.MessageHeaders;
import org.springframework.integration.annotation.ServiceActivator;
import org.w3c.dom.Node;
import java.io.*;
import java.util.List;
import java.util.Map;
import static com.boissinot.jenkins.csvexporter.domain.JobMessageHeaders.*;
/**
* @author Gregory Boissinot
*/
public class OutputObjBuilder {
private HttpResourceContentFetcher httpResourceContentFetcher;
private POMFileInfoExtractor pomFileInfoExtractor;
public void setHttpResourceContentFetcher(HttpResourceContentFetcher httpResourceContentFetcher) {
this.httpResourceContentFetcher = httpResourceContentFetcher;
}
public void setPomFileInfoExtractor(POMFileInfoExtractor pomFileInfoExtractor) {
this.pomFileInfoExtractor = pomFileInfoExtractor;
}
@ServiceActivator
public OutputCSVJobObj buildObj(Message message) {
OutputCSVJobObj.Builder builder = new OutputCSVJobObj.Builder();
MessageHeaders headers = message.getHeaders();
//jobName
String jobName = headers.get(HEADER_JOB_NAME, String.class);
builder.name(jobName);
String functionalJobType = headers.get(HEADER_FUNCTIONAL_JOB_TYPE, String.class);
builder.functionalJobType(functionalJobType);
//jenkinsJobType
String jenkinsJobType = headers.get(HEADER_JENKINS_JOB_TYPE, String.class);
builder.jenkinsType(jenkinsJobType);
//functionalJobLanguage
String functionalJobLanguage = headers.get(HEADER_FUNCTIONAL_JOB_LANGUAGE, String.class);
builder.functionalJobLanguage(functionalJobLanguage);
//spec
final String spec = (String) headers.get("spec");
builder.trigger(spec);
//description
final String description = (String) headers.get("description");
builder.desc(description);
//disabled
final Boolean disabled = (Boolean) headers.get("disabled");
builder.disabled(disabled);
//scm
final Node scmNode = (Node) headers.get("scm");
SCMElementBuilder scmElementBuilder = new SCMElementBuilder();
scmElementBuilder.build(scmNode);
builder.svnURL(scmElementBuilder.getSvnURL());
builder.gitURL(scmElementBuilder.getGitURL());
builder.cvsRoot(scmElementBuilder.getCvsRoot());
builder.cvsModule(scmElementBuilder.getCvsModule());
builder.cvsBranche(scmElementBuilder.getCvsBranche());
//builders
final Node buildersNode = (Node) headers.get("builders");
BuildersElementRetriever buildersElementRetriever = new BuildersElementRetriever();
final String buildSteps = buildersElementRetriever.buildCommandSection(buildersNode);
builder.buildSteps(buildSteps);
//developers
ConfigJob configJob = new ConfigJob();
configJob.setCvsBranche(scmElementBuilder.getCvsBranche());
configJob.setCvsModule(scmElementBuilder.getCvsModule());
configJob.setGitURL(scmElementBuilder.getGitURL());
configJob.setSvnURL(scmElementBuilder.getSvnURL());
configJob.setJobName(jobName);
POMRemoteObj pomObj = pomFileInfoExtractor.getPomUrl(configJob, (Map) message.getHeaders().get("MODULE_MAP"));
if (pomObj != null) {
String pomContent = httpResourceContentFetcher.getContent(pomObj.getHttpURL());
POMDeveloperSectionExtractor sectionExtractor = new POMDeveloperSectionExtractor();
List<Developer> developers = sectionExtractor.extract(pomContent);
DeveloperElementRetriever retriever = new DeveloperElementRetriever();
builder.developers(retriever.buildDeveloperSection(developers));
}
final OutputCSVJobObj outputCSVJobObj = builder.build();
File jobEmailsFile = new File("jobEmails.txt");
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
PrintWriter printWriter = null;
try {
fileWriter = new FileWriter(jobEmailsFile, true);
bufferedWriter = new BufferedWriter(fileWriter);
printWriter = new PrintWriter(bufferedWriter);
printWriter
.append(outputCSVJobObj.getName())
.append(";")
.append(outputCSVJobObj.getDevelopers())
.append("\n");
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
if (printWriter != null)
printWriter.close();
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return outputCSVJobObj;
}
}
|
package services.player;
import intents.GalacticIntent;
import intents.PlayerEventIntent;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import main.ProjectSWG;
import network.packets.Packet;
import network.packets.soe.SessionRequest;
import network.packets.swg.login.AccountFeatureBits;
import network.packets.swg.login.ClientIdMsg;
import network.packets.swg.login.ClientPermissionsMessage;
import network.packets.swg.login.ServerId;
import network.packets.swg.login.ServerString;
import network.packets.swg.login.creation.ClientVerifyAndLockNameRequest;
import network.packets.swg.login.creation.ClientVerifyAndLockNameResponse;
import network.packets.swg.login.creation.ClientCreateCharacter;
import network.packets.swg.login.creation.ClientVerifyAndLockNameResponse.ErrorMessage;
import network.packets.swg.login.creation.CreateCharacterFailure;
import network.packets.swg.login.creation.CreateCharacterFailure.NameFailureReason;
import network.packets.swg.login.creation.CreateCharacterSuccess;
import network.packets.swg.login.creation.RandomNameRequest;
import network.packets.swg.login.creation.RandomNameResponse;
import network.packets.swg.zone.GalaxyLoopTimesRequest;
import network.packets.swg.zone.GalaxyLoopTimesResponse;
import network.packets.swg.zone.HeartBeatMessage;
import resources.Galaxy;
import resources.Location;
import resources.Race;
import resources.Terrain;
import resources.client_info.ClientFactory;
import resources.client_info.visitors.ProfTemplateData;
import resources.config.ConfigFile;
import resources.control.Service;
import resources.objects.creature.CreatureObject;
import resources.objects.player.PlayerObject;
import resources.objects.tangible.TangibleObject;
import resources.player.Player;
import resources.player.PlayerEvent;
import resources.services.Config;
import services.objects.ObjectManager;
import utilities.namegen.SWGNameGenerator;
public class ZoneService extends Service {
private SWGNameGenerator nameGenerator;
private Map <String, ProfTemplateData> profTemplates;
private ClientFactory clientFac;
private PreparedStatement createCharacter;
private PreparedStatement getCharacter;
public ZoneService() {
nameGenerator = new SWGNameGenerator();
clientFac = new ClientFactory();
}
@Override
public boolean initialize() {
String createCharacterSql = "INSERT INTO characters (id, name, race, userId, galaxyId) VALUES (?, ?, ?, ?, ?)";
createCharacter = getLocalDatabase().prepareStatement(createCharacterSql);
getCharacter = getLocalDatabase().prepareStatement("SELECT * FROM characters WHERE name = ?");
nameGenerator.loadAllRules();
loadProfTemplates();
return super.initialize();
}
public void handlePacket(GalacticIntent intent, Player player, long networkId, Packet p) {
if (p instanceof SessionRequest)
sendServerInfo(intent.getGalaxy(), networkId);
if (p instanceof ClientIdMsg)
handleClientIdMsg(player, (ClientIdMsg) p);
if (p instanceof RandomNameRequest)
handleRandomNameRequest(player, (RandomNameRequest) p);
if (p instanceof ClientVerifyAndLockNameRequest)
handleApproveNameRequest(intent.getPlayerManager(), player, (ClientVerifyAndLockNameRequest) p);
if (p instanceof ClientCreateCharacter)
handleCharCreation(intent.getObjectManager(), player, (ClientCreateCharacter) p);
if (p instanceof GalaxyLoopTimesRequest)
handleGalaxyLoopTimesRequest(player, (GalaxyLoopTimesRequest) p);
}
private void sendServerInfo(Galaxy galaxy, long networkId) {
Config c = getConfig(ConfigFile.PRIMARY);
String name = c.getString("ZONE-SERVER-NAME", galaxy.getName());
int id = c.getInt("ZONE-SERVER-ID", galaxy.getId());
sendPacket(networkId, new ServerString(name + ":" + id));
sendPacket(networkId, new ServerId(id));
}
private void handleClientIdMsg(Player player, ClientIdMsg clientId) {
System.out.println(player.getUsername() + " has connected to the zone server.");
sendPacket(player.getNetworkId(), new HeartBeatMessage());
sendPacket(player.getNetworkId(), new AccountFeatureBits());
sendPacket(player.getNetworkId(), new ClientPermissionsMessage());
}
private void handleRandomNameRequest(Player player, RandomNameRequest request) {
RandomNameResponse response = new RandomNameResponse(request.getRace(), "");
String race = Race.getRaceByFile(request.getRace()).getSpecies();
response.setRandomName(nameGenerator.generateRandomName(race));
sendPacket(player.getNetworkId(), response);
}
private void handleApproveNameRequest(PlayerManager playerMgr, Player player, ClientVerifyAndLockNameRequest request) {
// TODO: Lore reserved name checks
if (!characterExistsForName(request.getName()))
sendPacket(player.getNetworkId(), new ClientVerifyAndLockNameResponse(request.getName(), ErrorMessage.NAME_APPROVED));
else
sendPacket(player.getNetworkId(), new ClientVerifyAndLockNameResponse(request.getName(), ErrorMessage.NAME_DECLINED_IN_USE));
}
private void handleCharCreation(ObjectManager objManager, Player player, ClientCreateCharacter create) {
System.out.println("Create Character: " + create.getName());
long characterId = createCharacter(objManager, player, create);
if (createCharacterInDb(characterId, create.getName(), player)) {
sendPacket(player, new CreateCharacterSuccess(characterId));
new PlayerEventIntent(player, PlayerEvent.PE_CREATE_CHARACTER).broadcast();
} else {
System.err.println("ZoneService: Unable to create character and put into database!");
sendPacket(player, new CreateCharacterFailure(NameFailureReason.NAME_RETRY));
}
}
private boolean createCharacterInDb(long characterId, String name, Player player) {
if (characterExistsForName(name))
return false;
synchronized (createCharacter) {
try {
createCharacter.setLong(1, characterId);
createCharacter.setString(2, name);
createCharacter.setString(3, ((CreatureObject)player.getCreatureObject()).getRace().getFilename());
createCharacter.setInt(4, player.getUserId());
createCharacter.setInt(5, player.getGalaxyId());
return createCharacter.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
private boolean characterExistsForName(String name) {
synchronized (getCharacter) {
try {
getCharacter.setString(1, name);
return !getCharacter.execute();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
private long createCharacter(ObjectManager objManager, Player player, ClientCreateCharacter create) {
Location start = getStartLocation(create.getStart());
Race race = Race.getRaceByFile(create.getRace());
CreatureObject creatureObj = (CreatureObject) objManager.createObject(race.getFilename());
PlayerObject playerObj = (PlayerObject) objManager.createObject("object/player/shared_player.iff");
setCreatureObjectValues(objManager, creatureObj, create);
setPlayerObjectValues(playerObj, create);
createHair(objManager, creatureObj, create.getHair(), create.getHairCustomization());
createStarterClothing(objManager, creatureObj, create.getRace(), create.getClothes());
creatureObj.setVolume(0x000F4240);
creatureObj.setLocation(start);
creatureObj.setOwner(player);
creatureObj.setSlot("ghost", playerObj);
playerObj.setTag(player.getAccessLevel());
player.setCreatureObject(creatureObj);
return creatureObj.getObjectId();
}
private void createHair(ObjectManager objManager, CreatureObject creatureObj, String hair, byte [] customization) {
if (hair.isEmpty())
return;
TangibleObject hairObj = (TangibleObject) objManager.createObject(ClientFactory.formatToSharedFile(hair));
hairObj.setAppearanceData(customization);
creatureObj.setSlot("hair", hairObj);
creatureObj.addEquipment(hairObj);
}
private void setCreatureObjectValues(ObjectManager objManager, CreatureObject creatureObj, ClientCreateCharacter create) {
TangibleObject inventory = (TangibleObject) objManager.createObject("object/tangible/inventory/shared_character_inventory.iff");
TangibleObject datapad = (TangibleObject) objManager.createObject("object/tangible/datapad/shared_character_datapad.iff");
creatureObj.setRace(Race.getRaceByFile(create.getRace()));
creatureObj.setAppearanceData(create.getCharCustomization());
creatureObj.setHeight(create.getHeight());
creatureObj.setName(create.getName());
creatureObj.setPvpType(20);
creatureObj.getSkills().add("species_" + creatureObj.getRace().getSpecies());
creatureObj.setSlot("inventory", inventory);
creatureObj.setSlot("datapad", datapad);
creatureObj.addEquipment(inventory);
creatureObj.addEquipment(datapad);
}
private void setPlayerObjectValues(PlayerObject playerObj, ClientCreateCharacter create) {
playerObj.setProfession(create.getProfession());
Calendar date = Calendar.getInstance();
playerObj.setBornDate(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
}
private void handleGalaxyLoopTimesRequest(Player player, GalaxyLoopTimesRequest req) {
sendPacket(player, new GalaxyLoopTimesResponse(ProjectSWG.getCoreTime()/1000));
}
private void createStarterClothing(ObjectManager objManager, CreatureObject player, String race, String profession) {
if (player.getSlottedObject("inventory") == null)
return;
for (String template : profTemplates.get(profession).getItems(ClientFactory.formatToSharedFile(race))) {
TangibleObject clothing = (TangibleObject) objManager.createObject(template);
player.addChild(clothing);
}
}
private void loadProfTemplates() {
profTemplates = new ConcurrentHashMap<String, ProfTemplateData>();
profTemplates.put("crafting_artisan", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_combat_brawler.iff"));
profTemplates.put("combat_brawler", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_combat_brawler.iff"));
profTemplates.put("social_entertainer", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_social_entertainer.iff"));
profTemplates.put("combat_marksman", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_combat_marksman.iff"));
profTemplates.put("science_medic", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_science_medic.iff"));
profTemplates.put("outdoors_scout", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_outdoors_scout.iff"));
profTemplates.put("jedi", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_jedi.iff"));
}
private Location getStartLocation(String start) {
Location location = new Location();
location.setTerrain(Terrain.TATOOINE);
location.setX(3525 + (Math.random()-.5) * 5);
location.setY(4);
location.setZ(-4807 + (Math.random()-.5) * 5);
location.setOrientationX(0);
location.setOrientationY(0);
location.setOrientationZ(0);
location.setOrientationW(1);
return location;
}
}
|
package org.ow2.proactive.scheduler.ext.masterworker;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.objectweb.proactive.extensions.masterworker.TaskException;
import org.objectweb.proactive.extensions.masterworker.core.AOWorker;
import org.objectweb.proactive.extensions.masterworker.core.ResultInternImpl;
import org.objectweb.proactive.extensions.masterworker.interfaces.internal.ResultIntern;
import org.objectweb.proactive.extensions.masterworker.interfaces.internal.TaskIntern;
import org.objectweb.proactive.extensions.masterworker.interfaces.internal.WorkerMaster;
import org.ow2.proactive.scheduler.common.exception.SchedulerException;
import org.ow2.proactive.scheduler.common.exception.UserException;
import org.ow2.proactive.scheduler.common.job.*;
import org.ow2.proactive.scheduler.common.scheduler.SchedulerAuthenticationInterface;
import org.ow2.proactive.scheduler.common.scheduler.SchedulerConnection;
import org.ow2.proactive.scheduler.common.scheduler.SchedulerEvent;
import org.ow2.proactive.scheduler.common.scheduler.SchedulerEventListener;
import org.ow2.proactive.scheduler.common.scheduler.UserSchedulerInterface;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.TaskEvent;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable;
import javax.security.auth.login.LoginException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
public class AOSchedulerWorker extends AOWorker implements SchedulerEventListener {
/**
* interface to scheduler
*/
private UserSchedulerInterface scheduler;
/**
* Current tasks processed by the scheduler
*/
private HashMap<JobId, Collection<TaskIntern<Serializable>>> processing;
/**
* url to the scheduler
*/
private String schedulerUrl;
/**
* user name
*/
private String user;
/**
* password
*/
private String password;
/**
* ProActive no arg contructor
*/
public AOSchedulerWorker() {
}
/**
* Creates a worker with the given name connected to a scheduler
* @param name name of the worker
* @param provider the entity which will provide tasks to the worker
* @param initialMemory initial memory of the worker
* @param schedulerUrl url of the scheduler
* @param user username
* @param passwd paswword
* @throws SchedulerException
* @throws LoginException
*/
public AOSchedulerWorker(final String name, final WorkerMaster provider,
final Map<String, Serializable> initialMemory, String schedulerUrl, String user, String passwd)
throws SchedulerException, LoginException {
super(name, provider, initialMemory);
this.schedulerUrl = schedulerUrl;
this.user = user;
this.password = passwd;
}
/*
* (non-Javadoc)
*
* @see org.objectweb.proactive.extensions.masterworker.core.AOWorker#initActivity(org.objectweb.proactive.Body)
*/
public void initActivity(Body body) {
stubOnThis = (AOSchedulerWorker) PAActiveObject.getStubOnThis();
SchedulerAuthenticationInterface auth;
try {
auth = SchedulerConnection.join(schedulerUrl);
this.scheduler = auth.logAsUser(user, password);
} catch (LoginException e) {
throw new ProActiveRuntimeException(e);
} catch (SchedulerException e1) {
throw new ProActiveRuntimeException(e1);
}
this.processing = new HashMap<JobId, Collection<TaskIntern<Serializable>>>();
// We register this active object as a listener
try {
this.scheduler.addSchedulerEventListener((AOSchedulerWorker) stubOnThis,
SchedulerEvent.JOB_KILLED, SchedulerEvent.JOB_RUNNING_TO_FINISHED, SchedulerEvent.KILLED,
SchedulerEvent.SHUTDOWN, SchedulerEvent.SHUTTING_DOWN);
} catch (SchedulerException e) {
e.printStackTrace();
}
PAActiveObject.setImmediateService("heartBeat");
PAActiveObject.setImmediateService("terminate");
// Initial Task
stubOnThis.getTaskAndSchedule();
}
public void clear() {
for (JobId id : processing.keySet()) {
try {
scheduler.kill(id);
} catch (SchedulerException e) {
logger.error(e.getMessage());
}
}
processing.clear();
provider.isCleared(stubOnThis);
}
/**
* ScheduleTask : find a new task to run (actually here a task is a scheduler job)
*/
public void scheduleTask() {
if (debug) {
logger.debug(name + " schedules tasks...");
}
while (pendingTasksFutures.size() > 0) {
pendingTasks.addAll(pendingTasksFutures.remove());
}
if (pendingTasks.size() > 0) {
TaskFlowJob job = new TaskFlowJob();
job.setName("Master-Worker Framework Job " + pendingTasks.peek().getId());
job.setPriority(JobPriority.NORMAL);
job.setCancelOnError(true);
job.setDescription("Set of parallel master-worker tasks");
Collection<TaskIntern<Serializable>> newTasks = new ArrayList<TaskIntern<Serializable>>();
while (pendingTasks.size() > 0) {
TaskIntern<Serializable> task = pendingTasks.remove();
newTasks.add(task);
JavaExecutable schedExec = new SchedulerExecutableAdapter(task);
JavaTask schedulerTask = new JavaTask();
schedulerTask.setName("" + task.getId());
schedulerTask.setPreciousResult(true);
// schedulerTask.setTaskInstance(schedExec);
try {
job.addTask(schedulerTask);
} catch (UserException e) {
e.printStackTrace();
}
}
try {
JobId jobId = scheduler.submit(job);
processing.put(jobId, newTasks);
} catch (SchedulerException e) {
e.printStackTrace();
}
} else {
// if there is nothing to do we sleep i.e. we do nothing
if (debug) {
logger.debug(name + " sleeps...");
}
}
}
/**
* Terminate this worker
*/
public BooleanWrapper terminate() {
try {
scheduler.disconnect();
} catch (SchedulerException e) {
// ignore
}
return super.terminate();
}
public void jobChangePriorityEvent(JobEvent event) {
// TODO Auto-generated method stub
}
public void jobKilledEvent(JobId jobId) {
if (!processing.containsKey(jobId)) {
return;
}
jobDidNotSucceed(jobId, new TaskException(new SchedulerException("Job id=" + jobId + " was killed")));
}
public void jobPausedEvent(JobEvent event) {
// TODO Auto-generated method stub
}
public void jobPendingToRunningEvent(JobEvent event) {
// TODO Auto-generated method stub
}
public void jobRemoveFinishedEvent(JobEvent event) {
// TODO Auto-generated method stub
}
public void jobResumedEvent(JobEvent event) {
// TODO Auto-generated method stub
}
public void jobRunningToFinishedEvent(JobEvent event) {
if (debug) {
logger.debug(name + " receives job finished event...");
}
if (event == null) {
return;
}
if (!processing.containsKey(event.getJobId())) {
return;
}
JobResult jResult = null;
try {
jResult = scheduler.getJobResult(event.getJobId());
} catch (SchedulerException e) {
jobDidNotSucceed(event.getJobId(), new TaskException(e));
return;
}
if (debug) {
logger.debug(this.getName() + ": updating results of job: " + jResult.getName());
}
Collection<TaskIntern<Serializable>> tasksOld = processing.remove(event.getJobId());
ArrayList<ResultIntern<Serializable>> results = new ArrayList<ResultIntern<Serializable>>();
HashMap<String, TaskResult> allTaskResults = jResult.getAllResults();
for (TaskIntern<Serializable> task : tasksOld) {
if (debug) {
logger.debug(this.getName() + ": looking for result of task: " + task.getId());
}
ResultIntern<Serializable> intres = new ResultInternImpl(task.getId());
TaskResult result = allTaskResults.get("" + task.getId());
if (result == null) {
intres.setException(new TaskException(new SchedulerException("Task id=" + task.getId() +
" was not returned by the scheduler")));
if (debug) {
logger
.debug("Task result not found in job result: " +
intres.getException().getMessage());
}
} else if (result.hadException()) { //Exception took place inside the framework
intres.setException(new TaskException(result.getException()));
if (debug) {
logger.debug("Task result contains exception: " + intres.getException().getMessage());
}
} else {
try {
Serializable computedResult = (Serializable) result.value();
intres.setResult(computedResult);
} catch (Throwable e) {
intres.setException(new TaskException(e));
if (debug) {
logger.debug(intres.getException().getMessage());
}
}
}
results.add(intres);
}
Queue<TaskIntern<Serializable>> newTasks = provider.sendResultsAndGetTasks(results, name, true);
pendingTasksFutures.offer(newTasks);
// Schedule a new job
stubOnThis.scheduleTask();
}
public void jobSubmittedEvent(Job job) {
// TODO Auto-generated method stub
}
public void schedulerFrozenEvent() {
// TODO Auto-generated method stub
}
public void schedulerKilledEvent() {
for (JobId jobId : processing.keySet()) {
jobDidNotSucceed(jobId, new TaskException(new SchedulerException("Scheduler was killed")));
}
}
public void schedulerPausedEvent() {
// TODO Auto-generated method stub
}
public void schedulerResumedEvent() {
// TODO Auto-generated method stub
}
public void schedulerShutDownEvent() {
}
public void schedulerShuttingDownEvent() {
for (JobId jobId : processing.keySet()) {
jobDidNotSucceed(jobId, new TaskException(new SchedulerException("Scheduler is shutting down")));
}
}
public void schedulerStartedEvent() {
// TODO Auto-generated method stub
}
public void schedulerStoppedEvent() {
// TODO Auto-generated method stub
}
public void taskPendingToRunningEvent(TaskEvent event) {
// TODO Auto-generated method stub
}
public void taskRunningToFinishedEvent(TaskEvent event) {
// TODO Auto-generated method stub
}
public void schedulerRMDownEvent() {
// TODO Auto-generated method stub
}
public void schedulerRMUpEvent() {
// TODO Auto-generated method stub
}
/**
* The job failed
* @param jobId id of the job
* @param ex exception thrown
*/
private void jobDidNotSucceed(JobId jobId, Exception ex) {
if (debug) {
logger.debug("Job did not succeed: " + ex.getMessage());
}
if (!processing.containsKey(jobId)) {
return;
}
Collection<TaskIntern<Serializable>> tList = processing.remove(jobId);
ArrayList<ResultIntern<Serializable>> results = new ArrayList<ResultIntern<Serializable>>();
for (TaskIntern<Serializable> task : tList) {
ResultIntern<Serializable> intres = new ResultInternImpl(task.getId());
intres.setException(ex);
results.add(intres);
}
Queue<TaskIntern<Serializable>> newTasks = provider.sendResultsAndGetTasks(results, name, true);
pendingTasksFutures.offer(newTasks);
// Schedule a new job
stubOnThis.scheduleTask();
}
public void usersUpdate(UserIdentification userIdentification) {
// TODO Auto-generated method stub
}
public void taskWaitingForRestart(TaskEvent event) {
// TODO Auto-generated method stub
}
}
|
package org.eclipse.birt.report.engine.api.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.DataEngine;
import org.eclipse.birt.data.engine.api.IPreparedQuery;
import org.eclipse.birt.data.engine.api.IQueryResults;
import org.eclipse.birt.data.engine.api.IResultIterator;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IParameterSelectionChoice;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.data.IDataEngine;
import org.eclipse.birt.report.model.api.CascadingParameterGroupHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.ParameterHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SelectionChoiceHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import com.ibm.icu.util.ULocale;
/**
* Defines an engine task that handles parameter definition retrieval
*/
public class GetParameterDefinitionTask extends EngineTask
implements
IGetParameterDefinitionTask
{
private static final String VALUE_PREFIX = "__VALUE__";
private static final String LABEL_PREFIX = "__LABEL__";
// stores all parameter definitions. Each task clones the parameter
// definition information
// so that Engine IR (repor runnable) can keep a task-independent of the
// parameter definitions.
protected Collection parameterDefns = null;
protected HashMap dataCache = null;
// protected HashMap labelMap = null;
// protected HashMap valueMap = null;
private List labelColumnBindingNames = null;
/**
* @param engine
* reference to the report engine
* @param runnable
* the runnable report design
*/
public GetParameterDefinitionTask( IReportEngine engine,
IReportRunnable runnable )
{
super( engine, runnable );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#getParameterDefns(boolean)
*/
public Collection getParameterDefns( boolean includeParameterGroups )
{
Collection original = ( (ReportRunnable) runnable )
.getParameterDefns( includeParameterGroups );
Iterator iter = original.iterator( );
// Clone parameter definitions, fill in locale and report dsign
// information
parameterDefns = new ArrayList( );
while ( iter.hasNext( ) )
{
ParameterDefnBase pBase = (ParameterDefnBase) iter.next( );
try
{
parameterDefns.add( pBase.clone( ) );
}
catch ( CloneNotSupportedException e ) // This is a Java
// exception
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
if ( parameterDefns != null )
{
iter = parameterDefns.iterator( );
while ( iter.hasNext( ) )
{
IParameterDefnBase pBase = (IParameterDefnBase) iter.next( );
if ( pBase instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) pBase )
.setReportDesign( (ReportDesignHandle) runnable
.getDesignHandle( ) );
( (ScalarParameterDefn) pBase ).setLocale( locale );
( (ScalarParameterDefn) pBase ).evaluateSelectionList( );
}
else if ( pBase instanceof ParameterGroupDefn )
{
( (ParameterGroupDefn) pBase )
.setReportDesign( (ReportDesignHandle) runnable
.getDesignHandle( ) );
Iterator iter2 = ( (ParameterGroupDefn) pBase )
.getContents( ).iterator( );
while ( iter2.hasNext( ) )
{
IParameterDefnBase p = (IParameterDefnBase) iter2
.next( );
if ( p instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) p )
.setReportDesign( (ReportDesignHandle) runnable
.getDesignHandle( ) );
( (ScalarParameterDefn) p ).setLocale( locale );
( (ScalarParameterDefn) p ).evaluateSelectionList( );
}
}
}
}
}
return parameterDefns;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#evaluateDefaults()
*/
public void evaluateDefaults( ) throws EngineException
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getParameterDefn(java.lang.String)
*/
public IParameterDefnBase getParameterDefn( String name )
{
IParameterDefnBase ret = null;
if ( name == null )
{
return ret;
}
Collection original = ( (ReportRunnable) runnable )
.getParameterDefns( true );
Iterator iter = original.iterator( );
while ( iter.hasNext( ) )
{
ret = getParamDefnBaseByName( (ParameterDefnBase) iter.next( ),
name );
if ( ret != null )
break;
}
if ( ret != null )
{
if ( ret instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) ret )
.setReportDesign( (ReportDesignHandle) runnable
.getDesignHandle( ) );
( (ScalarParameterDefn) ret ).setLocale( locale );
( (ScalarParameterDefn) ret ).evaluateSelectionList( );
}
else if ( ret instanceof ParameterGroupDefn )
{
( (ParameterGroupDefn) ret )
.setReportDesign( (ReportDesignHandle) runnable
.getDesignHandle( ) );
( (ParameterGroupDefn) ret ).setLocale( locale );
Iterator iter2 = ( (ParameterGroupDefn) ret ).getContents( )
.iterator( );
while ( iter2.hasNext( ) )
{
IParameterDefnBase p = (IParameterDefnBase) iter2.next( );
if ( p instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) p )
.setReportDesign( (ReportDesignHandle) runnable
.getDesignHandle( ) );
( (ScalarParameterDefn) p ).setLocale( locale );
( (ScalarParameterDefn) p ).evaluateSelectionList( );
}
}
}
}
return ret;
}
public SlotHandle getParameters( )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.getParameters( );
}
public ParameterHandle getParameter( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.findParameter( name );
}
public HashMap getDefaultValues( )
{
// using current parameter settings to evaluate the default parameters
usingParameterValues( );
final HashMap values = new HashMap( );
// reset the context parameters
new ParameterVisitor( ) {
boolean visitScalarParameter( ScalarParameterHandle param,
Object userData )
{
String name = param.getName( );
String expr = param.getDefaultValue( );
String type = param.getDataType( );
Object value = convertToType( expr, type );
values.put( name, value );
return true;
}
boolean visitParameterGroup( ParameterGroupHandle group,
Object userData )
{
return visitParametersInGroup( group, userData );
}
}.visit( (ReportDesignHandle) runnable.getDesignHandle( ) );
return values;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getDefaultParameter(java.lang.String)
*/
public Object getDefaultValue( IParameterDefnBase param )
{
return ( param == null ) ? null : getDefaultValue( param.getName( ) );
}
public Object getDefaultValue( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
ScalarParameterHandle parameter = (ScalarParameterHandle) report
.findParameter( name );
if ( parameter == null )
{
return null;
}
usingParameterValues( );
// using the current setting to evaluate the parameter values.
String expr = parameter.getDefaultValue( );
if ( expr == null || expr.length( ) == 0 )
{
return null;
}
return convertToType( expr, parameter.getDataType( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getSelectionChoice(java.lang.String)
*/
public Collection getSelectionList( String name )
{
usingParameterValues( );
ReportDesignHandle report = (ReportDesignHandle) this.runnable
.getDesignHandle( );
ScalarParameterHandle parameter = (ScalarParameterHandle) report
.findParameter( name );
if ( parameter == null )
{
return Collections.EMPTY_LIST;
}
String selectionType = parameter.getValueType( );
String dataType = parameter.getDataType( );
boolean fixedOrder = parameter.isFixedOrder( );
if ( DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC
.equals( selectionType ) )
{
CascadingParameterGroupHandle group = null;
if ( isCascadingParameter( parameter ) )
{
group = getCascadingGroup( parameter );
}
if ( group != null
&& DesignChoiceConstants.DATA_SET_MODE_SINGLE.equals( group
.getDataSetMode( ) ) )
{
return getCascadingParameterList( parameter );
}
else if ( parameter.getDataSetName( ) != null )
{
return getChoicesFromParameterQuery( parameter );
}
else if ( group != null )
{
return getCascadingParameterList( parameter );
}
}
else if ( DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC
.equals( selectionType ) )
{
Iterator iter = parameter.choiceIterator( );
ArrayList choices = new ArrayList( );
while ( iter.hasNext( ) )
{
SelectionChoiceHandle choice = (SelectionChoiceHandle) iter
.next( );
String label = report
.getMessage( choice.getLabelKey( ), locale );
if ( label == null )
{
label = choice.getLabel( );
}
Object value = getStringValue( choice.getValue( ), dataType );
choices.add( new SelectionChoice( label, value ) );
}
if ( !fixedOrder )
Collections
.sort( choices, new SelectionChoiceComparator( true, parameter.getPattern( ), ULocale.forLocale( locale ) ) );
return choices;
}
return Collections.EMPTY_LIST;
}
private Collection getCascadingParameterList( ScalarParameterHandle parameter )
{
Object[] parameterValuesAhead = getParameterValuesAhead( parameter );
return getChoicesFromParameterGroup ( parameter, parameterValuesAhead );
}
/**
* convert the string to value.
*
* @param value
* value string
* @param valueType
* value type
* @return object with the specified value
*/
private Object getStringValue( String value, String valueType )
{
try
{
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( valueType ) )
return DataTypeUtil.toBoolean( value );
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( valueType ) )
return DataTypeUtil.toDate( value );
if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( valueType ) )
return DataTypeUtil.toBigDecimal( value );
if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( valueType ) )
return DataTypeUtil.toDouble( value );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getLocalizedMessage( ), e );
}
return value;
}
/**
* get selection choices from the data set.
*
* @param dataSetName
* data set name
* @param labelStmt
* label statement
* @param valueStmt
* value statement
* @param dataType
* value type
* @return
*/
private Collection createDynamicSelectionChoices( String pattern, String dataSetName,
String labelStmt, String valueStmt, String dataType, int limit,
boolean fixedOrder )
{
ArrayList choices = new ArrayList( );
ReportDesignHandle report = (ReportDesignHandle) this.runnable
.getDesignHandle( );
DataSetHandle dataSet = report.findDataSet( dataSetName );
if ( dataSet != null )
{
try
{
IDataEngine dataEngine = executionContext.getDataEngine( );
DataEngine dteDataEngine = getDataEngine();
// Define data source and data set
dataEngine.defineDataSet(dataSet);
ScriptExpression labelExpr = null;
if ( labelStmt != null && labelStmt.length( ) > 0 )
{
labelExpr = new ScriptExpression( labelStmt );
}
ScriptExpression valueExpr = new ScriptExpression( valueStmt );
QueryDefinition queryDefn = new QueryDefinition( );
queryDefn.setDataSetName( dataSetName );
if( limit > 0)
{
queryDefn.setMaxRows( limit );
}
// add parameters if have any
Iterator paramIter = dataSet.paramBindingsIterator( );
while ( paramIter.hasNext( ) )
{
ParamBindingHandle binding = (ParamBindingHandle) paramIter
.next( );
String paramName = binding.getParamName( );
String paramExpr = binding.getExpression( );
queryDefn.getInputParamBindings( ).add(
new InputParameterBinding( paramName,
new ScriptExpression( paramExpr ) ) );
}
String labelColumnName = LABEL_PREFIX;;
String valueColumnName = VALUE_PREFIX;;
if ( labelExpr != null )
{
queryDefn.addResultSetExpression( labelColumnName, labelExpr );
}
queryDefn.addResultSetExpression( valueColumnName, valueExpr );
// Create a group to skip all of the duplicate values
GroupDefinition groupDef = new GroupDefinition( );
groupDef.setKeyColumn( valueColumnName );
queryDefn.addGroup( groupDef );
queryDefn.setAutoBinding( true );
IPreparedQuery query = dteDataEngine.prepare( queryDefn, this.appContext );
IQueryResults result = query.execute( executionContext
.getSharedScope( ) );
IResultIterator iter = result.getResultIterator( );
int count = 0;
while ( iter.next( ) )
{
String label = null;
if ( labelExpr != null )
{
label = iter.getString( labelColumnName );
}
Object value = iter.getValue( valueColumnName );
choices.add( new SelectionChoice( label, convertToType(
value, dataType ) ) );
count++;
if ( ( limit != 0 ) && ( count >= limit ) )
{
break;
}
iter.skipToEnd( 1 ); // Skip all of the duplicate values
}
}
catch ( BirtException ex )
{
ex.printStackTrace( );
}
}
if ( !fixedOrder )
Collections.sort( choices, new SelectionChoiceComparator( true, pattern, ULocale.forLocale( locale ) ) );
return choices;
}
/**
* The first step to work with the cascading parameters. Create the query
* definition, prepare and execute the query. Cache the iterator of the
* result set and also cache the IBaseExpression used in the prepare.
*
* @param parameterGroupName -
* the cascading parameter group name
*/
public void evaluateQuery( String parameterGroupName )
{
CascadingParameterGroupHandle parameterGroup = getCascadingParameterGroup( parameterGroupName );
if ( dataCache == null )
dataCache = new HashMap( );
if ( parameterGroup == null )
return;
//If a IResultIterator with the same name has already existed in the dataCache,
//this IResultIterator and its IQueryResults should be closed.
IResultIterator iterOld = (IResultIterator) dataCache.get( parameterGroup.getName( ) );
if ( iterOld != null )
{
dataCache.remove( parameterGroup.getName( ) );
try
{
IQueryResults iresultOld = iterOld.getQueryResults();
iterOld.close( );
iresultOld.close( );
}
catch ( BirtException ex )
{
log.log( Level.WARNING, ex.getMessage( ) );
}
}
DataSetHandle dataSet = parameterGroup.getDataSet( );
if ( dataSet != null )
{
try
{
// Handle data source and data set
DataEngine dteDataEngine = getDataEngine( );
IDataEngine dataEngine = executionContext.getDataEngine( );
dataEngine.defineDataSet( dataSet );
QueryDefinition queryDefn = new QueryDefinition( );
queryDefn.setDataSetName( dataSet.getQualifiedName( ) );
SlotHandle parameters = parameterGroup.getParameters( );
Iterator iter = parameters.iterator( );
/* if ( labelMap == null )
labelMap = new HashMap( );
if ( valueMap == null )
valueMap = new HashMap( );*/
if ( labelColumnBindingNames == null )
labelColumnBindingNames = new ArrayList();
while ( iter.hasNext( ) )
{
Object param = iter.next( );
if ( param instanceof ScalarParameterHandle )
{
String valueExpString = ( (ScalarParameterHandle) param )
.getValueExpr( );
ScriptExpression valueExpObject = new ScriptExpression(
valueExpString );
String keyValue = VALUE_PREFIX+parameterGroup.getName( ) + "_"
+ ( (ScalarParameterHandle) param ).getName( );
/* valueMap.put( keyValue,
valueExpObject );*/
queryDefn.addResultSetExpression( keyValue, valueExpObject );
//queryDefn.getRowExpressions( ).add( valueExpObject );
String labelExpString = ( (ScalarParameterHandle) param )
.getLabelExpr( );
if ( labelExpString != null
&& labelExpString.length( ) > 0 )
{
ScriptExpression labelExpObject = new ScriptExpression(
labelExpString );
String keyLabel = LABEL_PREFIX+parameterGroup.getName( ) + "_"
+ ( (ScalarParameterHandle) param ).getName( );
/* labelMap.put( keyLabel, labelExpObject );
queryDefn.getRowExpressions( ).add( labelExpObject );*/
labelColumnBindingNames.add( keyLabel );
queryDefn.addResultSetExpression( keyLabel, labelExpObject );
}
GroupDefinition groupDef = new GroupDefinition( );
groupDef.setKeyExpression( valueExpString );
queryDefn.addGroup( groupDef );
}
}
queryDefn.setAutoBinding( true );
IPreparedQuery query = dteDataEngine.prepare( queryDefn, this.appContext );
IQueryResults result = query.execute( executionContext
.getSharedScope( ) );
IResultIterator resultIter = result.getResultIterator( );
dataCache.put( parameterGroup.getName( ), resultIter );
return;
}
catch ( BirtException ex )
{
ex.printStackTrace( );
}
}
dataCache.put( parameterGroup.getName( ), null );
}
/**
* The second step to work with the cascading parameters. Get the selection
* choices for a parameter in the cascading group. The parameter to work on
* is the parameter on the next level in the parameter cascading hierarchy.
* For the "parameter to work on", please see the following example. Assume
* we have a cascading parameter group as Country - State - City. If user
* specified an empty array in groupKeyValues (meaning user doesn't have any
* parameter value), the parameter to work on will be the first level which
* is Country in this case. If user specified groupKeyValues as
* Object[]{"USA"} (meaning user has set the value of the top level), the
* parameter to work on will be the second level which is State in "USA" in
* this case. If user specified groupKeyValues as Object[]{"USA", "CA"}
* (meaning user has set the values of the top and the second level), the
* parameter to work on will be the third level which is City in "USA, CA"
* in this case.
*
* @param parameterGroupName -
* the cascading parameter group name
* @param groupKeyValues -
* the array of known parameter values (see the example above)
* @return the selection list of the parameter to work on
*/
public Collection getSelectionListForCascadingGroup(
String parameterGroupName, Object[] groupKeyValues )
{
CascadingParameterGroupHandle parameterGroup = getCascadingParameterGroup( parameterGroupName );
if ( parameterGroup == null )
return Collections.EMPTY_LIST;
SlotHandle slotHandle = parameterGroup.getParameters( );
if ( groupKeyValues.length >= slotHandle.getCount( ) )
{
return Collections.EMPTY_LIST;
}
for ( int i = 0; i < groupKeyValues.length; i++ )
{
String parameterName = (( ScalarParameterHandle ) slotHandle.get( i )).getName( );
setParameterValue( parameterName, groupKeyValues[ i ] );
}
ScalarParameterHandle requestedParam = (ScalarParameterHandle) slotHandle
.get( groupKeyValues.length ); // The parameters in
// parameterGroup must be scalar
// parameters.
if ( requestedParam == null )
{
return Collections.EMPTY_LIST;
}
return this.getSelectionList( requestedParam.getName( ) );
}
private Collection getChoicesFromParameterGroup( ScalarParameterHandle parameter, Object[] groupKeyValues )
{
assert isCascadingParameter( parameter );
CascadingParameterGroupHandle parameterGroup = getCascadingGroup( parameter );
String parameterGroupName = parameterGroup.getName( );
evaluateQuery( parameterGroupName );
IResultIterator iter = (IResultIterator) dataCache.get( parameterGroupName );
if ( iter == null )
{
evaluateQuery( parameterGroupName );
if ( iter == null )
{
return Collections.EMPTY_LIST;
}
}
String labelColumnName = LABEL_PREFIX + parameterGroupName + "_" + parameter.getName( );
String valueColumnName = VALUE_PREFIX + parameterGroupName + "_" + parameter.getName( );
int listLimit = parameter.getListlimit( );
ArrayList choices = new ArrayList( );
int skipLevel = groupKeyValues.length + 1;
try
{
if ( skipLevel > 1 )
iter.findGroup( groupKeyValues );
int startGroupLevel = skipLevel - 1;
int count = 0;
while ( iter.next( ) )
{
// startGroupLevel = iter.getStartingGroupLevel();
String label = ( labelColumnBindingNames.contains( labelColumnName )
? iter.getString( labelColumnName )
: null );
Object value = iter.getValue( valueColumnName );
// value = convertToType( value, valueType );
choices.add( new SelectionChoice( label, value ) );
count++;
if ( ( listLimit != 0 ) && ( count >= listLimit ) )
break;
iter.skipToEnd( skipLevel );
int endGroupLevel = iter.getEndingGroupLevel( );
if ( endGroupLevel <= startGroupLevel )
{
break;
}
}
}
catch ( BirtException e )
{
e.printStackTrace( );
}
if ( !parameter.isFixedOrder( ) )
Collections.sort( choices, new SelectionChoiceComparator( true, parameter.getPattern( ), ULocale.forLocale( locale ) ) );
return choices;
}
private CascadingParameterGroupHandle getCascadingParameterGroup(
String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.findCascadingParameterGroup( name );
}
static class SelectionChoice implements IParameterSelectionChoice
{
String label;
Object value;
SelectionChoice( String label, Object value )
{
this.label = label;
this.value = value;
}
public String getLabel( )
{
return this.label;
}
public Object getValue( )
{
return this.value;
}
}
public void close( )
{
if ( dataCache != null )
{
Iterator it = dataCache.entrySet( ).iterator( );
while (it.hasNext())
{
Map.Entry entry = (Map.Entry)it.next();
IResultIterator iter = (IResultIterator) entry.getValue();
if( null == iter)
continue;
try
{
IQueryResults iresult = iter.getQueryResults();
iter.close( );
iresult.close( );
}
catch ( BirtException ex )
{
log.log( Level.WARNING, ex.getMessage( ) );
}
}
dataCache.clear( );
dataCache = null;
}
super.close( );
}
private boolean isCascadingParameter( ScalarParameterHandle parameter )
{
return parameter.getContainer( ) instanceof CascadingParameterGroupHandle;
}
private Object[] getParameterValuesAhead( ScalarParameterHandle parameter )
{
assert isCascadingParameter( parameter );
CascadingParameterGroupHandle parameterGroup = getCascadingGroup( parameter );
SlotHandle parameters = parameterGroup.getParameters( );
List values = new ArrayList( );
for ( int i = 0; i < parameters.getCount( ); i++ )
{
ScalarParameterHandle tempParameter = ( ScalarParameterHandle ) parameters.get( i );
if ( tempParameter == parameter )
{
break;
}
values.add( getParameterValue( tempParameter.getName( ) ) );
}
return values.toArray( );
}
private CascadingParameterGroupHandle getCascadingGroup( ScalarParameterHandle parameter )
{
DesignElementHandle handle = parameter.getContainer( );
assert handle instanceof CascadingParameterGroupHandle;
CascadingParameterGroupHandle parameterGroup = ( CascadingParameterGroupHandle ) handle;
return parameterGroup;
}
private Collection getChoicesFromParameterQuery( ScalarParameterHandle parameter)
{
String dataType = parameter.getDataType( );
boolean fixedOrder = parameter.isFixedOrder( );
String dataSetName = parameter.getDataSetName( );
String valueExpr = parameter.getValueExpr( );
String labelExpr = parameter.getLabelExpr( );
int limit = parameter.getListlimit( );
String pattern = parameter.getPattern( );
return createDynamicSelectionChoices( pattern, dataSetName, labelExpr,
valueExpr, dataType, limit, fixedOrder );
}
private IParameterDefnBase getParamDefnBaseByName( ParameterDefnBase param,
String name )
{
ParameterDefnBase ret = null;
if ( param instanceof ScalarParameterDefn
&& name.equals( param.getName( ) ) )
{
ret = param;
}
else if ( param instanceof ParameterGroupDefn )
{
if ( name.equals( param.getName( ) ) )
{
ret = param;
}
else
{
Iterator iter = ( (ParameterGroupDefn) param ).getContents( )
.iterator( );
while ( iter.hasNext( ) )
{
ParameterDefnBase pBase = (ParameterDefnBase) iter.next( );
if ( name.equals( pBase.getName( ) ) )
{
ret = pBase;
break;
}
}
}
}
if ( ret != null )
{
try
{
return (IParameterDefnBase) ret.clone( );
}
catch ( CloneNotSupportedException e )
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
return ret;
}
}
|
package at.ac.tuwien.inso.method_security_tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
import at.ac.tuwien.inso.controller.lecturer.forms.AddCourseForm;
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Lecturer;
import at.ac.tuwien.inso.entity.Role;
import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.entity.SemesterType;
import at.ac.tuwien.inso.entity.Student;
import at.ac.tuwien.inso.entity.Subject;
import at.ac.tuwien.inso.entity.UisUser;
import at.ac.tuwien.inso.entity.UserAccount;
import at.ac.tuwien.inso.exception.BusinessObjectNotFoundException;
import at.ac.tuwien.inso.exception.ValidationException;
import at.ac.tuwien.inso.repository.CourseRepository;
import at.ac.tuwien.inso.repository.LecturerRepository;
import at.ac.tuwien.inso.repository.SemesterRepository;
import at.ac.tuwien.inso.repository.StudentRepository;
import at.ac.tuwien.inso.repository.SubjectRepository;
import at.ac.tuwien.inso.repository.UisUserRepository;
import at.ac.tuwien.inso.service.CourseService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class CourseServiceSecurityTests {
@Autowired
private CourseService courseService;
@Autowired
private CourseRepository courseRepository;
@Autowired
private SubjectRepository subjectRepository;
@Autowired
private SemesterRepository semesterRepository;
@Autowired
private LecturerRepository lecturerRepository;
@Autowired
private StudentRepository studentRepository;
private Lecturer lecturer;
private Course course;
private Student student;
private Student adminaccount;
private UserAccount user = new UserAccount("student1", "pass", Role.STUDENT);
private UserAccount admin = new UserAccount("admin1", "pass", Role.ADMIN);
private UserAccount lecturerRole = new UserAccount("Lecturer", "pass", Role.LECTURER);
@BeforeTransaction
public void beforeTransaction() {
student = studentRepository.save(new Student("1", "student1", "student@student.com", user));
//workaround because it is not possible to instanceise an admin
adminaccount = studentRepository.save(new Student("2", "admin1", "admin@test.com", admin));
}
@AfterTransaction
public void afterTransaction() {
studentRepository.delete(student);
studentRepository.delete(adminaccount);
}
@Before
public void setUp() {
lecturer = lecturerRepository.save(new Lecturer("2", "Lecturer", "lecturer@lecturer.com", lecturerRole));
Subject subject = subjectRepository.save(new Subject("ASE", BigDecimal.valueOf(6)));
subject.addLecturers(lecturer);
subjectRepository.save(subject);
Semester semester = semesterRepository.save(new Semester(2016, SemesterType.WinterSemester));
course = courseRepository.save(new Course(subject, semester));
course.setStudentLimits(0);
course.addStudents(student);
}
@After
public void destroy(){
course.removeStudents(student);
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void findCourseForCurrentSemesterWithNameNotAuthenticated() {
courseService.findCourseForCurrentSemesterWithName("test", new PageRequest(1, 1));
}
@Test
@WithMockUser
public void findCourseForCurrentSemesterWithNameAuthenticated() {
Page<Course> results = courseService.findCourseForCurrentSemesterWithName("ASE", new PageRequest(0, 1));
assertFalse(results.getContent().isEmpty());
assertEquals(results.getContent().get(0).getSubject().getName(), "ASE");
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void findCoursesForCurrentSemesterForLecturerNotAuthenticated() {
courseService.findCoursesForCurrentSemesterForLecturer(lecturer);
}
@Test
@WithMockUser
public void findCoursesForCurrentSemesterForLecturerAuthenticated() {
List<Course> courses = courseService.findCoursesForCurrentSemesterForLecturer(lecturer);
assertTrue(courses.size() == 1);
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void saveCourseNotAuthenticated() {
AddCourseForm addCourseForm = new AddCourseForm(course);
courseService.saveCourse(addCourseForm);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "student1", roles = "STUDENT")
public void saveCourseAuthenticatedAsStudent() {
AddCourseForm addCourseForm = new AddCourseForm(course);
courseService.saveCourse(addCourseForm);
}
@Test
@WithMockUser(roles = "ADMIN", username="admin1")
public void saveCourseAuthenticatedAsAdmin() {
AddCourseForm addCourseForm = new AddCourseForm(course);
Course result = courseService.saveCourse(addCourseForm);
assertTrue(addCourseForm.getCourse().equals(result));
}
@Test
@WithMockUser(roles = "LECTURER", username="Lecturer")
public void saveCourseAuthenticatedAsLecturer() {
AddCourseForm addCourseForm = new AddCourseForm(course);
Course result = courseService.saveCourse(addCourseForm);
assertTrue(addCourseForm.getCourse().equals(result));
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void findOneNotAuthenticated() {
courseService.findOne(Long.parseLong("1"));
}
@Test
@WithMockUser
public void findOneAuthenticated() {
Course result = courseService.findOne(course.getId());
assertTrue(course.getId().equals(result.getId()));
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void registerStudentForCourseNotAuthenticated() {
courseService.registerStudentForCourse(course);
}
@Test(expected = ValidationException.class)
@WithMockUser(roles = "LECTURER", username="Lecturer")
public void removeCourseAuthenticatedButHasStudents(){
AddCourseForm addCourseForm = new AddCourseForm(course);
Course result = courseService.saveCourse(addCourseForm);
assertTrue(addCourseForm.getCourse().equals(result));
courseService.remove(result.getId());
Course result2 = courseService.findOne(course.getId());
}
@Test(expected = BusinessObjectNotFoundException.class)
@WithMockUser(roles = "LECTURER", username="Lecturer")
public void removeCourseAuthenticated(){
course.removeStudents(student);
courseRepository.save(course);
AddCourseForm addCourseForm = new AddCourseForm(course);
Course result = courseService.saveCourse(addCourseForm);
assertTrue(addCourseForm.getCourse().equals(result));
courseService.remove(result.getId());
Course result2 = courseService.findOne(course.getId());
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void removeCourseNotAuthenticated(){
courseService.remove(course.getId());
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(roles = "ADMIN")
public void registerStudentForCourseAuthenticatedAsAdmin() {
courseService.registerStudentForCourse(course);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(roles = "LECTURER")
public void registerStudentForCourseAuthenticatedAsLecturer() {
courseService.registerStudentForCourse(course);
}
@Test
@WithUserDetails(value = "student1")
public void registerStudentForCourseAuthenticatedAsStudent() {
assertFalse(courseService.registerStudentForCourse(course));
}
}
|
package org.eclipse.birt.report.engine.executor.optimize;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.ir.BandDesign;
import org.eclipse.birt.report.engine.ir.CellDesign;
import org.eclipse.birt.report.engine.ir.DataItemDesign;
import org.eclipse.birt.report.engine.ir.DefaultReportItemVisitorImpl;
import org.eclipse.birt.report.engine.ir.DynamicTextItemDesign;
import org.eclipse.birt.report.engine.ir.ExtendedItemDesign;
import org.eclipse.birt.report.engine.ir.FreeFormItemDesign;
import org.eclipse.birt.report.engine.ir.GridItemDesign;
import org.eclipse.birt.report.engine.ir.GroupDesign;
import org.eclipse.birt.report.engine.ir.ImageItemDesign;
import org.eclipse.birt.report.engine.ir.ListingDesign;
import org.eclipse.birt.report.engine.ir.MasterPageDesign;
import org.eclipse.birt.report.engine.ir.PageSetupDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.ReportItemDesign;
import org.eclipse.birt.report.engine.ir.RowDesign;
import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign;
import org.eclipse.birt.report.engine.ir.TableItemDesign;
import org.eclipse.birt.report.engine.ir.TemplateDesign;
import org.eclipse.birt.report.engine.ir.TextItemDesign;
import org.w3c.dom.css.CSSValue;
public class ExecutionOptimize
{
public ExecutionOptimize( )
{
}
public ExecutionPolicy optimize( Report report )
{
return new OptimizeVisitor( report ).optimize( );
}
private static class PolicyNode
{
PolicyNode parent;
ArrayList children = new ArrayList( );
ReportItemDesign design;
boolean execute;
boolean breakBefore;
boolean breakAfter;
boolean executeAll;
}
private static class OptimizeVisitor extends DefaultReportItemVisitorImpl
{
Report report;
boolean disableOptimization;
boolean suppressDuplicate;
PolicyNode currentNode;
PolicyNode parentNode;
LinkedList rows = new LinkedList( );
OptimizeVisitor( Report report )
{
this.report = report;
}
ExecutionPolicy optimize( )
{
ExecutionPolicy policies = new ExecutionPolicy( );
if ( report.getOnPageStart( ) != null
|| report.getOnPageEnd( ) != null
|| report.getJavaClass( ) != null )
{
disableOptimization = true;
return null;
}
handleContent( policies );
// add all page content
handleMasterPage( policies );
if ( disableOptimization )
{
return null;
}
return policies;
}
protected void handleContent( ExecutionPolicy policy )
{
PolicyNode root = new PolicyNode( );
parentNode = root;
PolicyNode dummyFirst = new PolicyNode( );
dummyFirst.parent = root;
dummyFirst.breakAfter = true;
root.children.add( dummyFirst );
currentNode = dummyFirst;
int count = report.getContentCount( );
for ( int i = 0; i < count; i++ )
{
ReportItemDesign design = report.getContent( i );
design.accept( this, null );
}
PolicyNode dummyLast = new PolicyNode( );
dummyLast.parent = root;
dummyLast.breakBefore = true;
root.children.add( dummyLast );
// generate the policies;
generateExecutionPolicy( policy, root );
}
protected void handleMasterPage( ExecutionPolicy policy )
{
PolicyNode root = new PolicyNode( );
parentNode = root;
currentNode = root;
PageSetupDesign pageSetup = report.getPageSetup( );
int count = pageSetup.getMasterPageCount( );
for ( int i = 0; i < count; i++ )
{
MasterPageDesign masterPage = pageSetup.getMasterPage( i );
if ( masterPage.getOnPageStart( ) != null
|| masterPage.getOnPageEnd( ) != null )
{
// disable the whole optimization as the user can user
// getInstancessByElementId to access any content in run
// task
disableOptimization = true;
}
// FIXME handle others masterpage
if ( masterPage instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign simple = (SimpleMasterPageDesign) masterPage;
ArrayList headerList = simple.getHeaders( );
Iterator iter = headerList.iterator( );
while ( iter.hasNext( ) )
{
ReportItemDesign design = (ReportItemDesign) iter
.next( );
design.accept( this, null );
}
ArrayList footerList = simple.getFooters( );
iter = footerList.iterator( );
while ( iter.hasNext( ) )
{
ReportItemDesign design = (ReportItemDesign) iter
.next( );
design.accept( this, null );
}
}
}
generateMasterPageExecutionPolicy( policy, root );
}
protected void generateMasterPageExecutionPolicy(
ExecutionPolicy policy, PolicyNode root )
{
ArrayList children = root.children;
for ( int i = 0; i < children.size( ); i++ )
{
PolicyNode child = (PolicyNode) children.get( i );
child.executeAll = true;
}
for ( int i = 0; i < children.size( ); i++ )
{
PolicyNode child = (PolicyNode) children.get( i );
analysisExecutionPolicy( policy, child );
}
}
protected void generateExecutionPolicy( ExecutionPolicy policy,
PolicyNode root )
{
ArrayList children = root.children;
for ( int i = 0; i < children.size( ); i++ )
{
PolicyNode child = (PolicyNode) children.get( i );
handlePageBreak( child );
}
for ( int i = 0; i < children.size( ); i++ )
{
PolicyNode child = (PolicyNode) children.get( i );
analysisExecutionPolicy( policy, child );
}
if ( suppressDuplicate )
{
policy.enableSuppressDuplicate( );
}
}
protected boolean analysisExecutionPolicy( ExecutionPolicy policy,
PolicyNode node )
{
for ( int i = 0; i < node.children.size( ); i++ )
{
PolicyNode child = (PolicyNode) node.children.get( i );
if ( node.executeAll )
{
child.execute = true;
child.executeAll = true;
}
if ( analysisExecutionPolicy( policy, child ) )
{
node.execute = true;
}
}
if ( node.execute || node.executeAll )
{
if ( node.design != null )
{
policy.setExecute( node.design );
}
}
return node.execute;
}
protected PolicyNode findLastLeafNode( PolicyNode root )
{
if ( root != null && root.children.size( ) > 0 )
{
return findLastLeafNode( (PolicyNode) root.children
.get( root.children.size( ) - 1 ) );
}
else
{
return root;
}
}
protected PolicyNode findPreviousNode( PolicyNode node )
{
if ( node.design instanceof GroupDesign )
return node;
if ( node == null || node.parent == null )
{
return null;
}
int index = node.parent.children.indexOf( node );
if ( index < 1 )
{
return findPreviousNode( node.parent );
}
else
{
return (PolicyNode) node.parent.children.get( index - 1 );
}
}
protected PolicyNode findNextNode( PolicyNode node )
{
if ( node.design instanceof GroupDesign )
return node;
if ( node == null || node.parent == null )
{
return null;
}
int index = node.parent.children.indexOf( node );
int count = node.parent.children.size( );
if ( index < count - 1 )
{
return (PolicyNode) node.parent.children.get( index + 1 );
}
else
{
return findNextNode( node.parent );
}
}
protected void handlePageBreak( PolicyNode node )
{
if ( node.breakBefore )
{
node.execute = true;
PolicyNode leaf = findLastLeafNode( findPreviousNode( node ) );
if ( leaf != null )
{
leaf.execute = true;
}
}
if ( node.breakAfter )
{
node.execute = true;
PolicyNode leaf = findLastLeafNode( node );
if ( leaf != null )
{
leaf.execute = true;
}
PolicyNode next = findNextNode( node );
if ( next != null )
{
next.execute = true;
}
}
for ( int i = 0; i < node.children.size( ); i++ )
{
PolicyNode child = (PolicyNode) node.children.get( i );
handlePageBreak( child );
}
}
public Object visitExtendedItem( ExtendedItemDesign item, Object value )
{
PolicyNode parent = parentNode;
// setupPageBreaking...
visitReportItem( item, Boolean.TRUE );
parentNode = currentNode;
// we need execute all its children...
List children = item.getChildren( );
if ( children != null )
{
Iterator iter = children.iterator( );
while ( iter.hasNext( ) )
{
ReportItemDesign child = (ReportItemDesign) iter.next( );
child.accept( this, Boolean.TRUE );
}
}
parentNode = parent;
return Boolean.TRUE;
}
public Object visitTemplate( TemplateDesign template, Object value )
{
visitReportItem( template, Boolean.TRUE );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.DefaultReportItemVisitorImpl#visitFreeFormItem(org.eclipse.birt.report.engine.ir.FreeFormItemDesign,
* java.lang.Object)
*/
public Object visitFreeFormItem( FreeFormItemDesign container,
Object value )
{
PolicyNode parent = parentNode;
visitReportItem( container, value );
parentNode = currentNode;
// setup the previous line...
int count = container.getItemCount( );
for ( int i = 0; i < count; i++ )
{
ReportItemDesign item = container.getItem( i );
item.accept( this, null );
}
parentNode = parent;
return Boolean.TRUE;
}
public Object visitListing( ListingDesign listing, Object value )
{
PolicyNode parent = parentNode;
// visit listing itself.
visitReportItem( listing, Boolean.TRUE );
parentNode = currentNode;
//support horizontal page break
currentNode.breakAfter = true;
// visit listing header
BandDesign header = listing.getHeader( );
if ( header != null )
{
header.accept( this, null );
}
// visit listing groups
int groupCount = listing.getGroupCount( );
if ( groupCount > 0 )
{
processGroup( listing, 0, header != null );
processGroup( listing, 0, false );
}
else
{
processDetail( listing, header != null );
processDetail( listing, false );
}
// visit listing footer
BandDesign footer = listing.getFooter( );
if ( footer != null )
{
footer.accept( this, Boolean.TRUE );
}
// we need execute the next element in-case there is a
// page-break-after in the group footer.
parentNode = parent;
return Boolean.TRUE;
}
protected void processDetail( ListingDesign listing, boolean breakBefore )
{
BandDesign detail = listing.getDetail( );
if ( detail != null )
{
PolicyNode parent = parentNode;
visitReportItem( detail, true );
parentNode = currentNode;
int pageBreakInterval = listing.getPageBreakInterval( );
if ( pageBreakInterval > 0 )
{
currentNode.breakAfter = true;
}
if ( breakBefore )
{
currentNode.breakBefore = true;
}
int count = detail.getContentCount( );
for ( int i = 0; i < count; i++ )
{
ReportItemDesign item = detail.getContent( i );
item.accept( this, Boolean.TRUE );
}
parentNode = parent;
}
}
protected void processGroup( ListingDesign listing, int groupLevel,
boolean breakBefore )
{
GroupDesign group = listing.getGroup( groupLevel );
PolicyNode parent = parentNode;
// visit group header
visitReportItem( group, Boolean.TRUE );
parentNode = currentNode;
if ( group.getPageBreakAfter( ) != null )
{
currentNode.breakAfter = true;
}
if ( breakBefore || group.getPageBreakBefore( ) != null )
{
currentNode.breakBefore = true;
}
// visit listing header
BandDesign header = group.getHeader( );
if ( header != null )
{
header.accept( this, null );
}
if ( ++groupLevel < listing.getGroupCount( ) )
{
processGroup( listing, groupLevel, header != null );
}
else
{
processDetail( listing, true );
processDetail( listing, false );
}
// visit group footer
BandDesign footer = group.getFooter( );
if ( footer != null )
{
footer.accept( this, Boolean.TRUE );
}
parentNode = parent;
}
public Object visitBand( BandDesign band, Object value )
{
PolicyNode parent = parentNode;
visitReportItem( band, value );
parentNode = currentNode;
int count = band.getContentCount( );
for ( int i = 0; i < count; i++ )
{
ReportItemDesign item = band.getContent( i );
item.accept( this, null );
}
parentNode = parent;
return Boolean.TRUE;
}
public Object visitGridItem( GridItemDesign grid, Object value )
{
PolicyNode parent = parentNode;
visitReportItem( grid, value );
parentNode = currentNode;
//support horizontal page break
currentNode.breakAfter = true;
int count = grid.getRowCount( );
for ( int i = 0; i < count; i++ )
{
RowDesign row = grid.getRow( i );
row.accept( this, null );
}
parentNode = parent;
return Boolean.TRUE;
}
protected boolean hasListingObject(RowDesign row)
{
int cellCount = row.getCellCount( );
for ( int i = 0; i < cellCount; i++ )
{
CellDesign cell = row.getCell( i );
for ( int j = 0; j < cell.getContentCount( ); j++ )
{
ReportItemDesign item = cell.getContent( j );
if(item instanceof ListingDesign || item instanceof ExtendedItemDesign)
{
return true;
}
}
}
return false;
}
protected void setRowExecute( PolicyNode node )
{
node.execute = true;
for ( int i = 0; i < node.children.size( ); i++ )
{
PolicyNode child = (PolicyNode) node.children.get( i );
child.execute = true;
for ( int j = 0; j < child.children.size( ); j++ )
{
PolicyNode grandson = (PolicyNode) child.children.get( j );
grandson.execute = true;
}
}
}
public Object visitRow( RowDesign row, Object value )
{
PolicyNode parent = parentNode;
visitReportItem( row, true );
PolicyNode rowNode = currentNode;
parentNode = currentNode;
rows.addLast( currentNode );
int cellCount = row.getCellCount( );
for ( int i = 0; i < cellCount; i++ )
{
CellDesign cell = row.getCell( i );
cell.accept( this, null );
}
if ( hasListingObject( row ) )
{
setRowExecute( rowNode );
}
parentNode = parent;
rows.removeLast( );
return value;
}
public Object visitCell( CellDesign cell, Object value )
{
PolicyNode parent = parentNode;
visitReportItem( cell, value );
parentNode = currentNode;
if ( cell.getRowSpan( ) != 1 || cell.getColSpan( ) != 1
|| needProcessDrop( cell.getDrop( ) ))
{
currentNode.execute = true;
}
int count = cell.getContentCount( );
for ( int i = 0; i < count; i++ )
{
ReportItemDesign item = cell.getContent( i );
item.accept( this, null );
}
parentNode = parent;
return value;
}
private boolean needProcessDrop( String drop )
{
return drop != null && !"none".equals( drop );
}
public Object visitImageItem( ImageItemDesign image, Object value )
{
visitReportItem( image, Boolean.TRUE );
return value;
}
public Object visitDynamicTextItem( DynamicTextItemDesign multiLine,
Object value )
{
visitReportItem( multiLine, Boolean.TRUE );
return value;
}
public Object visitTextItem( TextItemDesign text, Object value )
{
visitReportItem( text, Boolean.TRUE );
return value;
}
public Object visitDataItem( DataItemDesign data, Object value )
{
visitReportItem( data, value );
if ( data.getSuppressDuplicate( ) )
{
suppressDuplicate = true;
}
return value;
}
public Object visitReportItem( ReportItemDesign item, Object value )
{
PolicyNode node = new PolicyNode( );
node.parent = parentNode;
node.design = item;
boolean needExecute = value == Boolean.TRUE;
// first test if we need execute the previous object
if ( needExecute )
{
node.execute = true;
}
setupPageBreak( node );
parentNode.children.add( node );
currentNode = node;
return Boolean.valueOf( needExecute );
}
protected void setupPageBreak( PolicyNode node )
{
ReportItemDesign item = node.design;
// test if it changes the pagination
String styleClass = item.getStyleName( );
if ( styleClass != null )
{
IStyle style = report.findStyle( styleClass );
CSSValue masterPage = style
.getProperty( IStyle.STYLE_MASTER_PAGE );
CSSValue pageBreakBefore = style
.getProperty( IStyle.STYLE_PAGE_BREAK_BEFORE );
CSSValue pageBreakAfter = style
.getProperty( IStyle.STYLE_PAGE_BREAK_AFTER );
if ( masterPage != null || (pageBreakBefore != null) && !pageBreakBefore.equals( IStyle.AUTO_VALUE ) )
{
node.breakBefore = true;
node.execute = true;
}
if ( pageBreakAfter != null && !pageBreakAfter.equals( IStyle.AUTO_VALUE ))
{
node.breakAfter = true;
node.execute = true;
}
}
// if the item has scripts, it must be executed
if ( item.getJavaClass( ) != null || item.getOnCreate( ) != null
|| item.getOnPageBreak( ) != null )
{
node.breakBefore = true;
node.breakAfter = true;
node.execute = true;
//since table script can access column, so page-break on columns can be changed.
if(item instanceof TableItemDesign)
{
node.executeAll = true;
}
}
if ( node.breakBefore || node.breakAfter )
{
Iterator iter = rows.iterator( );
while ( iter.hasNext( ) )
{
PolicyNode row = (PolicyNode) iter.next( );
row.executeAll = true;
}
return;
}
// if it has map or highlight, it must be executed
if ( item.getHighlight( ) != null || item.getMap( ) != null )
{
node.execute = true;
}
// if it has TOC/book mark/hyper link, it must be executed
if ( item.getTOC( ) != null || item.getBookmark( ) != null
|| item.getAction( ) != null )
{
node.execute = true;
}
// if it has queries, it must be executed
if ( item.getQueries( ) != null )
{
node.execute = true;
}
// if it has page-break, it must be executed
if ( item.getVisibility( ) != null )
{
node.execute = true;
}
}
}
}
|
package com.feenk.jdt2famix.injava.multipleSamples;
import java.nio.file.Paths;
import org.junit.Before;
import com.feenk.jdt2famix.JavaFiles;
import com.feenk.jdt2famix.injava.InJavaImporter;
import com.feenk.jdt2famix.injava.InJavaTestCase;
public abstract class MultipleSamplesTestCase extends InJavaTestCase {
@Before
public void before() {
importer = new InJavaImporter();
JavaFiles javaFiles = new JavaFiles();
this.sampleClassesIn(javaFiles);
importer.run(javaFiles);
setUp();
}
protected void setUp() {
// override this one if you need custom set up
}
protected abstract void sampleClassesIn(JavaFiles javaFiles);
protected String fileNameFor(Class<?> clazz) {
return basicSamplesPath() + "/" + clazz.getSimpleName() + ".java";
}
protected String basicSamplesPath() {
String relativePath = "src/test/java/org/moosetechnology/jdt2famix/samples/basic/";
return Paths.get(relativePath).toAbsolutePath().normalize().toString();
}
}
|
package org.ambraproject.rhino.service.impl;
import com.google.common.collect.ImmutableList;
import org.ambraproject.rhino.config.RuntimeConfiguration;
import org.ambraproject.rhino.identity.ArticleRevisionIdentifier;
import org.ambraproject.rhino.model.Journal;
import org.ambraproject.rhino.model.Syndication;
import org.ambraproject.rhino.service.ArticleCrudService;
import org.ambraproject.rhino.service.JournalCrudService;
import org.ambraproject.rhino.service.MessageSender;
import org.ambraproject.rhino.service.SyndicationCrudService;
import org.mockito.internal.stubbing.answers.Returns;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ContextConfiguration(classes = SyndicationCrudServiceImplTest.class)
@Configuration
public class SyndicationCrudServiceImplTest extends AbstractStubbingArticleTest {
private SyndicationCrudService mockSyndicationCrudService;
private MessageSender mockMessageSender;
private RuntimeConfiguration mockRuntimeConfiguration;
private JournalCrudService mockJournalCrudService;
private ArticleCrudService mockArticleCrudService;
private HibernateTemplate mockHibernateTemplate;
private List<Syndication> stubSyndications = ImmutableList.of(createStubSyndication());
private final ArticleRevisionIdentifier stubRevisionId = ArticleRevisionIdentifier.create("0", 1);
@Bean
public SyndicationCrudService syndicationCrudService() {
mockSyndicationCrudService = spy(SyndicationCrudServiceImpl.class);
LOG.debug("syndicationCrudService() * --> {}", mockSyndicationCrudService);
return mockSyndicationCrudService;
}
@Bean
public MessageSender messageSender() {
mockMessageSender = mock(MessageSender.class);
LOG.debug("messageSenderCrudService() * --> {}", mockMessageSender);
return mockMessageSender;
}
private Syndication createStubSyndication() {
return new Syndication(createStubArticleRevision(), "test");
}
@BeforeMethod
public void initMocks() throws IllegalAccessException, NoSuchFieldException {
mockSyndicationCrudService = applicationContext.getBean(SyndicationCrudService.class);
mockArticleCrudService = applicationContext.getBean(ArticleCrudService.class);
mockRuntimeConfiguration = applicationContext.getBean(RuntimeConfiguration.class);
mockJournalCrudService = applicationContext.getBean(JournalCrudService.class);
mockHibernateTemplate = applicationContext.getBean(HibernateTemplate.class);
mockMessageSender = applicationContext.getBean(MessageSender.class);
}
@Test
public void testGetSyndication() throws Exception {
when(mockArticleCrudService.readRevision(stubRevisionId)).thenReturn(createStubArticleRevision());
when(mockHibernateTemplate.execute(any())).thenReturn(createStubSyndication());
mockSyndicationCrudService.getSyndication(stubRevisionId, "test");
}
@Test
public void testGetSyndications() throws Exception {
when(mockArticleCrudService.readRevision(stubRevisionId)).thenReturn(createStubArticleRevision());
when(mockHibernateTemplate.execute(any())).thenAnswer(new Returns(stubSyndications));
mockSyndicationCrudService.getSyndications(stubRevisionId);
}
@Test
public void testUpdateSyndication() throws Exception {
when(mockArticleCrudService.readRevision(stubRevisionId)).thenReturn(createStubArticleRevision());
when(mockHibernateTemplate.execute(any())).thenReturn(createStubSyndication());
mockSyndicationCrudService.updateSyndication(stubRevisionId, "test", "test", "test");
verify(mockHibernateTemplate).update(any(Syndication.class));
}
@Test
public void testCreateSyndication() throws Exception {
when(mockArticleCrudService.readRevision(stubRevisionId)).thenReturn(createStubArticleRevision());
mockSyndicationCrudService.createSyndication(stubRevisionId, "test");
verify(mockHibernateTemplate).save(any(Syndication.class));
}
@Test
public void testReadSyndications() throws Exception {
when(mockRuntimeConfiguration.getQueueConfiguration()).thenReturn(stubConfig);
when(mockJournalCrudService.readJournal("test")).thenReturn(new Journal("test"));
when(mockHibernateTemplate.execute(any())).thenAnswer(new Returns(stubSyndications));
mockSyndicationCrudService.readSyndications("test", ImmutableList.of("test"));
}
@Test
@DirtiesContext
public void testSyndicateExistingSyndication() throws Exception {
when(mockArticleCrudService.readRevision(stubRevisionId)).thenReturn(createStubArticleRevision());
when(mockHibernateTemplate.execute(any())).thenReturn(createStubSyndication());
mockSyndicationCrudService.syndicate(stubRevisionId, "test");
verify(mockHibernateTemplate).update(any(Syndication.class));
verify(mockMessageSender).sendBody(any(String.class), any(String.class));
}
@Test
@DirtiesContext
public void testSyndicateNoSyndication() throws Exception {
when(mockArticleCrudService.readRevision(stubRevisionId)).thenReturn(createStubArticleRevision());
when(mockHibernateTemplate.execute(any())).thenReturn(null);
mockSyndicationCrudService.syndicate(stubRevisionId, "test");
verify(mockHibernateTemplate).save(any(Syndication.class));
verify(mockMessageSender).sendBody(any(String.class), any(String.class));
}
private final RuntimeConfiguration.QueueConfiguration stubConfig = new RuntimeConfiguration.QueueConfiguration() {
@Override
public String getBrokerUrl() {
return "test";
}
@Override
public String getSolrUpdate() {
return "test";
}
@Override
public String getLiteSolrUpdate() {
return "test";
}
@Override
public String getSolrDelete() {
return "test";
}
@Override
public int getSyndicationRange() {
return 0;
}
};
}
|
package org.innovateuk.ifs.workflow.audit;
import org.innovateuk.ifs.commons.security.NotSecured;
import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.workflow.domain.Process;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PreUpdate;
/**
* {@code EntityListener} to create new {@link ProcessHistory}s whenever a {@link Process} is updated.
*/
@Service
@Transactional
@SecuredBySpring(value = "TODO", description = "TODO")
public class ProcessHistoryEntityListener {
private static ProcessHistoryRepository processHistoryRepository;
private static ProcessHistoryRepository getProcessHistoryRepository() {
if (ProcessHistoryEntityListener.processHistoryRepository == null) {
throw new IllegalStateException("processHistoryRepository not autowired in ProcessEntityListener");
}
return ProcessHistoryEntityListener.processHistoryRepository;
}
@Autowired
@NotSecured("not secured")
public void setProcessHistoryRepository(ProcessHistoryRepository processHistoryRepository) {
ProcessHistoryEntityListener.processHistoryRepository = processHistoryRepository;
}
@PreUpdate
@NotSecured("not secured")
public void preUpdate(Process process) {
getProcessHistoryRepository().save(new ProcessHistory(process));
}
}
|
package com.yahoo.jdisc.http.filter.security.base;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.handler.FastContentWriter;
import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
import com.yahoo.log.LogLevel;
import java.io.UncheckedIOException;
import java.util.Optional;
import java.util.logging.Logger;
/**
* A base class for {@link SecurityRequestFilter} implementations that renders an error response as JSON.
*
* @author bjorncs
*/
public abstract class JsonSecurityRequestFilterBase implements SecurityRequestFilter {
private static final Logger log = Logger.getLogger(JsonSecurityRequestFilterBase.class.getName());
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public final void filter(DiscFilterRequest request, ResponseHandler handler) {
filter(request)
.ifPresent(errorResponse -> writeResponse(request, errorResponse, handler));
}
protected abstract Optional<ErrorResponse> filter(DiscFilterRequest request);
private void writeResponse(DiscFilterRequest request, ErrorResponse error, ResponseHandler responseHandler) {
ObjectNode errorMessage = mapper.createObjectNode();
errorMessage.put("code", error.errorCode);
errorMessage.put("message", error.message);
error.response.headers().put("Content-Type", "application/json"); // Note: Overwrites header if already exists
error.response.headers().put("Cache-Control", "must-revalidate,no-cache,no-store");
log.log(LogLevel.DEBUG, () -> String.format("Error response for '%s': statusCode=%d, errorCode=%d, message='%s'",
request, error.response.getStatus(), error.errorCode, error.message));
try (FastContentWriter writer = ResponseDispatch.newInstance(error.response).connectFastWriter(responseHandler)) {
writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorMessage));
} catch (JsonProcessingException e) {
throw new UncheckedIOException(e);
}
}
/**
* An error response that contains a {@link Response}, error code and message.
* The error code and message will be rendered as JSON fields with name 'code' and 'message' respectively.
*/
protected static class ErrorResponse {
private final Response response;
private final int errorCode;
private final String message;
public ErrorResponse(Response response, int errorCode, String message) {
this.response = response;
this.errorCode = errorCode;
this.message = message;
}
public ErrorResponse(Response response, String message) {
this(response, response.getStatus(), message);
}
public ErrorResponse(int httpStatusCode, int errorCode, String message) {
this(new Response(httpStatusCode), errorCode, message);
}
public ErrorResponse(int httpStatusCode, String message) {
this(new Response(httpStatusCode), message);
}
public Response getResponse() {
return response;
}
public int getErrorCode() {
return errorCode;
}
public String getMessage() {
return message;
}
}
}
|
package org.eclipse.jetty.spdy.server.http;
import java.util.EnumSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.DispatcherType;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.GzipFilter;
import org.eclipse.jetty.spdy.api.DataInfo;
import org.eclipse.jetty.spdy.api.ReplyInfo;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.Stream;
import org.eclipse.jetty.spdy.api.StreamFrameListener;
import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class WriteThroughAggregateBufferTest extends AbstractHTTPSPDYTest
{
private static final Logger LOG = Log.getLogger(WriteThroughAggregateBufferTest.class);
public WriteThroughAggregateBufferTest(short version)
{
super(version);
}
/**
* This test was created due to bugzilla #409403. It tests a specific code path through DefaultServlet leading to
* every byte of the response being sent one by one through BufferUtil.writeTo(). To do this,
* we need to use DefaultServlet + ResourceCache + GzipFilter. As this bug only affected SPDY,
* we test using SPDY. The accept-encoding header must not be set to replicate this issue.
* @throws Exception
*/
@Test
public void testGetBigJavaScript() throws Exception
{
final CountDownLatch replyLatch = new CountDownLatch(1);
final CountDownLatch dataLatch = new CountDownLatch(1);
ServletContextHandler contextHandler = new ServletContextHandler(getServer(), "/ctx");
FilterHolder gzipFilterHolder = new FilterHolder(GzipFilter.class);
|
package com.matthewtamlin.spyglass.library.default_annotations;
import com.matthewtamlin.java_utilities.testing.Tested;
import com.matthewtamlin.spyglass.library.default_adapters.DefaultToColorStateListResourceAdapter;
import com.matthewtamlin.spyglass.library.meta_annotations.Default;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Declares a default value to the Spyglass framework. This annotation should only be applied to
* methods which accept an integer array and have a handler annotation, and it should not be
* used in conjunction with other defaults.
*/
@Tested(testMethod = "automated")
@Default(adapterClass = DefaultToColorStateListResourceAdapter.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DefaultToColorStateListResource {
/**
* @return the resource ID of the default value, must resolve to a color state list resource
*/
int value();
}
|
package io.subutai.core.localpeer.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.karaf.bundle.core.BundleState;
import org.apache.karaf.bundle.core.BundleStateService;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.subutai.common.command.CommandCallback;
import io.subutai.common.command.CommandException;
import io.subutai.common.command.CommandResult;
import io.subutai.common.command.CommandUtil;
import io.subutai.common.command.RequestBuilder;
import io.subutai.common.dao.DaoManager;
import io.subutai.common.environment.CloneContainerTask;
import io.subutai.common.environment.Containers;
import io.subutai.common.environment.CreateEnvironmentContainersRequest;
import io.subutai.common.environment.CreateEnvironmentContainersResponse;
import io.subutai.common.environment.HostAddresses;
import io.subutai.common.environment.Node;
import io.subutai.common.environment.Nodes;
import io.subutai.common.environment.PeerTemplatesDownloadProgress;
import io.subutai.common.environment.PrepareTemplatesRequest;
import io.subutai.common.environment.PrepareTemplatesResponse;
import io.subutai.common.environment.RhP2pIp;
import io.subutai.common.environment.RhTemplatesDownloadProgress;
import io.subutai.common.exception.DaoException;
import io.subutai.common.host.ContainerHostInfo;
import io.subutai.common.host.ContainerHostInfoModel;
import io.subutai.common.host.ContainerHostState;
import io.subutai.common.host.HostId;
import io.subutai.common.host.HostInfo;
import io.subutai.common.host.HostInterfaceModel;
import io.subutai.common.host.HostInterfaces;
import io.subutai.common.host.ResourceHostInfo;
import io.subutai.common.metric.HistoricalMetrics;
import io.subutai.common.metric.QuotaAlertValue;
import io.subutai.common.metric.ResourceHostMetric;
import io.subutai.common.metric.ResourceHostMetrics;
import io.subutai.common.network.NetworkResource;
import io.subutai.common.network.NetworkResourceImpl;
import io.subutai.common.network.ProxyLoadBalanceStrategy;
import io.subutai.common.network.ReservedNetworkResources;
import io.subutai.common.network.SshTunnel;
import io.subutai.common.network.UsedNetworkResources;
import io.subutai.common.peer.AlertEvent;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.ContainerId;
import io.subutai.common.peer.EnvironmentId;
import io.subutai.common.peer.Host;
import io.subutai.common.peer.HostNotFoundException;
import io.subutai.common.peer.LocalPeer;
import io.subutai.common.peer.LocalPeerEventListener;
import io.subutai.common.peer.Payload;
import io.subutai.common.peer.PeerException;
import io.subutai.common.peer.PeerId;
import io.subutai.common.peer.PeerInfo;
import io.subutai.common.peer.PeerPolicy;
import io.subutai.common.peer.RegistrationStatus;
import io.subutai.common.peer.RequestListener;
import io.subutai.common.peer.ResourceHost;
import io.subutai.common.peer.ResourceHostException;
import io.subutai.common.protocol.CustomProxyConfig;
import io.subutai.common.protocol.Disposable;
import io.subutai.common.protocol.P2PConfig;
import io.subutai.common.protocol.P2PCredentials;
import io.subutai.common.protocol.P2pIps;
import io.subutai.common.protocol.Template;
import io.subutai.common.security.PublicKeyContainer;
import io.subutai.common.security.SshEncryptionType;
import io.subutai.common.security.SshKey;
import io.subutai.common.security.SshKeys;
import io.subutai.common.security.crypto.pgp.KeyPair;
import io.subutai.common.security.crypto.pgp.PGPKeyUtil;
import io.subutai.common.security.objects.KeyTrustLevel;
import io.subutai.common.security.objects.Ownership;
import io.subutai.common.security.objects.PermissionObject;
import io.subutai.common.security.objects.SecurityKeyType;
import io.subutai.common.security.objects.UserType;
import io.subutai.common.security.relation.RelationLink;
import io.subutai.common.security.relation.RelationLinkDto;
import io.subutai.common.security.relation.RelationManager;
import io.subutai.common.security.relation.model.Relation;
import io.subutai.common.security.relation.model.RelationInfoMeta;
import io.subutai.common.security.relation.model.RelationMeta;
import io.subutai.common.security.relation.model.RelationStatus;
import io.subutai.common.settings.Common;
import io.subutai.common.task.CloneRequest;
import io.subutai.common.util.CollectionUtil;
import io.subutai.common.util.ExceptionUtil;
import io.subutai.common.util.HostUtil;
import io.subutai.common.util.P2PUtil;
import io.subutai.common.util.ServiceLocator;
import io.subutai.common.util.StringUtil;
import io.subutai.common.util.TaskUtil;
import io.subutai.common.util.UnitUtil;
import io.subutai.core.executor.api.CommandExecutor;
import io.subutai.core.hostregistry.api.HostDisconnectedException;
import io.subutai.core.hostregistry.api.HostListener;
import io.subutai.core.hostregistry.api.HostRegistry;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.localpeer.impl.binding.BatchOutput;
import io.subutai.core.localpeer.impl.binding.Commands;
import io.subutai.core.localpeer.impl.binding.QuotaOutput;
import io.subutai.core.localpeer.impl.command.CommandRequestListener;
import io.subutai.core.localpeer.impl.container.CreateEnvironmentContainersRequestListener;
import io.subutai.core.localpeer.impl.container.ImportTemplateTask;
import io.subutai.core.localpeer.impl.container.PrepareTemplateRequestListener;
import io.subutai.core.localpeer.impl.dao.NetworkResourceDaoImpl;
import io.subutai.core.localpeer.impl.dao.ResourceHostDataService;
import io.subutai.core.localpeer.impl.entity.AbstractSubutaiHost;
import io.subutai.core.localpeer.impl.entity.ContainerHostEntity;
import io.subutai.core.localpeer.impl.entity.NetworkResourceEntity;
import io.subutai.core.localpeer.impl.entity.ResourceHostEntity;
import io.subutai.core.localpeer.impl.tasks.CleanupEnvironmentTask;
import io.subutai.core.localpeer.impl.tasks.DeleteTunnelsTask;
import io.subutai.core.localpeer.impl.tasks.JoinP2PSwarmTask;
import io.subutai.core.localpeer.impl.tasks.ResetP2PSwarmSecretTask;
import io.subutai.core.localpeer.impl.tasks.SetupTunnelsTask;
import io.subutai.core.localpeer.impl.tasks.UsedHostNetResourcesTask;
import io.subutai.core.metric.api.Monitor;
import io.subutai.core.network.api.NetworkManager;
import io.subutai.core.network.api.NetworkManagerException;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.core.registration.api.HostRegistrationManager;
import io.subutai.core.security.api.SecurityManager;
import io.subutai.core.security.api.crypto.EncryptionTool;
import io.subutai.core.security.api.crypto.KeyManager;
import io.subutai.core.template.api.TemplateManager;
import io.subutai.hub.share.dto.metrics.HostMetricsDto;
import io.subutai.hub.share.parser.CommonResourceValueParser;
import io.subutai.hub.share.quota.ContainerCpuResource;
import io.subutai.hub.share.quota.ContainerDiskResource;
import io.subutai.hub.share.quota.ContainerQuota;
import io.subutai.hub.share.quota.ContainerRamResource;
import io.subutai.hub.share.quota.ContainerResource;
import io.subutai.hub.share.quota.ContainerResourceFactory;
import io.subutai.hub.share.quota.ContainerSize;
import io.subutai.hub.share.quota.Quota;
import io.subutai.hub.share.quota.QuotaException;
import io.subutai.hub.share.resource.ByteUnit;
import io.subutai.hub.share.resource.ContainerResourceType;
import io.subutai.hub.share.resource.CpuResource;
import io.subutai.hub.share.resource.DiskResource;
import io.subutai.hub.share.resource.HostResources;
import io.subutai.hub.share.resource.PeerResources;
import io.subutai.hub.share.resource.RamResource;
import io.subutai.hub.share.resource.ResourceValue;
/**
* Local peer implementation
*
* TODO add proper security annotations
*/
@PermitAll
public class LocalPeerImpl implements LocalPeer, HostListener, Disposable
{
private static final int BUNDLE_COUNT = 278;
private static final Logger LOG = LoggerFactory.getLogger( LocalPeerImpl.class );
private static final BigDecimal ONE_HUNDRED = new BigDecimal( "100.00" );
private static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;
private transient DaoManager daoManager;
private transient TemplateManager templateManager;
transient Set<ResourceHost> resourceHosts = Sets.newConcurrentHashSet();
private transient CommandExecutor commandExecutor;
private transient Monitor monitor;
transient ResourceHostDataService resourceHostDataService;
private transient HostRegistry hostRegistry;
transient CommandUtil commandUtil = new CommandUtil();
transient ExceptionUtil exceptionUtil = new ExceptionUtil();
transient Set<RequestListener> requestListeners = Sets.newHashSet();
private transient SecurityManager securityManager;
transient ServiceLocator serviceLocator = new ServiceLocator();
private transient IdentityManager identityManager;
private transient RelationManager relationManager;
private transient NetworkResourceDaoImpl networkResourceDao;
private transient final LocalPeerCommands localPeerCommands = new LocalPeerCommands();
private transient final HostUtil hostUtil = new HostUtil();
private ObjectMapper mapper = new ObjectMapper();
volatile boolean initialized = false;
PeerInfo peerInfo;
private transient ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor();
private transient ExecutorService threadPool = Executors.newCachedThreadPool();
private transient Set<LocalPeerEventListener> peerEventListeners = Sets.newHashSet();
private AtomicInteger containerCreationCounter = new AtomicInteger();
public LocalPeerImpl( DaoManager daoManager, TemplateManager templateManager, CommandExecutor commandExecutor,
HostRegistry hostRegistry, Monitor monitor, SecurityManager securityManager )
{
this.daoManager = daoManager;
this.templateManager = templateManager;
this.monitor = monitor;
this.commandExecutor = commandExecutor;
this.hostRegistry = hostRegistry;
this.securityManager = securityManager;
}
public void setIdentityManager( final IdentityManager identityManager )
{
this.identityManager = identityManager;
}
public void setRelationManager( final RelationManager relationManager )
{
this.relationManager = relationManager;
}
public void init()
{
LOG.debug( "********************************************** Initializing peer "
+ "******************************************" );
try
{
initPeerInfo();
//add command request listener
addRequestListener( new CommandRequestListener() );
//add command response listener
//add create container requests listener
addRequestListener( new CreateEnvironmentContainersRequestListener( this ) );
//add prepare templates listener
addRequestListener( new PrepareTemplateRequestListener( this ) );
resourceHostDataService = createResourceHostDataService();
resourceHosts.clear();
resourceHosts.addAll( resourceHostDataService.getAll() );
setResourceHostTransientFields( getResourceHosts() );
this.networkResourceDao = new NetworkResourceDaoImpl( daoManager.getEntityManagerFactory() );
cleaner.scheduleWithFixedDelay( new Runnable()
{
@Override
public void run()
{
removeStaleContainers();
}
}, TimeUnit.MINUTES.toSeconds( 3L ), HostRegistry.HOST_EXPIRATION_SEC * 2L, TimeUnit.SECONDS );
}
catch ( Exception e )
{
LOG.error( e.getMessage(), e );
throw new LocalPeerInitializationError( "Failed to init Local Peer", e );
}
initialized = true;
}
@Override
public boolean isInitialized()
{
return initialized;
}
@Override
public boolean isMHPresent()
{
try
{
ResourceHost mh = getManagementHost();
return mh.isConnected();
}
catch ( HostNotFoundException ignore )
{
return false;
}
}
private void initPeerInfo()
{
peerInfo = new PeerInfo();
peerInfo.setId( securityManager.getKeyManager().getPeerId() );
peerInfo.setOwnerId( securityManager.getKeyManager().getPeerOwnerId() );
peerInfo.setPublicUrl( Common.DEFAULT_PUBLIC_URL );
peerInfo.setPublicSecurePort( Common.DEFAULT_PUBLIC_SECURE_PORT );
peerInfo.setName( "Local Peer" );
}
@Override
public PeerInfo getPeerInfo()
{
return peerInfo;
}
@Override
public void setPeerInfo( final PeerInfo peerInfo )
{
this.peerInfo = peerInfo;
}
ResourceHostDataService createResourceHostDataService()
{
return new ResourceHostDataService( daoManager.getEntityManagerFactory() );
}
@Override
public void dispose()
{
for ( ResourceHost resourceHost : getResourceHosts() )
{
( ( Disposable ) resourceHost ).dispose();
}
hostUtil.dispose();
commandUtil.dispose();
}
private void setResourceHostTransientFields( Set<ResourceHost> resourceHosts )
{
for ( ResourceHost resourceHost : resourceHosts )
{
( ( AbstractSubutaiHost ) resourceHost ).setPeer( this );
}
}
@Override
public String getId()
{
return peerInfo.getId();
}
@Override
public String getName()
{
return peerInfo.getName();
}
@Override
public String getOwnerId()
{
return peerInfo.getOwnerId();
}
@Override
public ContainerHostState getContainerState( final ContainerId containerId ) throws PeerException
{
Preconditions.checkNotNull( containerId );
try
{
ContainerHostInfo containerHostInfo =
( ContainerHostInfo ) hostRegistry.getHostInfoById( containerId.getId() );
return containerHostInfo.getState();
}
catch ( Exception e )
{
LOG.error( e.getMessage() );
throw new PeerException( String.format( "Error getting container state: %s", e.getMessage() ), e );
}
}
@Override
public io.subutai.common.host.Quota getRawQuota( final ContainerId containerId ) throws PeerException
{
Preconditions.checkNotNull( containerId );
try
{
ContainerHostInfo containerHostInfo =
( ContainerHostInfo ) hostRegistry.getHostInfoById( containerId.getId() );
return containerHostInfo.getRawQuota();
}
catch ( Exception e )
{
LOG.error( e.getMessage() );
throw new PeerException( String.format( "Error getting container quota: %s", e.getMessage() ), e );
}
}
@Override
public Containers getEnvironmentContainers( final EnvironmentId environmentId ) throws PeerException
{
Preconditions.checkNotNull( environmentId );
Containers result = new Containers();
try
{
Set<ContainerHost> containers = findContainersByEnvironmentId( environmentId.getId() );
for ( ContainerHost c : containers )
{
ContainerHostInfo info;
try
{
info = hostRegistry.getContainerHostInfoById( c.getId() );
}
catch ( HostDisconnectedException e )
{
info = new ContainerHostInfoModel( c );
}
result.addContainer( info );
}
return result;
}
catch ( Exception e )
{
LOG.error( e.getMessage() );
throw new PeerException( String.format( "Error getting environment containers: %s", e.getMessage() ), e );
}
}
@Override
public void configureHostsInEnvironment( final EnvironmentId environmentId, final HostAddresses hostAddresses )
throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkNotNull( hostAddresses, "Invalid HostAdresses" );
Preconditions.checkArgument( !hostAddresses.isEmpty(), "No host addresses" );
Set<Host> hosts = Sets.newHashSet();
hosts.addAll( findContainersByEnvironmentId( environmentId.getId() ) );
if ( hosts.isEmpty() )
{
return;
}
CommandUtil.HostCommandResults results = commandUtil
.executeFailFast( localPeerCommands.getAddIpHostToEtcHostsCommand( hostAddresses.getHostAddresses() ),
hosts, environmentId.getId() );
for ( CommandUtil.HostCommandResult result : results.getCommandResults() )
{
if ( !result.hasSucceeded() )
{
LOG.error( "Host registration failed on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
}
if ( results.hasFailures() )
{
throw new PeerException( "Failed to register hosts on each host" );
}
}
@Override
public SshKeys readOrCreateSshKeysForEnvironment( final EnvironmentId environmentId,
final SshEncryptionType sshKeyType ) throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkNotNull( sshKeyType, "Ssh key type is null" );
SshKeys sshPublicKeys = new SshKeys();
Set<Host> hosts = Sets.newHashSet();
hosts.addAll( findContainersByEnvironmentId( environmentId.getId() ) );
if ( hosts.isEmpty() )
{
return sshPublicKeys;
}
CommandUtil.HostCommandResults readResults = commandUtil
.executeFailFast( localPeerCommands.getReadOrCreateSSHCommand( sshKeyType ), hosts,
environmentId.getId() );
Set<Host> succeededHosts = Sets.newHashSet();
Set<Host> failedHosts = Sets.newHashSet( hosts );
for ( CommandUtil.HostCommandResult result : readResults.getCommandResults() )
{
if ( result.hasSucceeded() && !Strings.isNullOrEmpty( result.getCommandResult().getStdOut() ) )
{
sshPublicKeys.addKey( new SshKey( result.getHost().getId(), sshKeyType,
result.getCommandResult().getStdOut().trim() ) );
succeededHosts.add( result.getHost() );
}
else
{
LOG.error( "Failed to generate ssh key on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
}
failedHosts.removeAll( succeededHosts );
if ( !failedHosts.isEmpty() )
{
throw new PeerException( "Failed to generate ssh keys on each host" );
}
return sshPublicKeys;
}
@Override
public void configureSshInEnvironment( final EnvironmentId environmentId, final SshKeys sshKeys )
throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkNotNull( sshKeys, "SshPublicKey is null" );
Preconditions.checkArgument( !sshKeys.isEmpty(), "No ssh keys" );
Set<Host> hosts = Sets.newHashSet();
hosts.addAll( findContainersByEnvironmentId( environmentId.getId() ) );
if ( hosts.isEmpty() )
{
return;
}
//add keys in portions, since all can not fit into one command, it fails
int portionSize = Common.MAX_KEYS_IN_ECHO_CMD;
int i = 0;
StringBuilder keysString = new StringBuilder();
Set<SshKey> keys = sshKeys.getKeys();
for ( SshKey key : keys )
{
keysString.append( key.getPublicKey() ).append( System.lineSeparator() );
i++;
//send next portion of keys
if ( i % portionSize == 0 || i == keys.size() )
{
CommandUtil.HostCommandResults appendResults = commandUtil
.executeFailFast( localPeerCommands.getAppendSshKeysCommand( keysString.toString() ), hosts,
environmentId.getId() );
keysString.setLength( 0 );
for ( CommandUtil.HostCommandResult result : appendResults.getCommandResults() )
{
if ( !result.hasSucceeded() )
{
LOG.error( "Failed to add ssh keys on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
}
if ( appendResults.hasFailures() )
{
throw new PeerException( "Failed to add ssh keys on each host" );
}
}
}
//config ssh
CommandUtil.HostCommandResults configResults =
commandUtil.executeFailFast( localPeerCommands.getConfigSSHCommand(), hosts, environmentId.getId() );
for ( CommandUtil.HostCommandResult result : configResults.getCommandResults() )
{
if ( !result.hasSucceeded() )
{
LOG.error( "Failed to configure ssh on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
}
if ( configResults.hasFailures() )
{
throw new PeerException( "Failed to configure ssh on each host" );
}
}
@Override
public SshKeys getSshKeys( final EnvironmentId environmentId, final SshEncryptionType sshEncryptionType )
throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkNotNull( sshEncryptionType, "SSH encryption type is null" );
Set<Host> hosts = Sets.newHashSet();
hosts.addAll( findContainersByEnvironmentId( environmentId.getId() ) );
SshKeys sshKeys = new SshKeys();
if ( hosts.isEmpty() )
{
return sshKeys;
}
CommandUtil.HostCommandResults results = commandUtil
.execute( localPeerCommands.getReadSSHKeyCommand( sshEncryptionType ), hosts, environmentId.getId() );
for ( CommandUtil.HostCommandResult result : results.getCommandResults() )
{
if ( !result.hasSucceeded() )
{
LOG.warn( "SSH key read failed on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
else
{
sshKeys.addKey( new SshKey( result.getHost().getId(), sshEncryptionType,
result.getCommandResult().getStdOut().trim() ) );
}
}
return sshKeys;
}
@Override
public SshKeys getContainerAuthorizedKeys( final ContainerId containerId ) throws PeerException
{
Preconditions.checkNotNull( containerId, "Container id is null" );
ContainerHost containerHost = getContainerHostById( containerId.getId() );
try
{
CommandResult commandResult = execute( localPeerCommands.getReadAuthorizedKeysFile(), containerHost );
StringTokenizer tokenizer = new StringTokenizer( commandResult.getStdOut(), System.lineSeparator() );
SshKeys sshKeys = new SshKeys();
while ( tokenizer.hasMoreTokens() )
{
String sshKey = tokenizer.nextToken();
if ( !sshKey.trim().isEmpty() )
{
sshKeys.addKey(
new SshKey( containerId.getId(), SshEncryptionType.parseTypeFromKey( sshKey ), sshKey ) );
}
}
return sshKeys;
}
catch ( CommandException e )
{
throw new PeerException( "Error obtaining authorized keys", e );
}
}
@Override
public SshKey createSshKey( final EnvironmentId environmentId, final ContainerId containerId,
final SshEncryptionType sshEncryptionType ) throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkNotNull( containerId, "Container id is null" );
Preconditions.checkNotNull( sshEncryptionType, "SSH encryption type is null" );
try
{
ContainerHost containerHost = getContainerHostById( containerId.getId() );
if ( !containerHost.getEnvironmentId().equals( environmentId ) )
{
throw new HostNotFoundException( "Environment does not contains requested container." );
}
CommandResult commandResult = commandUtil
.execute( localPeerCommands.getReadOrCreateSSHCommand( sshEncryptionType ), containerHost );
if ( commandResult.hasSucceeded() )
{
return new SshKey( containerId.getId(), sshEncryptionType, commandResult.getStdOut().trim() );
}
else
{
throw new CommandException( "Command execution failed." );
}
}
catch ( Exception e )
{
throw new PeerException( "Error on creating ssh key." );
}
}
@Override
public void addToAuthorizedKeys( final EnvironmentId environmentId, final String sshPublicKey ) throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( sshPublicKey ), "Invalid ssh key" );
Set<Host> hosts = Sets.newHashSet();
hosts.addAll( findContainersByEnvironmentId( environmentId.getId() ) );
if ( hosts.isEmpty() )
{
return;
}
CommandUtil.HostCommandResults results = commandUtil
.executeFailFast( localPeerCommands.getAppendSshKeysCommand( sshPublicKey.trim() ), hosts,
environmentId.getId() );
for ( CommandUtil.HostCommandResult result : results.getCommandResults() )
{
if ( !result.hasSucceeded() )
{
LOG.error( "SSH key addition failed on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
}
if ( results.hasFailures() )
{
throw new PeerException( "Failed to add SSH key on each host" );
}
}
@Override
public void removeFromAuthorizedKeys( final EnvironmentId environmentId, final String sshPublicKey )
throws PeerException
{
Preconditions.checkNotNull( environmentId, "Environment id is null" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( sshPublicKey ), "Invalid ssh key" );
Set<Host> hosts = Sets.newHashSet();
hosts.addAll( findContainersByEnvironmentId( environmentId.getId() ) );
if ( hosts.isEmpty() )
{
return;
}
CommandUtil.HostCommandResults results = commandUtil
.executeFailFast( localPeerCommands.getRemoveSshKeyCommand( sshPublicKey ), hosts,
environmentId.getId() );
for ( CommandUtil.HostCommandResult result : results.getCommandResults() )
{
if ( !result.hasSucceeded() )
{
LOG.error( "SSH key removal failed on host {}: {}", result.getHost().getHostname(),
result.getFailureReason() );
}
}
if ( results.hasFailures() )
{
throw new PeerException( "Failed to remove SSH key on each host" );
}
}
@RolesAllowed( "Environment-Management|Write" )
@Override
public PrepareTemplatesResponse prepareTemplates( final PrepareTemplatesRequest request ) throws PeerException
{
PrepareTemplatesResponse response = new PrepareTemplatesResponse();
HostUtil.Tasks tasks = new HostUtil.Tasks();
for ( final String resourceHostId : request.getTemplates().keySet() )
{
final ResourceHost resourceHost = getResourceHostById( resourceHostId );
for ( final String templateId : request.getTemplates().get( resourceHostId ) )
{
Template template = templateManager.getTemplate( templateId, request.getKurjunToken() );
if ( template == null )
{
throw new PeerException( String.format( "Template `%s` not found.", templateId ) );
}
HostUtil.Task<Object> importTask =
new ImportTemplateTask( template, resourceHost, request.getEnvironmentId(),
request.getKurjunToken() );
tasks.addTask( resourceHost, importTask );
}
}
HostUtil.Results results = hostUtil.executeFailFast( tasks, request.getEnvironmentId() );
response.addResults( results );
return response;
}
@Override
public State getState()
{
boolean failed = false;
boolean ready = true;
BundleContext ctx = FrameworkUtil.getBundle( LocalPeerImpl.class ).getBundleContext();
BundleStateService bundleStateService = ServiceLocator.lookup( BundleStateService.class );
Bundle[] bundles = ctx.getBundles();
if ( bundles.length < BUNDLE_COUNT )
{
LOG.warn( "Bundle count is {}", bundles.length );
return State.LOADING;
}
for ( Bundle bundle : bundles )
{
if ( bundleStateService.getState( bundle ) == BundleState.Failure )
{
failed = true;
break;
}
if ( !( ( bundle.getState() == Bundle.ACTIVE ) || ( bundle.getState() == Bundle.RESOLVED ) ) )
{
ready = false;
break;
}
}
return failed ? State.FAILED : ready ? State.READY : State.LOADING;
}
//TODO add dateCreated to ContainerHostEntity
//when quota change is requested, check for the time passed since the dateCreated
//or since the last quota change
//must be at least 30 seconds otherwise throw an exception
@RolesAllowed( "Environment-Management|Read" )
@Override
public boolean canAccommodate( final Nodes nodes ) throws PeerException
{
Preconditions.checkArgument(
nodes != null && ( !CollectionUtil.isMapEmpty( nodes.getQuotas() ) || !CollectionUtil
.isCollectionEmpty( nodes.getNodes() ) ), "Invalid nodes" );
Map<ResourceHost, ResourceHostCapacity> requestedResources = Maps.newHashMap();
for ( ContainerHostInfo containerHostInfo : hostRegistry.getContainerHostsInfo() )
{
//use new quota instead of current if present
ContainerQuota newQuota = null;
if ( nodes.getQuotas() != null )
{
newQuota = nodes.getQuotas().get( containerHostInfo.getId() );
}
//use current quota as requested amount unless the container has a change of quota
//note: we use 0 for containers that have unset quota since we don't know what the effective limit is
double requestedRam = newQuota != null ? newQuota.getContainerSize().getRamQuota() :
containerHostInfo.getRawQuota() == null
|| containerHostInfo.getRawQuota().getRam() == null ? 0 :
UnitUtil.convert( containerHostInfo.getRawQuota().getRam(), UnitUtil.Unit.MB,
UnitUtil.Unit.B );
double requestedCpu = newQuota != null ? newQuota.getContainerSize().getCpuQuota() :
containerHostInfo.getRawQuota() == null
|| containerHostInfo.getRawQuota().getCpu() == null ? 0 :
containerHostInfo.getRawQuota().getCpu();
double requestedDisk = newQuota != null ? newQuota.getContainerSize().getDiskQuota() :
containerHostInfo.getRawQuota() == null
|| containerHostInfo.getRawQuota().getDisk() == null ? 0 :
UnitUtil.convert( containerHostInfo.getRawQuota().getDisk(), UnitUtil.Unit.GB,
UnitUtil.Unit.B );
//figure out current container resource consumption based on historical metrics
Calendar cal = Calendar.getInstance();
Date endTime = cal.getTime();
//1 hour interval is enough
cal.add( Calendar.MINUTE, -60 );
Date startTime = cal.getTime();
try
{
ContainerHost containerHost = getContainerHostById( containerHostInfo.getId() );
HistoricalMetrics historicalMetrics = monitor.getMetricsSeries( containerHost, startTime, endTime );
HostMetricsDto hostMetricsDto = historicalMetrics.getHostMetrics();
//skip partial metric, b/c this happens for new containers
if ( !HistoricalMetrics.isZeroMetric( hostMetricsDto ) )
{
double ramUsed = hostMetricsDto.getMemory().getCached() + hostMetricsDto.getMemory().getRss();
double cpuUsed = hostMetricsDto.getCpu().getSystem() + hostMetricsDto.getCpu().getUser();
double diskUsed = historicalMetrics.getContainerDiskUsed();
//subtract current consumption resource amount from the requested amount
if ( requestedRam > 0 )
{
requestedRam -= ramUsed;
}
if ( requestedCpu > 0 )
{
requestedCpu -= cpuUsed;
}
if ( requestedDisk > 0 )
{
requestedDisk -= diskUsed;
}
}
}
catch ( HostNotFoundException e )
{
//skip unregistered containers, b/c their quotas are not considered
}
ResourceHostInfo resourceHostInfo;
try
{
resourceHostInfo = hostRegistry.getResourceHostByContainerHost( containerHostInfo );
}
catch ( HostDisconnectedException e )
{
throw new PeerException( e );
}
ResourceHost resourceHost = getResourceHostById( resourceHostInfo.getId() );
ResourceHostCapacity resourceHostCapacity = requestedResources.get( resourceHost );
if ( resourceHostCapacity != null )
{
resourceHostCapacity.setRam( resourceHostCapacity.getRam() + requestedRam );
resourceHostCapacity.setDisk( resourceHostCapacity.getDisk() + requestedDisk );
resourceHostCapacity.setCpu( resourceHostCapacity.getCpu() + requestedCpu );
}
else
{
resourceHostCapacity = new ResourceHostCapacity( requestedRam, requestedDisk, requestedCpu );
}
requestedResources.put( resourceHost, resourceHostCapacity );
}
//new nodes
if ( nodes.getNodes() != null )
{
for ( Node node : nodes.getNodes() )
{
double requestedRam = node.getQuota().getContainerSize().getRamQuota();
double requestedDisk = node.getQuota().getContainerSize().getDiskQuota();
double requestedCpu = node.getQuota().getContainerSize().getCpuQuota();
ResourceHost resourceHost = getResourceHostById( node.getHostId() );
ResourceHostCapacity resourceHostCapacity = requestedResources.get( resourceHost );
if ( resourceHostCapacity != null )
{
resourceHostCapacity.setRam( resourceHostCapacity.getRam() + requestedRam );
resourceHostCapacity.setDisk( resourceHostCapacity.getDisk() + requestedDisk );
resourceHostCapacity.setCpu( resourceHostCapacity.getCpu() + requestedCpu );
}
else
{
resourceHostCapacity = new ResourceHostCapacity( requestedRam, requestedDisk, requestedCpu );
}
requestedResources.put( resourceHost, resourceHostCapacity );
}
}
Map<ResourceHost, ResourceHostCapacity> availableResources = Maps.newHashMap();
for ( ResourceHost resourceHost : getResourceHosts() )
{
ResourceHostMetric resourceHostMetric = monitor.getResourceHostMetric( resourceHost );
double availPeerRam = resourceHostMetric.getAvailableRam();
double availPeerDisk = resourceHostMetric.getAvailableSpace();
double availPeerCpu = resourceHostMetric.getCpuCore() * resourceHostMetric.getAvailableCpu();
availableResources
.put( resourceHost, new ResourceHostCapacity( availPeerRam, availPeerDisk, availPeerCpu ) );
}
boolean canAccommodate = true;
for ( Map.Entry<ResourceHost, ResourceHostCapacity> resourceEntry : requestedResources.entrySet() )
{
ResourceHost resourceHost = resourceEntry.getKey();
ResourceHostCapacity requestedCapacity = resourceEntry.getValue();
ResourceHostCapacity availableCapacity = availableResources.get( resourceHost );
if ( requestedCapacity.getRam() * ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam() )
{
LOG.warn( "Requested RAM volume {}MB can not be accommodated on RH {}: available RAM volume is {}MB",
UnitUtil.convert( requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB ),
resourceHost.getHostname(),
UnitUtil.convert( availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB ) );
canAccommodate = false;
}
if ( requestedCapacity.getDisk() * ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk() )
{
LOG.warn( "Requested DISK volume {}GB can not be accommodated on RH {}: available DISK volume is "
+ "{}GB", UnitUtil.convert( requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil
.Unit.GB ),
resourceHost.getHostname(),
UnitUtil.convert( availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB ) );
canAccommodate = false;
}
if ( requestedCapacity.getCpu() * ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu() )
{
LOG.warn( "Requested CPU {} can not be accommodated on RH {}: available CPU is {}",
resourceHost.getHostname(), requestedCapacity.getCpu(), availableCapacity.getCpu() );
canAccommodate = false;
}
}
return canAccommodate;
}
@RolesAllowed( "Environment-Management|Write" )
@Override
public CreateEnvironmentContainersResponse createEnvironmentContainers(
final CreateEnvironmentContainersRequest requestGroup ) throws PeerException
{
Preconditions.checkNotNull( requestGroup );
try
{
containerCreationCounter.incrementAndGet();
NetworkResource reservedNetworkResource =
getReservedNetworkResources().findByEnvironmentId( requestGroup.getEnvironmentId() );
if ( reservedNetworkResource == null )
{
throw new PeerException( String.format( "No reserved network resources found for environment %s",
requestGroup.getEnvironmentId() ) );
}
Set<String> namesToExclude = Sets.newHashSet();
for ( ContainerHostInfo containerHostInfo : getNotRegisteredContainers() )
{
namesToExclude.add( containerHostInfo.getContainerName().toLowerCase() );
}
//clone containers
HostUtil.Tasks cloneTasks = new HostUtil.Tasks();
for ( final CloneRequest request : requestGroup.getRequests() )
{
ResourceHost resourceHost = getResourceHostById( request.getResourceHostId() );
CloneContainerTask task =
new CloneContainerTask( request, templateManager.getTemplate( request.getTemplateId() ),
resourceHost, reservedNetworkResource, this, namesToExclude );
cloneTasks.addTask( resourceHost, task );
}
HostUtil.Results cloneResults = hostUtil.execute( cloneTasks, reservedNetworkResource.getEnvironmentId() );
//register succeeded containers
for ( HostUtil.Task cloneTask : cloneResults.getTasks().getTasks() )
{
CloneRequest request = ( ( CloneContainerTask ) cloneTask ).getRequest();
if ( cloneTask.getTaskState() == HostUtil.Task.TaskState.SUCCEEDED )
{
final HostInterfaces interfaces = new HostInterfaces();
interfaces.addHostInterface( new HostInterfaceModel( Common.DEFAULT_CONTAINER_INTERFACE,
request.getIp().split( "/" )[0] ) );
ContainerHostEntity containerHostEntity =
new ContainerHostEntity( getId(), ( ( CloneContainerTask ) cloneTask ).getResult(),
request.getHostname(), request.getTemplateArch(), interfaces,
request.getContainerName(), request.getTemplateId(),
requestGroup.getEnvironmentId(), requestGroup.getOwnerId(),
requestGroup.getInitiatorPeerId(), request.getContainerQuota() );
registerContainer( request.getResourceHostId(), containerHostEntity );
}
}
return new CreateEnvironmentContainersResponse( cloneResults );
}
finally
{
containerCreationCounter.decrementAndGet();
}
}
private boolean isContainerCreationInProgress()
{
return containerCreationCounter.get() > 0;
}
private void registerContainer( String resourceHostId, ContainerHostEntity containerHost ) throws PeerException
{
ResourceHost resourceHost = getResourceHostById( resourceHostId );
try
{
signContainerKeyWithPEK( containerHost.getId(), containerHost.getEnvironmentId() );
resourceHost.addContainerHost( containerHost );
resourceHostDataService.update( ( ResourceHostEntity ) resourceHost );
buildEnvContainerRelation( containerHost );
LOG.debug( "New container host registered: " + containerHost.getHostname() );
}
catch ( Exception e )
{
LOG.error( e.getMessage(), e );
throw new PeerException( String.format( "Error registering container: %s", e.getMessage() ), e );
}
}
private void signContainerKeyWithPEK( String containerId, EnvironmentId envId ) throws PeerException
{
String pairId = String.format( "%s_%s", getId(), envId.getId() );
final PGPSecretKeyRing pekSecKeyRing = securityManager.getKeyManager().getSecretKeyRing( pairId );
PGPPublicKeyRing containerPub = securityManager.getKeyManager().getPublicKeyRing( containerId );
PGPPublicKeyRing signedKey =
securityManager.getKeyManager().setKeyTrust( pekSecKeyRing, containerPub, KeyTrustLevel.FULL.getId() );
securityManager.getKeyManager().updatePublicKeyRing( signedKey );
}
@PermitAll
@Override
public Set<ContainerHost> findContainersByEnvironmentId( final String environmentId )
{
Preconditions.checkNotNull( environmentId, "Invalid environment id" );
Set<ContainerHost> result = new HashSet<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
result.addAll( resourceHost.getContainerHostsByEnvironmentId( environmentId ) );
}
return result;
}
@PermitAll
@Override
public ContainerHost getContainerHostByHostName( String hostname ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Container hostname shouldn't be null" );
for ( ResourceHost resourceHost : getResourceHosts() )
{
try
{
return resourceHost.getContainerHostByHostName( hostname );
}
catch ( HostNotFoundException ignore )
{
//ignore
}
}
throw new HostNotFoundException( String.format( "No container host found for hostname %s", hostname ) );
}
@PermitAll
@Override
public ContainerHost getContainerHostByContainerName( String containerName ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( containerName ), "Container name shouldn't be null" );
for ( ResourceHost resourceHost : getResourceHosts() )
{
try
{
return resourceHost.getContainerHostByContainerName( containerName );
}
catch ( HostNotFoundException ignore )
{
//ignore
}
}
throw new HostNotFoundException( String.format( "No container host found for name %s", containerName ) );
}
@PermitAll
@Override
public ContainerHost getContainerHostById( final String hostId ) throws HostNotFoundException
{
Preconditions.checkNotNull( hostId, "Invalid container host id" );
for ( ResourceHost resourceHost : getResourceHosts() )
{
try
{
return resourceHost.getContainerHostById( hostId );
}
catch ( HostNotFoundException e )
{
//ignore
}
}
throw new HostNotFoundException( String.format( "Container host not found by id %s", hostId ) );
}
@PermitAll
@Override
public ContainerHost getContainerHostByIp( final String hostIp ) throws HostNotFoundException
{
Preconditions.checkNotNull( hostIp, "Invalid container host ip" );
for ( ResourceHost resourceHost : getResourceHosts() )
{
try
{
return resourceHost.getContainerHostByIp( hostIp );
}
catch ( HostNotFoundException e )
{
//ignore
}
}
throw new HostNotFoundException( String.format( "Container host not found by ip %s", hostIp ) );
}
@PermitAll
@Override
public ResourceHost getResourceHostByHostName( String hostname ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid resource host hostname" );
for ( ResourceHost resourceHost : getResourceHosts() )
{
if ( resourceHost.getHostname().equalsIgnoreCase( hostname ) )
{
return resourceHost;
}
}
throw new HostNotFoundException( String.format( "Resource host not found by hostname %s", hostname ) );
}
@PermitAll
@Override
public ResourceHost getResourceHostById( final String hostId ) throws HostNotFoundException
{
Preconditions.checkNotNull( hostId, "Resource host id is null" );
for ( ResourceHost resourceHost : getResourceHosts() )
{
if ( resourceHost.getId().equals( hostId ) )
{
return resourceHost;
}
}
throw new HostNotFoundException( String.format( "Resource host not found by id %s", hostId ) );
}
@PermitAll
@Override
public ResourceHost getResourceHostByContainerHostName( final String hostname ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid container hostname" );
ContainerHost c = getContainerHostByHostName( hostname );
ContainerHostEntity containerHostEntity = ( ContainerHostEntity ) c;
return containerHostEntity.getParent();
}
@Override
public ResourceHost getResourceHostByContainerName( final String containerName ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( containerName ), "Invalid container name" );
ContainerHost c = getContainerHostByContainerName( containerName );
ContainerHostEntity containerHostEntity = ( ContainerHostEntity ) c;
return containerHostEntity.getParent();
}
@PermitAll
@Override
public ResourceHost getResourceHostByContainerId( final String hostId ) throws HostNotFoundException
{
Preconditions.checkNotNull( hostId, "Container host id is invalid" );
ContainerHost c = getContainerHostById( hostId );
ContainerHostEntity containerHostEntity = ( ContainerHostEntity ) c;
return containerHostEntity.getParent();
}
@Override
public Host findHost( String id ) throws HostNotFoundException
{
Preconditions.checkNotNull( id );
for ( ResourceHost resourceHost : getResourceHosts() )
{
if ( resourceHost.getId().equals( id ) )
{
return resourceHost;
}
else
{
try
{
return resourceHost.getContainerHostById( id );
}
catch ( HostNotFoundException ignore )
{
//ignore
}
}
}
throw new HostNotFoundException( String.format( "Host by id %s is not registered", id ) );
}
@Override
public Host findHostByName( final String hostname ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ) );
for ( ResourceHost resourceHost : getResourceHosts() )
{
if ( resourceHost.getHostname().equals( hostname ) )
{
return resourceHost;
}
for ( ContainerHost containerHost : resourceHost.getContainerHosts() )
{
if ( containerHost.getHostname().equals( hostname ) )
{
return containerHost;
}
}
}
throw new HostNotFoundException( "Host by name '" + hostname + "' is not registered." );
}
@RolesAllowed( "Environment-Management|Update" )
@Override
public void startContainer( final ContainerId containerId ) throws PeerException
{
Preconditions.checkNotNull( containerId, "Cannot operate on null container id" );
ContainerHostEntity containerHost = ( ContainerHostEntity ) getContainerHostById( containerId.getId() );
ResourceHost resourceHost = containerHost.getParent();
try
{
resourceHost.startContainerHost( containerHost );
}
catch ( Exception e )
{
String errMsg = String.format( "Could not start container %s: %s", containerHost.getContainerName(),
e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
@RolesAllowed( "Environment-Management|Update" )
@Override
public void stopContainer( final ContainerId containerId ) throws PeerException
{
Preconditions.checkNotNull( containerId, "Cannot operate on null container id" );
ContainerHostEntity containerHost = ( ContainerHostEntity ) getContainerHostById( containerId.getId() );
ResourceHost resourceHost = containerHost.getParent();
try
{
resourceHost.stopContainerHost( containerHost );
}
catch ( Exception e )
{
String errMsg = String.format( "Could not stop container %s: %s", containerHost.getContainerName(),
e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
@RolesAllowed( "Environment-Management|Delete" )
@Override
public void destroyContainer( final ContainerId containerId ) throws PeerException
{
Preconditions.checkNotNull( containerId, "Cannot operate on null container id" );
ContainerHostEntity host;
try
{
host = ( ContainerHostEntity ) getContainerHostById( containerId.getId() );
}
catch ( HostNotFoundException e )
{
return;
}
ResourceHost resourceHost = host.getParent();
try
{
resourceHost.destroyContainerHost( host );
}
catch ( ResourceHostException e )
{
String errMsg = String.format( "Could not destroy container %s: %s", host.getHostname(), e.getMessage() );
LOG.error( errMsg, e );
throw new PeerException( errMsg, e );
}
resourceHostDataService.update( ( ResourceHostEntity ) resourceHost );
//if this container is the last one in its host environment
//then cleanup the host environment on local peer to release its reserved resources
if ( findContainersByEnvironmentId( host.getEnvironmentId().getId() ).isEmpty() )
{
//don't remove local peer PEK, it is used for communication with remote peers
cleanupEnvironment( host.getEnvironmentId(), !getId().equals( host.getInitiatorPeerId() ) );
}
}
@Override
public boolean isConnected( final HostId hostId )
{
Preconditions.checkNotNull( hostId, "Host id null" );
try
{
HostInfo hostInfo = hostRegistry.getHostInfoById( hostId.getId() );
if ( hostInfo.getId().equals( hostId.getId() ) )
{
return hostInfo instanceof ResourceHostInfo || ContainerHostState.RUNNING
.equals( ( ( ContainerHostInfo ) hostInfo ).getState() );
}
}
catch ( HostDisconnectedException ignore )
{
}
return false;
}
@Override
public ResourceHost getManagementHost() throws HostNotFoundException
{
return getResourceHostByContainerName( Common.MANAGEMENT_HOSTNAME );
}
@Override
public Set<ResourceHost> getResourceHosts()
{
return Collections.unmodifiableSet( this.resourceHosts );
}
void addResourceHost( final ResourceHost host )
{
Preconditions.checkNotNull( host, "Resource host could not be null." );
resourceHosts.add( host );
}
@Override
public void removeResourceHost( String rhId ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( rhId ) );
//remove rh ssl cert
securityManager.getKeyStoreManager().removeCertFromTrusted( Common.DEFAULT_PUBLIC_SECURE_PORT, rhId );
securityManager.getHttpContextManager().reloadKeyStore();
//remove rh key
KeyManager keyManager = securityManager.getKeyManager();
keyManager.removeKeyData( rhId );
//remove rh from db
resourceHostDataService.remove( rhId );
//remove from host registry cache
hostRegistry.removeResourceHost( rhId );
ResourceHost resourceHost = getResourceHostById( rhId );
//remove rh containers' keys
for ( final ContainerHost containerHost : resourceHost.getContainerHosts() )
{
keyManager.removeKeyData( containerHost.getKeyId() );
}
//remove rh from local cache
resourceHosts.remove( resourceHost );
}
@Override
public CommandResult execute( final RequestBuilder requestBuilder, final Host host ) throws CommandException
{
return execute( requestBuilder, host, null );
}
@Override
public CommandResult execute( final RequestBuilder requestBuilder, final Host aHost,
final CommandCallback callback ) throws CommandException
{
Preconditions.checkNotNull( requestBuilder, "Invalid request" );
Preconditions.checkNotNull( aHost, "Invalid host" );
CommandResult result;
if ( callback == null )
{
result = commandExecutor.execute( aHost.getId(), requestBuilder );
}
else
{
result = commandExecutor.execute( aHost.getId(), requestBuilder, callback );
}
return result;
}
@Override
public void executeAsync( final RequestBuilder requestBuilder, final Host aHost, final CommandCallback callback )
throws CommandException
{
Preconditions.checkNotNull( requestBuilder, "Invalid request" );
Preconditions.checkNotNull( aHost, "Invalid host" );
if ( callback == null )
{
commandExecutor.executeAsync( aHost.getId(), requestBuilder );
}
else
{
commandExecutor.executeAsync( aHost.getId(), requestBuilder, callback );
}
}
@Override
public void executeAsync( final RequestBuilder requestBuilder, final Host host ) throws CommandException
{
executeAsync( requestBuilder, host, null );
}
@Override
public boolean isLocal()
{
return true;
}
@PermitAll
@Override
public boolean isOnline()
{
return true;
}
@Override
public <T, V> V sendRequest( final T request, final String recipient, final int requestTimeout,
final Class<V> responseType, final int responseTimeout, Map<String, String> headers )
throws PeerException
{
Preconditions.checkNotNull( responseType, "Invalid response type" );
return sendRequestInternal( request, recipient, responseType );
}
@Override
public <T> void sendRequest( final T request, final String recipient, final int requestTimeout,
Map<String, String> headers ) throws PeerException
{
sendRequestInternal( request, recipient, null );
}
<T, V> V sendRequestInternal( final T request, final String recipient, final Class<V> responseType )
throws PeerException
{
Preconditions.checkNotNull( request, "Invalid request" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( recipient ), "Invalid recipient" );
for ( RequestListener requestListener : requestListeners )
{
if ( recipient.equalsIgnoreCase( requestListener.getRecipient() ) )
{
try
{
Object response = requestListener.onRequest( new Payload( request, getId() ) );
if ( response != null && responseType != null )
{
return responseType.cast( response );
}
}
catch ( Exception e )
{
LOG.error( e.getMessage() );
throw new PeerException( e );
}
}
}
return null;
}
public void registerResourceHost( ResourceHostInfo resourceHostInfo )
{
if ( StringUtils.isBlank( resourceHostInfo.getId() ) )
{
//handle case when agent sends empty ID after RH update
return;
}
if ( isInitialized() && !StringUtils.isBlank( resourceHostInfo.getAddress() ) )
{
boolean firstMhRegistration = false;
ResourceHostEntity host;
try
{
host = ( ResourceHostEntity ) getResourceHostById( resourceHostInfo.getId() );
}
catch ( HostNotFoundException e )
{
//register new RH
host = new ResourceHostEntity( getId(), resourceHostInfo );
resourceHostDataService.persist( host );
addResourceHost( host );
setResourceHostTransientFields( Sets.<ResourceHost>newHashSet( host ) );
buildAdminHostRelation( host );
LOG.debug( String.format( "Resource host %s registered.", resourceHostInfo.getHostname() ) );
try
{
getManagementHost();
}
catch ( HostNotFoundException ignore )
{
for ( ContainerHostInfo containerHostInfo : resourceHostInfo.getContainers() )
{
if ( Common.MANAGEMENT_HOSTNAME.equalsIgnoreCase( containerHostInfo.getContainerName() ) )
{
firstMhRegistration = true;
break;
}
}
}
}
//update host info from heartbeat
host.updateHostInfo( resourceHostInfo );
resourceHostDataService.update( host );
LOG.debug( String.format( "Resource host %s updated.", resourceHostInfo.getHostname() ) );
if ( firstMhRegistration )
{
//exchange keys with MH container
try
{
exchangeKeys( host, Common.MANAGEMENT_HOSTNAME );
}
catch ( Exception e )
{
LOG.error( "Error exchanging keys with MH" );
}
//setup security
try
{
buildAdminHostRelation( getContainerHostByContainerName( Common.MANAGEMENT_HOSTNAME ) );
}
catch ( Exception e )
{
LOG.error( "Error setting up security relations with MH", e );
}
}
}
}
@Override
public void onHeartbeat( final ResourceHostInfo resourceHostInfo, Set<QuotaAlertValue> alerts )
{
LOG.debug( "On heartbeat: " + resourceHostInfo.getHostname() );
registerResourceHost( resourceHostInfo );
}
@Override
public void exchangeKeys( ResourceHost resourceHost, String containerName ) throws PeerException
{
HostRegistrationManager registrationManager = ServiceLocator.lookup( HostRegistrationManager.class );
try
{
String token = registrationManager.generateContainerTTLToken( 30 * 1000L ).getToken();
commandUtil.execute( localPeerCommands.getExchangeKeyCommand( containerName, token ), resourceHost );
}
catch ( Exception e )
{
throw new PeerException( e );
}
}
//networking
@Override
public String getVniDomain( final Long vni ) throws PeerException
{
NetworkResource reservedNetworkResource = getReservedNetworkResources().findByVni( vni );
if ( reservedNetworkResource != null )
{
try
{
return getNetworkManager().getVlanDomain( reservedNetworkResource.getVlan() );
}
catch ( NetworkManagerException e )
{
String errMsg =
String.format( "Error obtaining domain by vlan %d: %s", reservedNetworkResource.getVlan(),
e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
else
{
throw new PeerException( String.format( "Vlan for vni %d not found", vni ) );
}
}
// @RolesAllowed( "Environment-Management|Delete" )
@Override
public void removeVniDomain( final Long vni ) throws PeerException
{
NetworkResource reservedNetworkResource = getReservedNetworkResources().findByVni( vni );
if ( reservedNetworkResource != null )
{
try
{
getNetworkManager().removeVlanDomain( reservedNetworkResource.getVlan() );
}
catch ( NetworkManagerException e )
{
String errMsg =
String.format( "Error removing domain by vlan %d: %s", reservedNetworkResource.getVlan(),
e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
else
{
throw new PeerException( String.format( "Vlan for vni %d not found", vni ) );
}
}
// @RolesAllowed( "Environment-Management|Update" )
@Override
public void setVniDomain( final Long vni, final String domain,
final ProxyLoadBalanceStrategy proxyLoadBalanceStrategy, final String sslCertPath )
throws PeerException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( domain ) );
Preconditions.checkNotNull( proxyLoadBalanceStrategy );
NetworkResource reservedNetworkResource = getReservedNetworkResources().findByVni( vni );
if ( reservedNetworkResource != null )
{
try
{
getNetworkManager().setVlanDomain( reservedNetworkResource.getVlan(), domain, proxyLoadBalanceStrategy,
sslCertPath );
}
catch ( NetworkManagerException e )
{
String errMsg = String.format( "Error setting domain by vlan %d: %s", reservedNetworkResource.getVlan(),
e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
else
{
throw new PeerException( String.format( "Vlan for vni %d not found", vni ) );
}
}
@Override
public boolean isIpInVniDomain( final String hostIp, final Long vni ) throws PeerException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostIp ) );
NetworkResource reservedNetworkResource = getReservedNetworkResources().findByVni( vni );
if ( reservedNetworkResource != null )
{
try
{
return getNetworkManager().isIpInVlanDomain( hostIp, reservedNetworkResource.getVlan() );
}
catch ( NetworkManagerException e )
{
String errMsg = String.format( "Error checking domain by ip %s and vlan %d: %s", hostIp,
reservedNetworkResource.getVlan(), e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
else
{
throw new PeerException( String.format( "Vlan for vni %d not found", vni ) );
}
}
// @RolesAllowed( "Environment-Management|Update" )
@Override
public void addIpToVniDomain( final String hostIp, final Long vni ) throws PeerException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostIp ) );
NetworkResource reservedNetworkResource = getReservedNetworkResources().findByVni( vni );
if ( reservedNetworkResource != null )
{
try
{
getNetworkManager().addIpToVlanDomain( hostIp, reservedNetworkResource.getVlan() );
}
catch ( NetworkManagerException e )
{
String errMsg = String.format( "Error adding ip %s to domain by vlan %d: %s", hostIp,
reservedNetworkResource.getVlan(), e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
else
{
throw new PeerException( String.format( "Vlan for vni %d not found", vni ) );
}
}
// @RolesAllowed( "Environment-Management|Update" )
@Override
public void removeIpFromVniDomain( final String hostIp, final Long vni ) throws PeerException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostIp ) );
NetworkResource reservedNetworkResource = getReservedNetworkResources().findByVni( vni );
if ( reservedNetworkResource != null )
{
try
{
getNetworkManager().removeIpFromVlanDomain( hostIp, reservedNetworkResource.getVlan() );
}
catch ( NetworkManagerException e )
{
String errMsg = String.format( "Error removing ip %s from domain by vlan %d: %s", hostIp,
reservedNetworkResource.getVlan(), e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
else
{
throw new PeerException( String.format( "Vlan for vni %d not found", vni ) );
}
}
@RolesAllowed( "Environment-Management|Update" )
@Override
public SshTunnel setupSshTunnelForContainer( final String containerIp, final int sshIdleTimeout )
throws PeerException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( containerIp ) );
Preconditions.checkArgument( containerIp.matches( Common.IP_REGEX ) );
Preconditions.checkArgument( sshIdleTimeout > 0 );
try
{
return getNetworkManager().setupContainerSshTunnel( containerIp, sshIdleTimeout );
}
catch ( NetworkManagerException e )
{
String errMsg =
String.format( "Error setting up ssh tunnel for container ip %s: %s", containerIp, e.getMessage() );
LOG.error( errMsg );
throw new PeerException( errMsg, e );
}
}
@Override
public List<ContainerHost> getPeerContainers( final String peerId )
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( peerId ) );
List<ContainerHost> result = new ArrayList<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
result.addAll( resourceHost.getContainerHostsByPeerId( peerId ) );
}
return result;
}
@Override
public void addRequestListener( final RequestListener listener )
{
if ( listener != null )
{
requestListeners.add( listener );
}
}
public void removeRequestListener( final RequestListener listener )
{
if ( listener != null )
{
requestListeners.remove( listener );
}
}
@Override
public Set<RequestListener> getRequestListeners()
{
return Collections.unmodifiableSet( requestListeners );
}
@RolesAllowed( "Environment-Management|Write" )
@Override
public PublicKeyContainer createPeerEnvironmentKeyPair( RelationLinkDto envLink ) throws PeerException
{
Preconditions.checkNotNull( envLink );
KeyManager keyManager = securityManager.getKeyManager();
EncryptionTool encTool = securityManager.getEncryptionTool();
String pairId = String.format( "%s_%s", getId(), envLink.getUniqueIdentifier() );
PGPPublicKeyRing envPubkey = keyManager.getPublicKeyRing( pairId );
try
{
if ( envPubkey == null )
{
buildPeerEnvRelation( envLink );
final PGPSecretKeyRing peerSecKeyRing = keyManager.getSecretKeyRing( null );
KeyPair keyPair = keyManager.generateKeyPair( pairId, false );
/**
* Destroys only not registered container
*
* @return - true if container is not registered and destroyed, false otherwise
*/
@Override
public boolean destroyNotRegisteredContainer( final String containerId ) throws PeerException
{
ContainerHostInfo containerHost = null;
for ( ContainerHostInfo containerHostInfo : getNotRegisteredContainers() )
{
if ( containerHostInfo.getId().equals( containerId ) )
{
containerHost = containerHostInfo;
break;
}
}
if ( containerHost != null )
{
try
{
commandExecutor.execute( hostRegistry.getResourceHostByContainerHost( containerHost ).getId(),
localPeerCommands.getDestroyContainerCommand( containerHost.getContainerName() ) );
}
catch ( Exception e )
{
throw new PeerException( e );
}
return true;
}
return false;
}
@Override
public Set<ContainerHost> getRegisteredContainers()
{
Set<ContainerHost> result = Sets.newHashSet();
for ( ResourceHost resourceHost : getResourceHosts() )
{
result.addAll( resourceHost.getContainerHosts() );
}
return result;
}
@Override
public Set<ContainerHost> getOrphanContainers()
{
Set<ContainerHost> result = new HashSet<>();
Set<String> involvedPeers = getInvolvedPeers();
final Set<String> unregisteredPeers = getNotRegisteredPeers( involvedPeers );
for ( ResourceHost resourceHost : getResourceHosts() )
{
for ( ContainerHost containerHost : resourceHost.getContainerHosts() )
{
if ( unregisteredPeers.contains( containerHost.getInitiatorPeerId() ) && !Common.MANAGEMENT_HOSTNAME
.equalsIgnoreCase( containerHost.getContainerName() ) )
{
result.add( containerHost );
}
}
}
return result;
}
private Set<String> getInvolvedPeers()
{
final Set<String> result = new HashSet<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
for ( ContainerHost containerHost : resourceHost.getContainerHosts() )
{
result.add( containerHost.getInitiatorPeerId() );
}
}
return result;
}
private Set<String> getNotRegisteredPeers( Set<String> peers )
{
final Set<String> result = new HashSet<>();
PeerManager peerManager = getPeerManager();
for ( String p : peers )
{
if ( RegistrationStatus.NOT_REGISTERED == peerManager.getRemoteRegistrationStatus( p ) )
{
result.add( p );
}
}
return result;
}
protected PeerManager getPeerManager()
{
return ServiceLocator.lookup( PeerManager.class );
}
@Override
public void removeOrphanContainers()
{
Set<ContainerHost> orphanContainers = getOrphanContainers();
for ( ContainerHost containerHost : orphanContainers )
{
try
{
destroyContainer( containerHost.getContainerId() );
}
catch ( PeerException e )
{
LOG.error( "Error on destroying container", e );
}
}
}
@Override
public PeerTemplatesDownloadProgress getTemplateDownloadProgress( final EnvironmentId environmentId )
throws PeerException
{
Preconditions.checkNotNull( environmentId, "Invalid environment id" );
PeerTemplatesDownloadProgress peerProgress = new PeerTemplatesDownloadProgress( getId() );
List<ResourceHost> resourceHosts = Lists.newArrayList( getResourceHosts() );
Collections.sort( resourceHosts, new Comparator<ResourceHost>()
{
@Override
public int compare( final ResourceHost o1, final ResourceHost o2 )
{
return o1.getId().compareTo( o2.getId() );
}
} );
for ( ResourceHost resourceHost : resourceHosts )
{
RhTemplatesDownloadProgress rhProgress = resourceHost.getTemplateDownloadProgress( environmentId.getId() );
//add only RH with existing progress
if ( !rhProgress.getTemplatesDownloadProgresses().isEmpty() )
{
peerProgress.addTemplateDownloadProgress( rhProgress );
}
}
return peerProgress;
}
@Override
public void promoteTemplate( final ContainerId containerId, final String templateName ) throws PeerException
{
Preconditions.checkNotNull( containerId, "Invalid container id" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( templateName ), "Invalid template name" );
ContainerHostEntity containerHost = ( ContainerHostEntity ) getContainerHostById( containerId.getId() );
ResourceHost resourceHost = containerHost.getParent();
try
{
resourceHost.promoteTemplate( containerHost.getContainerName(), templateName );
}
catch ( ResourceHostException e )
{
LOG.error( e.getMessage(), e );
throw new PeerException( String.format( "Error promoting template: %s", e.getMessage() ) );
}
}
@Override
public String exportTemplate( final ContainerId containerId, final String templateName,
final boolean isPrivateTemplate, final String token ) throws PeerException
{
Preconditions.checkNotNull( containerId, "Invalid container id" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( templateName ), "Invalid template name" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( token ), "Invalid token" );
ResourceHost resourceHost = getResourceHostByContainerId( containerId.getId() );
try
{
return resourceHost.exportTemplate( templateName, isPrivateTemplate, token );
}
catch ( ResourceHostException e )
{
LOG.error( e.getMessage(), e );
throw new PeerException( String.format( "Error exporting template: %s", e.getMessage() ) );
}
}
|
package cuneyt.tag;
import android.graphics.drawable.Drawable;
public class Tag {
public int id;
public String text;
public int tagTextColor;
public float tagTextSize;
public int layoutColor;
public int layoutColorPress;
public boolean isDeletable;
public int deleteIndicatorColor;
public float deleteIndicatorSize;
public float radius;
public String deleteIcon;
public float layoutBorderSize;
public int layoutBorderColor;
public Drawable background;
public Tag(String text) {
init(0, text, Constants.DEFAULT_TAG_TEXT_COLOR, Constants.DEFAULT_TAG_TEXT_SIZE, Constants.DEFAULT_TAG_LAYOUT_COLOR, Constants.DEFAULT_TAG_LAYOUT_COLOR_PRESS,
Constants.DEFAULT_TAG_IS_DELETABLE, Constants.DEFAULT_TAG_DELETE_INDICATOR_COLOR, Constants.DEFAULT_TAG_DELETE_INDICATOR_SIZE, Constants.DEFAULT_TAG_RADIUS, Constants.DEFAULT_TAG_DELETE_ICON, Constants.DEFAULT_TAG_LAYOUT_BORDER_SIZE, Constants.DEFAULT_TAG_LAYOUT_BORDER_COLOR);
}
public Tag(String text, int color) {
init(0, text, Constants.DEFAULT_TAG_TEXT_COLOR, Constants.DEFAULT_TAG_TEXT_SIZE, color, Constants.DEFAULT_TAG_LAYOUT_COLOR_PRESS, Constants.DEFAULT_TAG_IS_DELETABLE,
Constants.DEFAULT_TAG_DELETE_INDICATOR_COLOR, Constants.DEFAULT_TAG_DELETE_INDICATOR_SIZE, Constants.DEFAULT_TAG_RADIUS, Constants.DEFAULT_TAG_DELETE_ICON, Constants.DEFAULT_TAG_LAYOUT_BORDER_SIZE, Constants.DEFAULT_TAG_LAYOUT_BORDER_COLOR);
}
private void init(int id, String text, int tagTextColor, float tagTextSize, int layout_color, int layout_color_press, boolean isDeletable, int deleteIndicatorColor,
float deleteIndicatorSize, float radius, String deleteIcon, float layoutBorderSize, int layoutBorderColor) {
this.id = id;
this.text = text;
this.tagTextColor = tagTextColor;
this.tagTextSize = tagTextSize;
this.layoutColor = layout_color;
this.layoutColorPress = layout_color_press;
this.isDeletable = isDeletable;
this.deleteIndicatorColor = deleteIndicatorColor;
this.deleteIndicatorSize = deleteIndicatorSize;
this.radius = radius;
this.deleteIcon = deleteIcon;
this.layoutBorderSize = layoutBorderSize;
this.layoutBorderColor = layoutBorderColor;
}
}
|
package com.exedio.dsmf;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import com.exedio.dsmf.Node.ResultSetHandler;
public final class PostgresqlDriver extends Driver
{
public PostgresqlDriver()
{
super(null, "pga_");
}
@Override
String getColumnType(final int dataType, final ResultSet resultSet) throws SQLException
{
final int columnSize = resultSet.getInt("COLUMN_SIZE");
switch(dataType)
{
case Types.INTEGER:
return "INTEGER";
case Types.VARCHAR:
return "VARCHAR("+columnSize+')';
case Types.DATE:
return "DATE";
default:
return null;
}
}
@Override
void verify(final Schema schema)
{
super.verify(schema);
schema.querySQL(
"select " +
"ut.relname," +
"uc.conname," +
"uc.contype," +
"uc.consrc " +
"from pg_constraint uc " +
"inner join pg_class ut on uc.conrelid=ut.oid " +
"where ut.relname not like 'pg_%' and ut.relname not like 'pga_%'",
new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
//printMeta(resultSet);
while(resultSet.next())
{
//printRow(resultSet);
final String tableName = resultSet.getString(1);
final String constraintName = resultSet.getString(2);
final String constraintType = resultSet.getString(3);
final Table table = schema.notifyExistentTable(tableName);
//System.out.println("tableName:"+tableName+" constraintName:"+constraintName+" constraintType:>"+constraintType+"<");
if("c".equals(constraintType))
{
String searchCondition = resultSet.getString(4);
//System.out.println("searchCondition:>"+searchCondition+"<");
if(searchCondition.startsWith("(")&& searchCondition.endsWith(")"))
searchCondition = searchCondition.substring(1, searchCondition.length()-1);
table.notifyExistentCheckConstraint(constraintName, searchCondition);
}
else if("p".equals(constraintType))
table.notifyExistentPrimaryKeyConstraint(constraintName);
else if("f".equals(constraintType))
table.notifyExistentForeignKeyConstraint(constraintName);
else if("u".equals(constraintType))
table.notifyExistentUniqueConstraint(constraintName, "postgresql unique constraint dummy clause"); // TODO, still don't know where to get this information
else
throw new RuntimeException(constraintType+'-'+constraintName);
//System.out.println("EXISTS:"+tableName);
}
}
});
}
@Override
void appendTableCreateStatement(final StringBuffer bf)
{
bf.append(" without oids");
}
// same as oracle
@Override
String getRenameColumnStatement(final String tableName, final String oldColumnName, final String newColumnName, final String columnType)
{
final StringBuffer bf = new StringBuffer();
bf.append("alter table ").
append(tableName).
append(" rename column ").
append(oldColumnName).
append(" to ").
append(newColumnName);
return bf.toString();
}
// same as hsqldb
@Override
String getCreateColumnStatement(final String tableName, final String columnName, final String columnType)
{
final StringBuffer bf = new StringBuffer();
bf.append("alter table ").
append(tableName).
append(" add column ").
append(columnName).
append(' ').
append(columnType);
return bf.toString();
}
// same as oracle
@Override
String getModifyColumnStatement(final String tableName, final String columnName, final String newColumnType)
{
final StringBuffer bf = new StringBuffer();
bf.append("alter table ").
append(tableName).
append(" modify ").
append(columnName).
append(' ').
append(newColumnType);
return bf.toString();
}
}
|
package org.apache.airavata.helix.impl.workflow;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.helix.workflow.WorkflowOperator;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Type;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.ProcessIdentifier;
import org.apache.airavata.model.messaging.event.ProcessStatusChangeEvent;
import org.apache.airavata.model.status.ProcessState;
import org.apache.airavata.model.status.ProcessStatus;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
public class WorkflowManager {
private final static Logger logger = LoggerFactory.getLogger(WorkflowManager.class);
private Publisher statusPublisher;
private CuratorFramework curatorClient = null;
private WorkflowOperator workflowOperator;
private ThriftClientPool<RegistryService.Client> registryClientPool;
private String workflowManagerName;
public WorkflowManager(String workflowManagerName) {
this.workflowManagerName = workflowManagerName;
}
protected void initComponents() throws Exception {
initRegistryClientPool();
initWorkflowOperatorr();
initStatusPublisher();
initCuratorClient();
}
private void initWorkflowOperatorr() throws Exception {
workflowOperator = new WorkflowOperator(
ServerSettings.getSetting("helix.cluster.name"),
workflowManagerName,
ServerSettings.getZookeeperConnection());
}
private void initStatusPublisher() throws AiravataException {
this.statusPublisher = MessagingFactory.getPublisher(Type.STATUS);
}
private void initCuratorClient() throws Exception {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
this.curatorClient = CuratorFrameworkFactory.newClient(ServerSettings.getZookeeperConnection(), retryPolicy);
this.curatorClient.start();
}
private void initRegistryClientPool() throws ApplicationSettingsException {
GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
poolConfig.maxActive = 100;
poolConfig.minIdle = 5;
poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
poolConfig.testOnBorrow = true;
poolConfig.testWhileIdle = true;
poolConfig.numTestsPerEvictionRun = 10;
poolConfig.maxWait = 3000;
this.registryClientPool = new ThriftClientPool<>(
RegistryService.Client::new, poolConfig, ServerSettings.getRegistryServerHost(),
Integer.parseInt(ServerSettings.getRegistryServerPort()));
}
public Publisher getStatusPublisher() {
return statusPublisher;
}
public CuratorFramework getCuratorClient() {
return curatorClient;
}
public WorkflowOperator getWorkflowOperator() {
return workflowOperator;
}
public ThriftClientPool<RegistryService.Client> getRegistryClientPool() {
return registryClientPool;
}
public void publishProcessStatus(String processId, String experimentId, String gatewayId, ProcessState state)
throws AiravataException {
ProcessStatus status = new ProcessStatus();
status.setState(state);
status.setTimeOfStateChange(Calendar.getInstance().getTimeInMillis());
RegistryService.Client registryClient = getRegistryClientPool().getResource();
try {
registryClient.updateProcessStatus(status, processId);
getRegistryClientPool().returnResource(registryClient);
} catch (Exception e) {
logger.error("Failed to update process status " + processId, e);
getRegistryClientPool().returnBrokenResource(registryClient);
}
ProcessIdentifier identifier = new ProcessIdentifier(processId, experimentId, gatewayId);
ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent(status.getState(), identifier);
MessageContext msgCtx = new MessageContext(processStatusChangeEvent, MessageType.PROCESS,
AiravataUtils.getId(MessageType.PROCESS.name()), gatewayId);
msgCtx.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
getStatusPublisher().publish(msgCtx);
}
public String normalizeTaskId(String taskId) {
return taskId.replace(":", "-").replace(",", "-");
}
}
|
package com.wizzardo.tools.collections.flow.flows;
import com.wizzardo.tools.collections.flow.BiConsumer;
public class FlowCollectWithAccumulator<C, T> extends FlowProcessOnEnd<T, C> {
private final BiConsumer<? super C, ? super T> accumulator;
public FlowCollectWithAccumulator(C collector, BiConsumer<? super C, ? super T> accumulator) {
this.accumulator = accumulator;
this.result = collector;
}
@Override
public void process(T t) {
accumulator.consume(result, t);
}
}
|
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
public class test2_login {
private WebDriver driver;
private WebDriverWait wait;
@Before
public void start(){
//Chrome
//driver = new ChromeDriver();
//wait = new WebDriverWait(driver, 10);
//Firefox old schema
// DesiredCapabilities caps = new DesiredCapabilities();
// caps.setCapability(FirefoxDriver.MARIONETTE, false);
// driver = new FirefoxDriver(caps);
// wait = new WebDriverWait(driver, 10);
//Firefox Nightly
DesiredCapabilities caps = new DesiredCapabilities();
driver = new FirefoxDriver(new FirefoxBinary(new File("C:\\Program Files (x86)\\Nightly\\firefox.exe")), new FirefoxProfile(), caps);
wait = new WebDriverWait(driver, 10);
// DesiredCapabilities caps = new DesiredCapabilities();
// caps.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);
// WebDriver driver = new InternetExplorerDriver(caps);
}
@Test
public void test1(){
driver.get("http://localhost/litecart/admin/login.php");
driver.findElement(By.name("login")).click(); //click with no data input
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin");
driver.findElement(By.name("remember_me")).click();
driver.findElement(By.name("login")).click(); //click with correct login data
}
@After
public void stop(){
driver.quit();
driver = null;
}
}
|
package lib;
import java.util.ArrayList;
import java.util.List;
/**
* Parse list of Strings to a List of tagged entities.
*/
public final class ParseList {
public static List<TaggedEntity> parseStringList(final List<String> toParse) {
List<TaggedEntity> retList = new ArrayList<>();
System.out.println(
String.join("", "[DEBUG] List has a length of: ",
Integer.toString(toParse.size()), "\n")
);
for (String currLine : toParse) {
if (currLine.contains("(#)") & currLine.endsWith("#)")) {
System.out.println("[DEBUG] TagLine");
retList.add(new TaggedEntity());
String[] ls = currLine
.substring(currLine.indexOf("(#)")+"(#)".length(),
currLine.length()-"#)".length())
.split(",");
for (String s : ls) {
retList.get(retList.size()-1).getTags().add(s);
}
} else if (!retList.isEmpty()) {
System.out.println("[DEBUG] BodyLine");
String currString = retList.get(retList.size()-1).getBody();
retList.get(retList.size()-1).setBody(
String.join("", currString, currLine, "\n")
);
} else {
System.out.println("[WARNING] Found line not connected to a tag, will be omitted.");
}
}
System.out.println(String.join("", "[DEBUG] # of Tagged entities: ",
Integer.toString(retList.size()))
);
retList.forEach(c -> System.out.println(
String.join("", "[DEBUG] ", "ID: ", c.getEntityID(), " Tags: ",
Integer.toString(c.getTags().size()), " ", c.getTags().toString(),
" Body: ", c.getBody()
)
)
);
return retList;
}
}
|
package unitTests.doc;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import junit.framework.Assert;
import doc.DocBookize;
/**
* Contains tests for {@link DocBookize}.
*
* @author vjuresch
* @since 3.9
* @version $Id$
*
*/
public class TestDocBookize {
/**
* Regular expresion matching the & lt ; and & gt ;
* inside programlisting tags.
*/
private static final String REGEXP = "(<programlisting.*>)(.*(<).*|(>).*?)(</programlisting>)";
/** Path to the files cotaining xml that triggers the bug */
private static final String PATH = "src/Tests/unitTests/doc/";
/** File containing the xml that triggers the bug */
private static final String XML_FILE = "singleLine.xml";
/** Temporary file that will contain the modified xml */
private static final String TEST_FILE = "singleLineTest.xml";
/**
* Tests for bug PROACTIVE-346:
* Characters < and > do not get transformed into & lt; & gt; when code
* is included from programlisting tags from a file and it is a single line of code.
*
* @throws Exception
*/
@Test
public void testTransform() throws Exception {
final String path[] = { "./" };
final String inPath = PATH + XML_FILE;
final String javaSrc = "";
final String testPath = PATH + TEST_FILE;
//copy file to temporary file
final InputStream input = new FileInputStream(inPath);
final OutputStream output = new FileOutputStream(testPath);
//copy singleLine.xml to singleLineTest.xml
final byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
}
input.close();
output.close();
//run DocBookize on singleLineTest file
final String mainArgs[] = { testPath, javaSrc, path[0] };
DocBookize.main(mainArgs);
//load singleLineText.xml in String (it's a small file)
final File tmp = new File(testPath);
final BufferedReader buff = new BufferedReader(new FileReader(tmp));
String fileText = "";
String tmpLine = "";
while (tmpLine != null) {
fileText += tmpLine;
tmpLine = buff.readLine();
}
buff.close();
System.out.println(fileText);
//scan for programlisting containing < >
//String regex = "(<programlisting.*>)(.*[><].*?)(</programlisting>)";
//it assumes the test file is changed to contain < and >
final Matcher matcher = Pattern.compile(REGEXP).matcher(fileText);
final boolean good = matcher.find();
//delete temporary file
if (!tmp.delete()) {
throw new IOException("Cannot delete temporary file : " + tmp.getAbsolutePath());
}
Assert.assertTrue(good);
}
}
|
package VASSAL.build.module.map;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.datatransfer.StringSelection;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DragSourceMotionListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.dnd.InvalidDnDOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import org.apache.commons.lang.SystemUtils;
import VASSAL.build.AbstractBuildable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.command.NullCommand;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.counters.BasicPiece;
import VASSAL.counters.BoundsTracker;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.Decorator;
import VASSAL.counters.DragBuffer;
import VASSAL.counters.EventFilter;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Highlighter;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceCloner;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceIterator;
import VASSAL.counters.PieceSorter;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.imageop.Op;
/**
* This is a MouseListener that moves pieces onto a Map window
*/
public class PieceMover extends AbstractBuildable
implements MouseListener,
GameComponent,
Comparator<GamePiece> {
/** The Preferences key for autoreporting moves. */
public static final String AUTO_REPORT = "autoReport"; //$NON-NLS-1$
public static final String NAME = "name";
public static final String HOTKEY = "hotkey";
protected Map map;
protected Point dragBegin;
protected GamePiece dragging;
protected LaunchButton markUnmovedButton;
protected String markUnmovedText;
protected String markUnmovedIcon;
public static final String ICON_NAME = "icon"; //$NON-NLS-1$
protected String iconName;
// Selects drag target from mouse click on the Map
protected PieceFinder dragTargetSelector;
// Selects piece to merge with at the drop destination
protected PieceFinder dropTargetSelector;
// Processes drag target after having been selected
protected PieceVisitorDispatcher selectionProcessor;
protected Comparator<GamePiece> pieceSorter = new PieceSorter();
public void addTo(Buildable b) {
dragTargetSelector = createDragTargetSelector();
dropTargetSelector = createDropTargetSelector();
selectionProcessor = createSelectionProcessor();
map = (Map) b;
map.addLocalMouseListener(this);
GameModule.getGameModule().getGameState().addGameComponent(this);
map.setDragGestureListener(DragHandler.getTheDragHandler());
map.setPieceMover(this);
setAttribute(Map.MARK_UNMOVED_TEXT,
map.getAttributeValueString(Map.MARK_UNMOVED_TEXT));
setAttribute(Map.MARK_UNMOVED_ICON,
map.getAttributeValueString(Map.MARK_UNMOVED_ICON));
}
protected MovementReporter createMovementReporter(Command c) {
return new MovementReporter(c);
}
/**
* When the user completes a drag-drop operation, the pieces being
* dragged will either be combined with an existing piece on the map
* or else placed on the map without stack. This method returns a
* {@link PieceFinder} instance that determines which {@link GamePiece}
* (if any) to combine the being-dragged pieces with.
*
* @return
*/
protected PieceFinder createDropTargetSelector() {
return new PieceFinder.Movable() {
public Object visitDeck(Deck d) {
final Point pos = d.getPosition();
final Point p = new Point(pt.x - pos.x, pt.y - pos.y);
if (d.getShape().contains(p)) {
return d;
}
else {
return null;
}
}
public Object visitDefault(GamePiece piece) {
GamePiece selected = null;
if (this.map.getStackMetrics().isStackingEnabled() &&
this.map.getPieceCollection().canMerge(dragging, piece)) {
if (this.map.isLocationRestricted(pt)) {
final Point snap = this.map.snapTo(pt);
if (piece.getPosition().equals(snap)) {
selected = piece;
}
}
else {
selected = (GamePiece) super.visitDefault(piece);
}
}
if (selected != null &&
DragBuffer.getBuffer().contains(selected) &&
selected.getParent() != null &&
selected.getParent().topPiece() == selected) {
selected = null;
}
return selected;
}
public Object visitStack(Stack s) {
GamePiece selected = null;
if (this.map.getStackMetrics().isStackingEnabled() &&
this.map.getPieceCollection().canMerge(dragging, s) &&
!DragBuffer.getBuffer().contains(s) &&
s.topPiece() != null) {
if (this.map.isLocationRestricted(pt) && !s.isExpanded()) {
if (s.getPosition().equals(this.map.snapTo(pt))) {
selected = s;
}
}
else {
selected = (GamePiece) super.visitStack(s);
}
}
return selected;
}
};
}
/**
* When the user clicks on the map, a piece from the map is selected by
* the dragTargetSelector. What happens to that piece is determined by
* the {@link PieceVisitorDispatcher} instance returned by this method.
* The default implementation does the following: If a Deck, add the top
* piece to the drag buffer If a stack, add it to the drag buffer.
* Otherwise, add the piece and any other multi-selected pieces to the
* drag buffer.
*
* @see #createDragTargetSelector
* @return
*/
protected PieceVisitorDispatcher createSelectionProcessor() {
return new DeckVisitorDispatcher(new DeckVisitor() {
public Object visitDeck(Deck d) {
DragBuffer.getBuffer().clear();
for (PieceIterator it = d.drawCards(); it.hasMoreElements();) {
DragBuffer.getBuffer().add(it.nextPiece());
}
return null;
}
public Object visitStack(Stack s) {
DragBuffer.getBuffer().clear();
// RFE 1629255 - Only add selected pieces within the stack to the DragBuffer
// Add whole stack if all pieces are selected - better drag cursor
int selectedCount = 0;
for (int i = 0; i < s.getPieceCount(); i++) {
if (Boolean.TRUE.equals(s.getPieceAt(i)
.getProperty(Properties.SELECTED))) {
selectedCount++;
}
}
if (((Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS)).booleanValue() || s.getPieceCount() == 1 || s.getPieceCount() == selectedCount) {
DragBuffer.getBuffer().add(s);
}
else {
for (int i = 0; i < s.getPieceCount(); i++) {
final GamePiece p = s.getPieceAt(i);
if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
DragBuffer.getBuffer().add(p);
}
}
}
// End RFE 1629255
if (KeyBuffer.getBuffer().containsChild(s)) {
// If clicking on a stack with a selected piece, put all selected
// pieces in other stacks into the drag buffer
KeyBuffer.getBuffer().sort(PieceMover.this);
for (Iterator<GamePiece> i =
KeyBuffer.getBuffer().getPiecesIterator(); i.hasNext();) {
final GamePiece piece = i.next();
if (piece.getParent() != s) {
DragBuffer.getBuffer().add(piece);
}
}
}
return null;
}
public Object visitDefault(GamePiece selected) {
DragBuffer.getBuffer().clear();
if (KeyBuffer.getBuffer().contains(selected)) {
// If clicking on a selected piece, put all selected pieces into the
// drag buffer
KeyBuffer.getBuffer().sort(PieceMover.this);
for (Iterator<GamePiece> i =
KeyBuffer.getBuffer().getPiecesIterator(); i.hasNext();) {
DragBuffer.getBuffer().add(i.next());
}
}
else {
DragBuffer.getBuffer().clear();
DragBuffer.getBuffer().add(selected);
}
return null;
}
});
}
/**
* Returns the {@link PieceFinder} instance that will select a
* {@link GamePiece} for processing when the user clicks on the map.
* The default implementation is to return the first piece whose shape
* contains the point clicked on.
*
* @return
*/
protected PieceFinder createDragTargetSelector() {
return new PieceFinder.Movable() {
public Object visitDeck(Deck d) {
final Point pos = d.getPosition();
final Point p = new Point(pt.x - pos.x, pt.y - pos.y);
if (d.boundingBox().contains(p) && d.getPieceCount() > 0) {
return d;
}
else {
return null;
}
}
};
}
public void setup(boolean gameStarting) {
if (gameStarting) {
initButton();
}
}
public Command getRestoreCommand() {
return null;
}
private Image loadIcon(String name) {
if (name == null || name.length() == 0) return null;
return Op.load(name).getImage();
}
protected void initButton() {
final String value = getMarkOption();
if (GlobalOptions.PROMPT.equals(value)) {
BooleanConfigurer config = new BooleanConfigurer(
Map.MARK_MOVED, "Mark Moved Pieces", Boolean.TRUE);
GameModule.getGameModule().getPrefs().addOption(config);
}
if (!GlobalOptions.NEVER.equals(value)) {
if (markUnmovedButton == null) {
final ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
final GamePiece[] p = map.getAllPieces();
final Command c = new NullCommand();
for (int i = 0; i < p.length; ++i) {
c.append(markMoved(p[i], false));
}
GameModule.getGameModule().sendAndLog(c);
map.repaint();
}
};
markUnmovedButton =
new LaunchButton("", NAME, HOTKEY, Map.MARK_UNMOVED_ICON, al);
Image img = null;
if (iconName != null && iconName.length() > 0) {
img = loadIcon(iconName);
if (img != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, iconName);
}
}
if (img == null) {
img = loadIcon(markUnmovedIcon);
if (img != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, markUnmovedIcon);
}
}
markUnmovedButton.setAlignmentY(0.0F);
markUnmovedButton.setText(markUnmovedText);
markUnmovedButton.setToolTipText(
map.getAttributeValueString(Map.MARK_UNMOVED_TOOLTIP));
map.getToolBar().add(markUnmovedButton);
}
}
else if (markUnmovedButton != null) {
map.getToolBar().remove(markUnmovedButton);
markUnmovedButton = null;
}
}
private String getMarkOption() {
String value = map.getAttributeValueString(Map.MARK_MOVED);
if (value == null) {
value = GlobalOptions.getInstance()
.getAttributeValueString(GlobalOptions.MARK_MOVED);
}
return value;
}
public String[] getAttributeNames() {
return new String[]{ICON_NAME};
}
public String getAttributeValueString(String key) {
return ICON_NAME.equals(key) ? iconName : null;
}
public void setAttribute(String key, Object value) {
if (ICON_NAME.equals(key)) {
iconName = (String) value;
}
else if (Map.MARK_UNMOVED_TEXT.equals(key)) {
if (markUnmovedButton != null) {
markUnmovedButton.setAttribute(NAME, value);
}
markUnmovedText = (String) value;
}
else if (Map.MARK_UNMOVED_ICON.equals(key)) {
if (markUnmovedButton != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, value);
}
markUnmovedIcon = (String) value;
}
}
protected boolean isMultipleSelectionEvent(MouseEvent e) {
return e.isShiftDown();
}
/** Invoked just before a piece is moved */
protected Command movedPiece(GamePiece p, Point loc) {
setOldLocation(p);
Command c = null;
if (!loc.equals(p.getPosition())) {
c = markMoved(p, true);
}
if (p.getParent() != null) {
final Command removedCommand = p.getParent().pieceRemoved(p);
c = c == null ? removedCommand : c.append(removedCommand);
}
return c;
}
protected void setOldLocation(GamePiece p) {
if (p instanceof Stack) {
for (int i = 0; i < ((Stack) p).getPieceCount(); i++) {
Decorator.setOldProperties(((Stack) p).getPieceAt(i));
}
}
else Decorator.setOldProperties(p);
}
public Command markMoved(GamePiece p, boolean hasMoved) {
if (GlobalOptions.NEVER.equals(getMarkOption())) {
hasMoved = false;
}
Command c = new NullCommand();
if (!hasMoved || shouldMarkMoved()) {
if (p instanceof Stack) {
for (Iterator<GamePiece> i = ((Stack) p).getPiecesIterator();
i.hasNext();) {
c.append(markMoved(i.next(), hasMoved));
}
}
else if (p.getProperty(Properties.MOVED) != null) {
if (p.getId() != null) {
final ChangeTracker comm = new ChangeTracker(p);
p.setProperty(Properties.MOVED,
hasMoved ? Boolean.TRUE : Boolean.FALSE);
c = comm.getChangeCommand();
}
}
}
return c;
}
protected boolean shouldMarkMoved() {
final String option = getMarkOption();
if (GlobalOptions.ALWAYS.equals(option)) {
return true;
}
else if (GlobalOptions.NEVER.equals(option)) {
return false;
}
else {
return Boolean.TRUE.equals(
GameModule.getGameModule().getPrefs().getValue(Map.MARK_MOVED));
}
}
/**
* Moves pieces in DragBuffer to point p by generating a Command for
* each element in DragBuffer
*
* @param map
* Map
* @param p
* Point mouse released
*/
public Command movePieces(Map map, Point p) {
final List<GamePiece> allDraggedPieces = new ArrayList<GamePiece>();
final PieceIterator it = DragBuffer.getBuffer().getIterator();
if (!it.hasMoreElements()) return null;
Point offset = null;
Command comm = new NullCommand();
final BoundsTracker tracker = new BoundsTracker();
// Map of Point->List<GamePiece> of pieces to merge with at a given
// location. There is potentially one piece for each Game Piece Layer.
final HashMap<Point,List<GamePiece>> mergeTargets =
new HashMap<Point,List<GamePiece>>();
while (it.hasMoreElements()) {
dragging = it.nextPiece();
tracker.addPiece(dragging);
/*
* Take a copy of the pieces in dragging.
* If it is a stack, it is cleared by the merging process.
*/
final ArrayList<GamePiece> draggedPieces = new ArrayList<GamePiece>(0);
if (dragging instanceof Stack) {
int size = ((Stack) dragging).getPieceCount();
for (int i = 0; i < size; i++) {
draggedPieces.add(((Stack) dragging).getPieceAt(i));
}
}
else {
draggedPieces.add(dragging);
}
if (offset != null) {
p = new Point(dragging.getPosition().x + offset.x,
dragging.getPosition().y + offset.y);
}
List<GamePiece> mergeCandidates = mergeTargets.get(p);
GamePiece mergeWith = null;
// Find an already-moved piece that we can merge with at the destination
// point
if (mergeCandidates != null) {
for (int i = 0, n = mergeCandidates.size(); i < n; ++i) {
final GamePiece candidate = mergeCandidates.get(i);
if (map.getPieceCollection().canMerge(candidate, dragging)) {
mergeWith = candidate;
mergeCandidates.set(i, dragging);
break;
}
}
}
// Now look for an already-existing piece at the destination point
if (mergeWith == null) {
mergeWith = map.findAnyPiece(p, dropTargetSelector);
if (mergeWith == null && !Boolean.TRUE.equals(
dragging.getProperty(Properties.IGNORE_GRID))) {
p = map.snapTo(p);
}
if (offset == null) {
offset = new Point(p.x - dragging.getPosition().x,
p.y - dragging.getPosition().y);
}
if (mergeWith != null && map.getStackMetrics().isStackingEnabled()) {
mergeCandidates = new ArrayList<GamePiece>();
mergeCandidates.add(dragging);
mergeCandidates.add(mergeWith);
mergeTargets.put(p, mergeCandidates);
}
}
if (mergeWith == null) {
comm = comm.append(movedPiece(dragging, p));
comm = comm.append(map.placeAt(dragging, p));
if (!(dragging instanceof Stack) &&
!Boolean.TRUE.equals(dragging.getProperty(Properties.NO_STACK))) {
final Stack parent = map.getStackMetrics().createStack(dragging);
if (parent != null) {
comm = comm.append(map.placeAt(parent, p));
}
}
}
else {
// Do not add pieces to the Deck that are Obscured to us, or that
// the Deck does not want to contain. Removing them from the
// draggedPieces list will cause them to be left behind where the
// drag started. NB. Pieces that have been dragged from a face-down
// Deck will be be Obscued to us, but will be Obscured by the dummy
// user Deck.NO_USER
if (mergeWith instanceof Deck) {
final ArrayList<GamePiece> newList = new ArrayList<GamePiece>(0);
for (GamePiece piece : draggedPieces) {
if (((Deck) mergeWith).mayContain(piece)) {
final boolean isObscuredToMe = Boolean.TRUE.equals(piece.getProperty(Properties.OBSCURED_TO_ME));
if (!isObscuredToMe || (isObscuredToMe && Deck.NO_USER.equals(piece.getProperty(Properties.OBSCURED_BY)))) {
newList.add(piece);
}
}
}
if (newList.size() != draggedPieces.size()) {
draggedPieces.clear();
for (GamePiece piece : newList) {
draggedPieces.add(piece);
}
}
}
for (GamePiece piece : draggedPieces) {
comm = comm.append(movedPiece(piece, mergeWith.getPosition()));
comm = comm.append(map.getStackMetrics().merge(mergeWith, piece));
}
}
for (GamePiece piece : draggedPieces) {
KeyBuffer.getBuffer().add(piece);
}
// Record each individual piece moved
for (GamePiece piece : draggedPieces) {
allDraggedPieces.add(piece);
}
tracker.addPiece(dragging);
}
if (GlobalOptions.getInstance().autoReportEnabled()) {
final Command report = createMovementReporter(comm).getReportCommand().append(new MovementReporter.HiddenMovementReporter(comm).getReportCommand());
report.execute();
comm = comm.append(report);
}
// Apply key after move to each moved piece
if (map.getMoveKey() != null) {
applyKeyAfterMove(allDraggedPieces, comm, map.getMoveKey());
}
tracker.repaint();
return comm;
}
protected void applyKeyAfterMove(List<GamePiece> pieces,
Command comm, KeyStroke key) {
for (GamePiece piece : pieces) {
if (piece.getProperty(Properties.SNAPSHOT) == null) {
piece.setProperty(Properties.SNAPSHOT,
PieceCloner.getInstance().clonePiece(piece));
}
comm.append(piece.keyEvent(key));
}
}
/**
* This listener is used for faking drag-and-drop on Java 1.1 systems
*
* @param e
*/
public void mousePressed(MouseEvent e) {
if (canHandleEvent(e)) {
selectMovablePieces(e);
}
}
/** Place the clicked-on piece into the {@link DragBuffer} */
protected void selectMovablePieces(MouseEvent e) {
final GamePiece p = map.findPiece(e.getPoint(), dragTargetSelector);
dragBegin = e.getPoint();
if (p != null) {
final EventFilter filter =
(EventFilter) p.getProperty(Properties.MOVE_EVENT_FILTER);
if (filter == null || !filter.rejectEvent(e)) {
selectionProcessor.accept(p);
}
else {
DragBuffer.getBuffer().clear();
}
}
else {
DragBuffer.getBuffer().clear();
}
// show/hide selection boxes
map.repaint();
}
/** @deprecated Use {@link #selectMovablePieces(MouseEvent)}. */
@Deprecated
protected void selectMovablePieces(Point point) {
final GamePiece p = map.findPiece(point, dragTargetSelector);
dragBegin = point;
selectionProcessor.accept(p);
// show/hide selection boxes
map.repaint();
}
protected boolean canHandleEvent(MouseEvent e) {
return !e.isShiftDown() &&
!e.isControlDown() &&
!e.isMetaDown() &&
e.getClickCount() < 2 &&
!e.isConsumed();
}
/**
* Return true if this point is "close enough" to the point at which
* the user pressed the mouse to be considered a mouse click (such
* that no moves are done)
*/
public boolean isClick(Point pt) {
boolean isClick = false;
if (dragBegin != null) {
final Board b = map.findBoard(pt);
boolean useGrid = b != null && b.getGrid() != null;
if (useGrid) {
final PieceIterator it = DragBuffer.getBuffer().getIterator();
final GamePiece dragging = it.hasMoreElements() ? it.nextPiece() : null;
useGrid =
dragging != null &&
!Boolean.TRUE.equals(dragging.getProperty(Properties.IGNORE_GRID)) &&
(dragging.getParent() == null || !dragging.getParent().isExpanded());
}
if (useGrid) {
if (map.equals(DragBuffer.getBuffer().getFromMap())) {
if (map.snapTo(pt).equals(map.snapTo(dragBegin))) {
isClick = true;
}
}
}
else {
if (Math.abs(pt.x - dragBegin.x) <= 5 &&
Math.abs(pt.y - dragBegin.y) <= 5) {
isClick = true;
}
}
}
return isClick;
}
public void mouseReleased(MouseEvent e) {
if (canHandleEvent(e)) {
if (!isClick(e.getPoint())) {
performDrop(e.getPoint());
}
}
dragBegin = null;
map.getView().setCursor(null);
}
protected void performDrop(Point p) {
final Command move = movePieces(map, p);
GameModule.getGameModule().sendAndLog(move);
if (move != null) {
DragBuffer.getBuffer().clear();
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
/**
* Implement Comparator to sort the contents of the drag buffer before
* completing the drag. This sorts the contents to be in the same order
* as the pieces were in their original parent stack.
*/
public int compare(GamePiece p1, GamePiece p2) {
return pieceSorter.compare(p1, p2);
}
// We force the loading of these classes because otherwise they would
// be loaded when the user initiates the first drag, which makes the
// start of the drag choppy.
static {
try {
Class.forName(MovementReporter.class.getName(),
true, MovementReporter.class.getClassLoader());
Class.forName(KeyBuffer.class.getName(),
true, KeyBuffer.class.getClassLoader());
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e); // impossible
}
}
/** Common functionality for DragHandler for cases with and without
* drag image support. <p>
* NOTE: DragSource.isDragImageSupported() returns false for j2sdk1.4.2_02 on
* Windows 2000
*
* @author Pieter Geerkens
*/
abstract static public class AbstractDragHandler
implements DragGestureListener, DragSourceListener,
DragSourceMotionListener, DropTargetListener
{
static private AbstractDragHandler theDragHandler =
DragSource.isDragImageSupported() ?
(SystemUtils.IS_OS_MAC_OSX ?
new DragHandlerMacOSX() : new DragHandler()) :
new DragHandlerNoImage();
/** returns the singleton DragHandler instance */
static public AbstractDragHandler getTheDragHandler() {
return theDragHandler;
}
static public void setTheDragHandler(AbstractDragHandler myHandler) {
theDragHandler = myHandler;
}
final static int CURSOR_ALPHA = 127; // psuedo cursor is 50% transparent
final static int EXTRA_BORDER = 4; // psuedo cursor is includes a 4 pixel border
protected JLabel dragCursor; // An image label. Lives on current DropTarget's
// LayeredPane.
// private BufferedImage dragImage; // An image label. Lives on current DropTarget's LayeredPane.
private Point drawOffset = new Point(); // translates event coords to local
// drawing coords
private Rectangle boundingBox; // image bounds
private int originalPieceOffsetX; // How far drag STARTED from gamepiece's
// center
private int originalPieceOffsetY; // I.e. on original map
protected double dragPieceOffCenterZoom = 1.0; // zoom at start of drag
private int currentPieceOffsetX; // How far cursor is CURRENTLY off-center,
// a function of
// dragPieceOffCenter{X,Y,Zoom}
private int currentPieceOffsetY; // I.e. on current map (which may have
// different zoom
protected double dragCursorZoom = 1.0; // Current cursor scale (zoom)
Component dragWin; // the component that initiated the drag operation
Component dropWin; // the drop target the mouse is currently over
JLayeredPane drawWin; // the component that owns our psuedo-cursor
// Seems there can be only one DropTargetListener a drop target. After we
// process a drop target
// event, we manually pass the event on to this listener.
java.util.Map<Component,DropTargetListener> dropTargetListeners =
new HashMap<Component,DropTargetListener>();
abstract protected int getOffsetMult();
/**
* Creates a new DropTarget and hooks us into the beginning of a
* DropTargetListener chain. DropTarget events are not multicast;
* there can be only one "true" listener.
*/
static public DropTarget makeDropTarget(Component theComponent, int dndContants, DropTargetListener dropTargetListener) {
if (dropTargetListener != null) {
DragHandler.getTheDragHandler()
.dropTargetListeners.put(theComponent, dropTargetListener);
}
return new DropTarget(theComponent, dndContants,
DragHandler.getTheDragHandler());
}
static public void removeDropTarget(Component theComponent) {
DragHandler.getTheDragHandler().dropTargetListeners.remove(theComponent);
}
protected DropTargetListener getListener(DropTargetEvent e) {
final Component component = e.getDropTargetContext().getComponent();
return dropTargetListeners.get(component);
}
/** Moves the drag cursor on the current draw window */
protected void moveDragCursor(int dragX, int dragY) {
if (drawWin != null) {
dragCursor.setLocation(dragX - drawOffset.x, dragY - drawOffset.y);
}
}
/** Removes the drag cursor from the current draw window */
protected void removeDragCursor() {
if (drawWin != null) {
if (dragCursor != null) {
dragCursor.setVisible(false);
drawWin.remove(dragCursor);
}
drawWin = null;
}
}
/** calculates the offset between cursor dragCursor positions */
private void calcDrawOffset() {
if (drawWin != null) {
// drawOffset is the offset between the mouse location during a drag
// and the upper-left corner of the cursor
// accounts for difference between event point (screen coords)
// and Layered Pane position, boundingBox and off-center drag
drawOffset.x = -boundingBox.x - currentPieceOffsetX + EXTRA_BORDER;
drawOffset.y = -boundingBox.y - currentPieceOffsetY + EXTRA_BORDER;
SwingUtilities.convertPointToScreen(drawOffset, drawWin);
}
}
/**
* creates or moves cursor object to given JLayeredPane. Usually called by setDrawWinToOwnerOf()
*/
private void setDrawWin(JLayeredPane newDrawWin) {
if (newDrawWin != drawWin) {
// remove cursor from old window
if (dragCursor.getParent() != null) {
dragCursor.getParent().remove(dragCursor);
}
if (drawWin != null) {
drawWin.repaint(dragCursor.getBounds());
}
drawWin = newDrawWin;
calcDrawOffset();
dragCursor.setVisible(false);
drawWin.add(dragCursor, JLayeredPane.DRAG_LAYER);
}
}
/**
* creates or moves cursor object to given window. Called when drag operation begins in a window or the cursor is
* dragged over a new drop-target window
*/
public void setDrawWinToOwnerOf(Component newDropWin) {
if (newDropWin != null) {
final JRootPane rootWin = SwingUtilities.getRootPane(newDropWin);
if (rootWin != null) {
setDrawWin(rootWin.getLayeredPane());
}
}
}
/** Common functionality abstracted from makeDragImage and makeDragCursor
*
* @param zoom
* @param doOffset
* @param target
* @param setSize
* @return
*/
BufferedImage makeDragImageCursorCommon(double zoom, boolean doOffset,
Component target, boolean setSize) {
// FIXME: Should be an ImageOp.
dragCursorZoom = zoom;
final List<Point> relativePositions = buildBoundingBox(zoom, doOffset);
final int w = boundingBox.width + EXTRA_BORDER * 2;
final int h = boundingBox.height + EXTRA_BORDER * 2;
BufferedImage image = ImageUtils.createCompatibleTranslucentImage(w, h);
drawDragImage(image, target, relativePositions, zoom);
if (setSize) dragCursor.setSize(w, h);
image = featherDragImage(image, w, h, EXTRA_BORDER);
return image;
}
/**
* Creates the image to use when dragging based on the zoom factor
* passed in.
*
* @param zoom DragBuffer.getBuffer
* @return dragImage
*/
private BufferedImage makeDragImage(double zoom) {
return makeDragImageCursorCommon(zoom, false, null, false);
}
/**
* Installs the cursor image into our dragCursor JLabel.
* Sets current zoom. Should be called at beginning of drag
* and whenever zoom changes. INPUT: DragBuffer.getBuffer OUTPUT:
* dragCursorZoom cursorOffCenterX cursorOffCenterY boundingBox
* @param zoom DragBuffer.getBuffer
*
*/
protected void makeDragCursor(double zoom) {
// create the cursor if necessary
if (dragCursor == null) {
dragCursor = new JLabel();
dragCursor.setVisible(false);
}
dragCursor.setIcon(new ImageIcon(
makeDragImageCursorCommon(zoom, true, dragCursor, true)));
}
private List<Point> buildBoundingBox(double zoom, boolean doOffset) {
final ArrayList<Point> relativePositions = new ArrayList<Point>();
final PieceIterator dragContents = DragBuffer.getBuffer().getIterator();
final GamePiece firstPiece = dragContents.nextPiece();
GamePiece lastPiece = firstPiece;
currentPieceOffsetX =
(int) (originalPieceOffsetX / dragPieceOffCenterZoom * zoom + 0.5);
currentPieceOffsetY =
(int) (originalPieceOffsetY / dragPieceOffCenterZoom * zoom + 0.5);
boundingBox = firstPiece.getShape().getBounds();
boundingBox.width *= zoom;
boundingBox.height *= zoom;
boundingBox.x *= zoom;
boundingBox.y *= zoom;
if (doOffset) {
calcDrawOffset();
}
relativePositions.add(new Point(0,0));
int stackCount = 0;
while (dragContents.hasMoreElements()) {
final GamePiece nextPiece = dragContents.nextPiece();
final Rectangle r = nextPiece.getShape().getBounds();
r.width *= zoom;
r.height *= zoom;
r.x *= zoom;
r.y *= zoom;
final Point p = new Point(
(int) Math.round(
zoom * (nextPiece.getPosition().x - firstPiece.getPosition().x)),
(int) Math.round(
zoom * (nextPiece.getPosition().y - firstPiece.getPosition().y)));
r.translate(p.x, p.y);
if (nextPiece.getPosition().equals(lastPiece.getPosition())) {
stackCount++;
final StackMetrics sm = getStackMetrics(nextPiece);
r.translate(sm.unexSepX*stackCount,-sm.unexSepY*stackCount);
}
boundingBox.add(r);
relativePositions.add(p);
lastPiece = nextPiece;
}
return relativePositions;
}
private void drawDragImage(BufferedImage image, Component target,
List<Point> relativePositions, double zoom) {
final Graphics2D g = image.createGraphics();
int index = 0;
Point lastPos = null;
int stackCount = 0;
for (PieceIterator dragContents = DragBuffer.getBuffer().getIterator();
dragContents.hasMoreElements(); ) {
final GamePiece piece = dragContents.nextPiece();
final Point pos = relativePositions.get(index++);
final Map map = piece.getMap();
if (piece instanceof Stack){
stackCount = 0;
piece.draw(g, EXTRA_BORDER - boundingBox.x + pos.x,
EXTRA_BORDER - boundingBox.y + pos.y,
map == null ? target : map.getView(), zoom);
}
else {
final Point offset = new Point(0,0);
if (pos.equals(lastPos)) {
stackCount++;
final StackMetrics sm = getStackMetrics(piece);
offset.x = sm.unexSepX * stackCount;
offset.y = sm.unexSepY * stackCount;
}
else {
stackCount = 0;
}
final int x = EXTRA_BORDER - boundingBox.x + pos.x + offset.x;
final int y = EXTRA_BORDER - boundingBox.y + pos.y - offset.y;
piece.draw(g, x, y, map == null ? target : map.getView(), zoom);
final Highlighter highlighter = map == null ?
BasicPiece.getHighlighter() : map.getHighlighter();
highlighter.draw(piece, g, x, y, null, zoom);
}
lastPos = pos;
}
g.dispose();
}
private StackMetrics getStackMetrics(GamePiece piece) {
StackMetrics sm = null;
final Map map = piece.getMap();
if (map != null) {
sm = map.getStackMetrics();
}
if (sm == null) {
sm = new StackMetrics();
}
return sm;
}
private BufferedImage featherDragImage(BufferedImage src,
int w, int h, int b) {
// FIXME: This should be redone so that we draw the feathering onto the
// destination first, and then pass the Graphics2D on to draw the pieces
// directly over it. Presently this doesn't work because some of the
// pieces screw up the Graphics2D when passed it... The advantage to doing
// it this way is that we create only one BufferedImage instead of two.
final BufferedImage dst =
ImageUtils.createCompatibleTranslucentImage(w, h);
final Graphics2D g = dst.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// paint the rectangle occupied by the piece at specified alpha
g.setColor(new Color(0xff, 0xff, 0xff, CURSOR_ALPHA));
g.fillRect(0, 0, w, h);
// feather outwards
for (int f = 0; f < b; ++f) {
final int alpha = CURSOR_ALPHA * (f + 1) / b;
g.setColor(new Color(0xff, 0xff, 0xff, alpha));
g.drawRect(f, f, w-2*f, h-2*f);
}
// paint in the source image
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN));
g.drawImage(src, 0, 0, null);
g.dispose();
return dst;
}
// DRAG GESTURE LISTENER INTERFACE
// EVENT uses SCALED, DRAG-SOURCE coordinate system.
// PIECE uses SCALED, OWNER (arbitrary) coordinate system
/** Fires after user begins moving the mouse several pixels over a map. */
public void dragGestureRecognized(DragGestureEvent dge) {
try {
beginDragging(dge);
}
// FIXME: Fix by replacing AWT Drag 'n Drop with Swing DnD.
// Catch and ignore spurious DragGestures
catch (InvalidDnDOperationException e) {
}
}
protected Point dragGestureRecognizedPrep(DragGestureEvent dge) {
// Ensure the user has dragged on a counter before starting the drag.
final DragBuffer db = DragBuffer.getBuffer();
if (db.isEmpty()) return null;
// Remove any Immovable pieces from the DragBuffer that were
// selected in a selection rectangle, unless they are being
// dragged from a piece palette (i.e., getMap() == null).
final List<GamePiece> pieces = new ArrayList<GamePiece>();
for (PieceIterator i = db.getIterator();
i.hasMoreElements(); pieces.add(i.nextPiece()));
for (GamePiece piece : pieces) {
if (piece.getMap() != null &&
Boolean.TRUE.equals(piece.getProperty(Properties.NON_MOVABLE))) {
db.remove(piece);
}
}
// Bail out if this leaves no pieces to drag.
if (db.isEmpty()) return null;
final GamePiece piece = db.getIterator().nextPiece();
final Map map = dge.getComponent() instanceof Map.View ?
((Map.View) dge.getComponent()).getMap() : null;
final Point mousePosition = (map == null)
? dge.getDragOrigin()
: map.componentCoordinates(dge.getDragOrigin());
Point piecePosition = (map == null)
? piece.getPosition()
: map.componentCoordinates(piece.getPosition());
// If DragBuffer holds a piece with invalid coordinates (for example, a
// card drawn from a deck), drag from center of piece
if (piecePosition.x <= 0 || piecePosition.y <= 0) {
piecePosition = mousePosition;
}
// Account for offset of piece within stack
// We do this even for un-expanded stacks, since the offset can
// still be significant if the stack is large
dragPieceOffCenterZoom = map == null ? 1.0 : map.getZoom();
if (piece.getParent() != null && map != null) {
final Point offset = piece.getParent()
.getStackMetrics()
.relativePosition(piece.getParent(), piece);
piecePosition.translate(
(int) Math.round(offset.x * dragPieceOffCenterZoom),
(int) Math.round(offset.y * dragPieceOffCenterZoom));
}
// dragging from UL results in positive offsets
originalPieceOffsetX = piecePosition.x - mousePosition.x;
originalPieceOffsetY = piecePosition.y - mousePosition.y;
dragWin = dge.getComponent();
drawWin = null;
dropWin = null;
return mousePosition;
}
protected void beginDragging(DragGestureEvent dge) {
// this call is needed to instantiate the boundingBox object
final BufferedImage bImage = makeDragImage(dragPieceOffCenterZoom);
final Point dragPointOffset = new Point(
getOffsetMult() * (boundingBox.x + currentPieceOffsetX - EXTRA_BORDER),
getOffsetMult() * (boundingBox.y + currentPieceOffsetY - EXTRA_BORDER)
);
dge.startDrag(
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR),
bImage,
dragPointOffset,
new StringSelection(""),
this
);
dge.getDragSource().addDragSourceMotionListener(this);
}
// DRAG SOURCE LISTENER INTERFACE
public void dragDropEnd(DragSourceDropEvent e) {
final DragSource ds = e.getDragSourceContext().getDragSource();
ds.removeDragSourceMotionListener(this);
}
public void dragEnter(DragSourceDragEvent e) {}
public void dragExit(DragSourceEvent e) {}
public void dragOver(DragSourceDragEvent e) {}
public void dropActionChanged(DragSourceDragEvent e) {}
// DRAG SOURCE MOTION LISTENER INTERFACE
// EVENT uses UNSCALED, SCREEN coordinate system
// Used to check for real mouse movement.
// Warning: dragMouseMoved fires 8 times for each point on development
// system (Win2k)
protected Point lastDragLocation = new Point();
/** Moves cursor after mouse */
abstract public void dragMouseMoved(DragSourceDragEvent e);
// DROP TARGET INTERFACE
// EVENT uses UNSCALED, DROP-TARGET coordinate system
/** switches current drawWin when mouse enters a new DropTarget */
public void dragEnter(DropTargetDragEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dragEnter(e);
}
/**
* Last event of the drop operation. We adjust the drop point for
* off-center drag, remove the cursor, and pass the event along
* listener chain.
*/
public void drop(DropTargetDropEvent e) {
// EVENT uses UNSCALED, DROP-TARGET coordinate system
e.getLocation().translate(currentPieceOffsetX, currentPieceOffsetY);
final DropTargetListener forward = getListener(e);
if (forward != null) forward.drop(e);
}
/** ineffectual. Passes event along listener chain */
public void dragExit(DropTargetEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dragExit(e);
}
/** ineffectual. Passes event along listener chain */
public void dragOver(DropTargetDragEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dragOver(e);
}
/** ineffectual. Passes event along listener chain */
public void dropActionChanged(DropTargetDragEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dropActionChanged(e);
}
}
/**
* Implements a psudo-cursor that follows the mouse cursor when user
* drags gamepieces. Supports map zoom by resizing cursor when it enters
* a drop target of type Map.View.
*
* @author Jim Urbas
* @version 0.4.2
*
*/
static public class DragHandlerNoImage extends AbstractDragHandler {
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
final Point mousePosition = dragGestureRecognizedPrep(dge);
if (mousePosition == null) return;
makeDragCursor(dragPieceOffCenterZoom);
setDrawWinToOwnerOf(dragWin);
SwingUtilities.convertPointToScreen(mousePosition, drawWin);
moveDragCursor(mousePosition.x, mousePosition.y);
super.dragGestureRecognized(dge);
}
protected int getOffsetMult() {
return 1;
}
@Override
public void dragDropEnd(DragSourceDropEvent e) {
removeDragCursor();
super.dragDropEnd(e);
}
public void dragMouseMoved(DragSourceDragEvent e) {
if (!e.getLocation().equals(lastDragLocation)) {
lastDragLocation = e.getLocation();
moveDragCursor(e.getX(), e.getY());
if (dragCursor != null && !dragCursor.isVisible()) {
dragCursor.setVisible(true);
}
}
}
public void dragEnter(DropTargetDragEvent e) {
final Component newDropWin = e.getDropTargetContext().getComponent();
if (newDropWin != dropWin) {
final double newZoom = newDropWin instanceof Map.View
? ((Map.View) newDropWin).getMap().getZoom() : 1.0;
if (Math.abs(newZoom - dragCursorZoom) > 0.01) {
makeDragCursor(newZoom);
}
setDrawWinToOwnerOf(e.getDropTargetContext().getComponent());
dropWin = newDropWin;
}
super.dragEnter(e);
}
public void drop(DropTargetDropEvent e) {
removeDragCursor();
super.drop(e);
}
}
/** Implementation of AbstractDragHandler when DragImage is supported by JRE
*
* @Author Pieter Geerkens
*/
static public class DragHandler extends AbstractDragHandler {
public void dragGestureRecognized(DragGestureEvent dge) {
if (dragGestureRecognizedPrep(dge) == null) return;
super.dragGestureRecognized(dge);
}
protected int getOffsetMult() {
return -1;
}
public void dragMouseMoved(DragSourceDragEvent e) {}
}
static public class DragHandlerMacOSX extends DragHandler {
@Override
protected int getOffsetMult() {
return 1;
}
}
}
|
package VASSAL.build.module.map;
import java.awt.Component;
import java.awt.Image;
import java.awt.Point;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.KeyStroke;
import VASSAL.build.AbstractBuildable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.command.NullCommand;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.counters.BoundsTracker;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.Decorator;
import VASSAL.counters.DragBuffer;
import VASSAL.counters.EventFilter;
import VASSAL.counters.GamePiece;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceCloner;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceIterator;
import VASSAL.counters.PieceSorter;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.imageop.Op;
/**
* This is a MouseListener that moves pieces onto a Map window
*/
public class PieceMover extends AbstractBuildable
implements MouseListener,
GameComponent,
Comparator<GamePiece> {
/** The Preferences key for autoreporting moves. */
public static final String AUTO_REPORT = "autoReport"; //$NON-NLS-1$
public static final String NAME = "name";
public static final String HOTKEY = "hotkey";
protected Map map;
protected Point dragBegin;
protected GamePiece dragging;
protected LaunchButton markUnmovedButton;
protected String markUnmovedText;
protected String markUnmovedIcon;
public static final String ICON_NAME = "icon"; //$NON-NLS-1$
protected String iconName;
// Selects drag target from mouse click on the Map
protected PieceFinder dragTargetSelector;
// Selects piece to merge with at the drop destination
protected PieceFinder dropTargetSelector;
// Processes drag target after having been selected
protected PieceVisitorDispatcher selectionProcessor;
protected Comparator<GamePiece> pieceSorter = new PieceSorter();
public void addTo(Buildable b) {
dragTargetSelector = createDragTargetSelector();
dropTargetSelector = createDropTargetSelector();
selectionProcessor = createSelectionProcessor();
map = (Map) b;
map.addLocalMouseListener(this);
GameModule.getGameModule().getGameState().addGameComponent(this);
map.setDragGestureListener(DragHandler.getTheDragHandler());
map.setPieceMover(this);
setAttribute(Map.MARK_UNMOVED_TEXT,
map.getAttributeValueString(Map.MARK_UNMOVED_TEXT));
setAttribute(Map.MARK_UNMOVED_ICON,
map.getAttributeValueString(Map.MARK_UNMOVED_ICON));
}
protected MovementReporter createMovementReporter(Command c) {
return new MovementReporter(c);
}
/**
* When the user completes a drag-drop operation, the pieces being
* dragged will either be combined with an existing piece on the map
* or else placed on the map without stack. This method returns a
* {@link PieceFinder} instance that determines which {@link GamePiece}
* (if any) to combine the being-dragged pieces with.
*
* @return
*/
protected PieceFinder createDropTargetSelector() {
return new PieceFinder.Movable() {
public Object visitDeck(Deck d) {
final Point pos = d.getPosition();
final Point p = new Point(pt.x - pos.x, pt.y - pos.y);
if (d.getShape().contains(p)) {
return d;
}
else {
return null;
}
}
public Object visitDefault(GamePiece piece) {
GamePiece selected = null;
if (this.map.getStackMetrics().isStackingEnabled() &&
this.map.getPieceCollection().canMerge(dragging, piece)) {
if (this.map.isLocationRestricted(pt)) {
final Point snap = this.map.snapTo(pt);
if (piece.getPosition().equals(snap)) {
selected = piece;
}
}
else {
selected = (GamePiece) super.visitDefault(piece);
}
}
if (selected != null &&
DragBuffer.getBuffer().contains(selected) &&
selected.getParent() != null &&
selected.getParent().topPiece() == selected) {
selected = null;
}
return selected;
}
public Object visitStack(Stack s) {
GamePiece selected = null;
if (this.map.getStackMetrics().isStackingEnabled() &&
this.map.getPieceCollection().canMerge(dragging, s) &&
!DragBuffer.getBuffer().contains(s) &&
s.topPiece() != null) {
if (this.map.isLocationRestricted(pt) && !s.isExpanded()) {
if (s.getPosition().equals(this.map.snapTo(pt))) {
selected = s;
}
}
else {
selected = (GamePiece) super.visitStack(s);
}
}
return selected;
}
};
}
/**
* When the user clicks on the map, a piece from the map is selected by
* the dragTargetSelector. What happens to that piece is determined by
* the {@link PieceVisitorDispatcher} instance returned by this method.
* The default implementation does the following: If a Deck, add the top
* piece to the drag buffer If a stack, add it to the drag buffer.
* Otherwise, add the piece and any other multi-selected pieces to the
* drag buffer.
*
* @see #createDragTargetSelector
* @return
*/
protected PieceVisitorDispatcher createSelectionProcessor() {
return new DeckVisitorDispatcher(new DeckVisitor() {
public Object visitDeck(Deck d) {
DragBuffer.getBuffer().clear();
for (PieceIterator it = d.drawCards(); it.hasMoreElements();) {
DragBuffer.getBuffer().add(it.nextPiece());
}
return null;
}
public Object visitStack(Stack s) {
DragBuffer.getBuffer().clear();
// RFE 1629255 - Only add selected pieces within the stack to the DragBuffer
// Add whole stack if all pieces are selected - better drag cursor
int selectedCount = 0;
for (int i = 0; i < s.getPieceCount(); i++) {
if (Boolean.TRUE.equals(s.getPieceAt(i)
.getProperty(Properties.SELECTED))) {
selectedCount++;
}
}
if (((Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS)).booleanValue() || s.getPieceCount() == 1 || s.getPieceCount() == selectedCount) {
DragBuffer.getBuffer().add(s);
}
else {
for (int i = 0; i < s.getPieceCount(); i++) {
final GamePiece p = s.getPieceAt(i);
if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
DragBuffer.getBuffer().add(p);
}
}
}
// End RFE 1629255
if (KeyBuffer.getBuffer().containsChild(s)) {
// If clicking on a stack with a selected piece, put all selected
// pieces in other stacks into the drag buffer
KeyBuffer.getBuffer().sort(PieceMover.this);
for (Iterator<GamePiece> i =
KeyBuffer.getBuffer().getPiecesIterator(); i.hasNext();) {
final GamePiece piece = i.next();
if (piece.getParent() != s) {
DragBuffer.getBuffer().add(piece);
}
}
}
return null;
}
public Object visitDefault(GamePiece selected) {
DragBuffer.getBuffer().clear();
if (KeyBuffer.getBuffer().contains(selected)) {
// If clicking on a selected piece, put all selected pieces into the
// drag buffer
KeyBuffer.getBuffer().sort(PieceMover.this);
for (Iterator<GamePiece> i =
KeyBuffer.getBuffer().getPiecesIterator(); i.hasNext();) {
DragBuffer.getBuffer().add(i.next());
}
}
else {
DragBuffer.getBuffer().clear();
DragBuffer.getBuffer().add(selected);
}
return null;
}
});
}
/**
* Returns the {@link PieceFinder} instance that will select a
* {@link GamePiece} for processing when the user clicks on the map.
* The default implementation is to return the first piece whose shape
* contains the point clicked on.
*
* @return
*/
protected PieceFinder createDragTargetSelector() {
return new PieceFinder.Movable() {
public Object visitDeck(Deck d) {
final Point pos = d.getPosition();
final Point p = new Point(pt.x - pos.x, pt.y - pos.y);
if (d.boundingBox().contains(p) && d.getPieceCount() > 0) {
return d;
}
else {
return null;
}
}
};
}
public void setup(boolean gameStarting) {
if (gameStarting) {
initButton();
}
}
public Command getRestoreCommand() {
return null;
}
private Image loadIcon(String name) {
if (name == null || name.length() == 0) return null;
return Op.load(name).getImage();
}
protected void initButton() {
final String value = getMarkOption();
if (GlobalOptions.PROMPT.equals(value)) {
BooleanConfigurer config = new BooleanConfigurer(
Map.MARK_MOVED, "Mark Moved Pieces", Boolean.TRUE);
GameModule.getGameModule().getPrefs().addOption(config);
}
if (!GlobalOptions.NEVER.equals(value)) {
if (markUnmovedButton == null) {
final ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
final GamePiece[] p = map.getAllPieces();
final Command c = new NullCommand();
for (int i = 0; i < p.length; ++i) {
c.append(markMoved(p[i], false));
}
GameModule.getGameModule().sendAndLog(c);
map.repaint();
}
};
markUnmovedButton =
new LaunchButton("", NAME, HOTKEY, Map.MARK_UNMOVED_ICON, al);
Image img = null;
if (iconName != null && iconName.length() > 0) {
img = loadIcon(iconName);
if (img != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, iconName);
}
}
if (img == null) {
img = loadIcon(markUnmovedIcon);
if (img != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, markUnmovedIcon);
}
}
markUnmovedButton.setAlignmentY(0.0F);
markUnmovedButton.setText(markUnmovedText);
markUnmovedButton.setToolTipText(
map.getAttributeValueString(Map.MARK_UNMOVED_TOOLTIP));
map.getToolBar().add(markUnmovedButton);
}
}
else if (markUnmovedButton != null) {
map.getToolBar().remove(markUnmovedButton);
markUnmovedButton = null;
}
}
private String getMarkOption() {
String value = map.getAttributeValueString(Map.MARK_MOVED);
if (value == null) {
value = GlobalOptions.getInstance()
.getAttributeValueString(GlobalOptions.MARK_MOVED);
}
return value;
}
public String[] getAttributeNames() {
return new String[]{ICON_NAME};
}
public String getAttributeValueString(String key) {
return ICON_NAME.equals(key) ? iconName : null;
}
public void setAttribute(String key, Object value) {
if (ICON_NAME.equals(key)) {
iconName = (String) value;
}
else if (Map.MARK_UNMOVED_TEXT.equals(key)) {
if (markUnmovedButton != null) {
markUnmovedButton.setAttribute(NAME, value);
}
markUnmovedText = (String) value;
}
else if (Map.MARK_UNMOVED_ICON.equals(key)) {
if (markUnmovedButton != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, value);
}
markUnmovedIcon = (String) value;
}
}
protected boolean isMultipleSelectionEvent(MouseEvent e) {
return e.isShiftDown();
}
/** Invoked just before a piece is moved */
protected Command movedPiece(GamePiece p, Point loc) {
setOldLocation(p);
Command c = null;
if (!loc.equals(p.getPosition())) {
c = markMoved(p, true);
}
if (p.getParent() != null) {
final Command removedCommand = p.getParent().pieceRemoved(p);
c = c == null ? removedCommand : c.append(removedCommand);
}
return c;
}
protected void setOldLocation(GamePiece p) {
if (p instanceof Stack) {
for (int i = 0; i < ((Stack) p).getPieceCount(); i++) {
Decorator.setOldProperties(((Stack) p).getPieceAt(i));
}
}
else Decorator.setOldProperties(p);
}
public Command markMoved(GamePiece p, boolean hasMoved) {
if (GlobalOptions.NEVER.equals(getMarkOption())) {
hasMoved = false;
}
Command c = new NullCommand();
if (!hasMoved || shouldMarkMoved()) {
if (p instanceof Stack) {
for (Iterator<GamePiece> i = ((Stack) p).getPiecesIterator();
i.hasNext();) {
c.append(markMoved(i.next(), hasMoved));
}
}
else if (p.getProperty(Properties.MOVED) != null) {
if (p.getId() != null) {
final ChangeTracker comm = new ChangeTracker(p);
p.setProperty(Properties.MOVED,
hasMoved ? Boolean.TRUE : Boolean.FALSE);
c = comm.getChangeCommand();
}
}
}
return c;
}
protected boolean shouldMarkMoved() {
final String option = getMarkOption();
if (GlobalOptions.ALWAYS.equals(option)) {
return true;
}
else if (GlobalOptions.NEVER.equals(option)) {
return false;
}
else {
return Boolean.TRUE.equals(
GameModule.getGameModule().getPrefs().getValue(Map.MARK_MOVED));
}
}
/**
* Moves pieces in DragBuffer to point p by generating a Command for
* each element in DragBuffer
*
* @param map
* Map
* @param p
* Point mouse released
*/
public Command movePieces(Map map, Point p) {
final List<GamePiece> allDraggedPieces = new ArrayList<GamePiece>();
final PieceIterator it = DragBuffer.getBuffer().getIterator();
if (!it.hasMoreElements()) return null;
Point offset = null;
Command comm = new NullCommand();
final BoundsTracker tracker = new BoundsTracker();
// Map of Point->List<GamePiece> of pieces to merge with at a given
// location. There is potentially one piece for each Game Piece Layer.
final HashMap<Point,List<GamePiece>> mergeTargets =
new HashMap<Point,List<GamePiece>>();
while (it.hasMoreElements()) {
dragging = it.nextPiece();
tracker.addPiece(dragging);
/*
* Take a copy of the pieces in dragging.
* If it is a stack, it is cleared by the merging process.
*/
final ArrayList<GamePiece> draggedPieces = new ArrayList<GamePiece>(0);
if (dragging instanceof Stack) {
int size = ((Stack) dragging).getPieceCount();
for (int i = 0; i < size; i++) {
draggedPieces.add(((Stack) dragging).getPieceAt(i));
}
}
else {
draggedPieces.add(dragging);
}
if (offset != null) {
p = new Point(dragging.getPosition().x + offset.x,
dragging.getPosition().y + offset.y);
}
List<GamePiece> mergeCandidates = mergeTargets.get(p);
GamePiece mergeWith = null;
// Find an already-moved piece that we can merge with at the destination
// point
if (mergeCandidates != null) {
for (int i = 0, n = mergeCandidates.size(); i < n; ++i) {
final GamePiece candidate = mergeCandidates.get(i);
if (map.getPieceCollection().canMerge(candidate, dragging)) {
mergeWith = candidate;
mergeCandidates.set(i, dragging);
break;
}
}
}
// Now look for an already-existing piece at the destination point
if (mergeWith == null) {
mergeWith = map.findAnyPiece(p, dropTargetSelector);
if (mergeWith == null && !Boolean.TRUE.equals(
dragging.getProperty(Properties.IGNORE_GRID))) {
p = map.snapTo(p);
}
if (offset == null) {
offset = new Point(p.x - dragging.getPosition().x,
p.y - dragging.getPosition().y);
}
if (mergeWith != null && map.getStackMetrics().isStackingEnabled()) {
mergeCandidates = new ArrayList<GamePiece>();
mergeCandidates.add(dragging);
mergeCandidates.add(mergeWith);
mergeTargets.put(p, mergeCandidates);
}
}
if (mergeWith == null) {
comm = comm.append(movedPiece(dragging, p));
comm = comm.append(map.placeAt(dragging, p));
if (!(dragging instanceof Stack) &&
!Boolean.TRUE.equals(dragging.getProperty(Properties.NO_STACK))) {
final Stack parent = map.getStackMetrics().createStack(dragging);
if (parent != null) {
comm = comm.append(map.placeAt(parent, p));
}
}
}
else {
// Do not add pieces to the Deck that are Obscured to us, or that
// the Deck does not want to contain. Removing them from the
// draggedPieces list will cause them to be left behind where the
// drag started. NB. Pieces that have been dragged from a face-down
// Deck will be be Obscued to us, but will be Obscured by the dummy
// user Deck.NO_USER
if (mergeWith instanceof Deck) {
final ArrayList<GamePiece> newList = new ArrayList<GamePiece>(0);
for (GamePiece piece : draggedPieces) {
if (((Deck) mergeWith).mayContain(piece)) {
final boolean isObscuredToMe = Boolean.TRUE.equals(piece.getProperty(Properties.OBSCURED_TO_ME));
if (!isObscuredToMe || (isObscuredToMe && Deck.NO_USER.equals(piece.getProperty(Properties.OBSCURED_BY)))) {
newList.add(piece);
}
}
}
if (newList.size() != draggedPieces.size()) {
draggedPieces.clear();
for (GamePiece piece : newList) {
draggedPieces.add(piece);
}
}
}
// Add the remaining dragged counters to the target.
// If mergeWith is a single piece (not a Stack), then we are merging
// into an expanded Stack and the merge order must be reversed to
// maintain the order of the merging pieces.
if (mergeWith instanceof Stack) {
for (int i = 0; i < draggedPieces.size(); ++i) {
comm = comm.append(movedPiece(draggedPieces.get(i), mergeWith.getPosition()));
comm = comm.append(map.getStackMetrics().merge(mergeWith, draggedPieces.get(i)));
}
}
else {
for (int i = draggedPieces.size()-1; i >= 0; --i) {
comm = comm.append(movedPiece(draggedPieces.get(i), mergeWith.getPosition()));
comm = comm.append(map.getStackMetrics().merge(mergeWith, draggedPieces.get(i)));
}
}
}
for (GamePiece piece : draggedPieces) {
KeyBuffer.getBuffer().add(piece);
}
// Record each individual piece moved
for (GamePiece piece : draggedPieces) {
allDraggedPieces.add(piece);
}
tracker.addPiece(dragging);
}
if (GlobalOptions.getInstance().autoReportEnabled()) {
final Command report = createMovementReporter(comm).getReportCommand().append(new MovementReporter.HiddenMovementReporter(comm).getReportCommand());
report.execute();
comm = comm.append(report);
}
// Apply key after move to each moved piece
if (map.getMoveKey() != null) {
applyKeyAfterMove(allDraggedPieces, comm, map.getMoveKey());
}
tracker.repaint();
return comm;
}
protected void applyKeyAfterMove(List<GamePiece> pieces,
Command comm, KeyStroke key) {
for (GamePiece piece : pieces) {
if (piece.getProperty(Properties.SNAPSHOT) == null) {
piece.setProperty(Properties.SNAPSHOT,
PieceCloner.getInstance().clonePiece(piece));
}
comm.append(piece.keyEvent(key));
}
}
/**
* This listener is used for faking drag-and-drop on Java 1.1 systems
*
* @param e
*/
public void mousePressed(MouseEvent e) {
if (canHandleEvent(e)) {
selectMovablePieces(e);
}
}
/** Place the clicked-on piece into the {@link DragBuffer} */
protected void selectMovablePieces(MouseEvent e) {
final GamePiece p = map.findPiece(e.getPoint(), dragTargetSelector);
dragBegin = e.getPoint();
if (p != null) {
final EventFilter filter =
(EventFilter) p.getProperty(Properties.MOVE_EVENT_FILTER);
if (filter == null || !filter.rejectEvent(e)) {
selectionProcessor.accept(p);
}
else {
DragBuffer.getBuffer().clear();
}
}
else {
DragBuffer.getBuffer().clear();
}
// show/hide selection boxes
map.repaint();
}
/** @deprecated Use {@link #selectMovablePieces(MouseEvent)}. */
@Deprecated
protected void selectMovablePieces(Point point) {
final GamePiece p = map.findPiece(point, dragTargetSelector);
dragBegin = point;
selectionProcessor.accept(p);
// show/hide selection boxes
map.repaint();
}
protected boolean canHandleEvent(MouseEvent e) {
return !e.isShiftDown() &&
!e.isControlDown() &&
!e.isMetaDown() &&
e.getClickCount() < 2 &&
!e.isConsumed();
}
/**
* Return true if this point is "close enough" to the point at which
* the user pressed the mouse to be considered a mouse click (such
* that no moves are done)
*/
public boolean isClick(Point pt) {
boolean isClick = false;
if (dragBegin != null) {
final Board b = map.findBoard(pt);
boolean useGrid = b != null && b.getGrid() != null;
if (useGrid) {
final PieceIterator it = DragBuffer.getBuffer().getIterator();
final GamePiece dragging = it.hasMoreElements() ? it.nextPiece() : null;
useGrid =
dragging != null &&
!Boolean.TRUE.equals(dragging.getProperty(Properties.IGNORE_GRID)) &&
(dragging.getParent() == null || !dragging.getParent().isExpanded());
}
if (useGrid) {
if (map.equals(DragBuffer.getBuffer().getFromMap())) {
if (map.snapTo(pt).equals(map.snapTo(dragBegin))) {
isClick = true;
}
}
}
else {
if (Math.abs(pt.x - dragBegin.x) <= 5 &&
Math.abs(pt.y - dragBegin.y) <= 5) {
isClick = true;
}
}
}
return isClick;
}
public void mouseReleased(MouseEvent e) {
if (canHandleEvent(e)) {
if (!isClick(e.getPoint())) {
performDrop(e.getPoint());
}
}
dragBegin = null;
map.getView().setCursor(null);
}
protected void performDrop(Point p) {
final Command move = movePieces(map, p);
GameModule.getGameModule().sendAndLog(move);
if (move != null) {
DragBuffer.getBuffer().clear();
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
/**
* Implement Comparator to sort the contents of the drag buffer before
* completing the drag. This sorts the contents to be in the same order
* as the pieces were in their original parent stack.
*/
public int compare(GamePiece p1, GamePiece p2) {
return pieceSorter.compare(p1, p2);
}
// We force the loading of these classes because otherwise they would
// be loaded when the user initiates the first drag, which makes the
// start of the drag choppy.
static {
try {
Class.forName(MovementReporter.class.getName(),
true, MovementReporter.class.getClassLoader());
Class.forName(KeyBuffer.class.getName(),
true, KeyBuffer.class.getClassLoader());
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e); // impossible
}
}
/** @deprecated Use {@link DragHandler} instead. */
@Deprecated
static public class AbstractDragHandler extends VASSAL.build.module.map.DragHandler {
private VASSAL.build.module.map.DragHandler theRealDragHandler =
VASSAL.build.module.map.DragHandler.getTheDragHandler();
static private final AbstractDragHandler shim = new AbstractDragHandler();
static public AbstractDragHandler getTheDragHandler() {
return shim;
}
static public void setTheDragHandler(AbstractDragHandler myHandler) {
VASSAL.build.module.map.DragHandler.setTheDragHandler(shim);
shim.theRealDragHandler = myHandler;
}
static public DropTarget makeDropTarget(Component theComponent, int dndContents, DropTargetListener dropTargetListener) {
return VASSAL.build.module.map.DragHandler.makeDropTarget(
theComponent, dndContents, dropTargetListener
);
}
static public void removeDropTarget(Component theComponent) {
VASSAL.build.module.map.DragHandler.removeDropTarget(theComponent);
}
protected int getOffsetMult() {
return theRealDragHandler.getOffsetMult();
}
public void setDrawWinToOwnerOf(Component newDropWin) {
theRealDragHandler.setDrawWinToOwnerOf(newDropWin);
}
public void dragGestureRecognized(DragGestureEvent dge) {
theRealDragHandler.dragGestureRecognized(dge);
}
public void dragDropEnd(DragSourceDropEvent e) {
theRealDragHandler.dragDropEnd(e);
}
public void dragEnter(DragSourceDragEvent e) {
theRealDragHandler.dragEnter(e);
}
public void dragExit(DragSourceEvent e) {
theRealDragHandler.dragExit(e);
}
public void dragOver(DragSourceDragEvent e) {
theRealDragHandler.dragOver(e);
}
public void dropActionChanged(DragSourceDragEvent e) {
theRealDragHandler.dropActionChanged(e);
}
public void dragMouseMoved(DragSourceDragEvent e) {
theRealDragHandler.dragMouseMoved(e);
}
public void dragEnter(DropTargetDragEvent e) {
theRealDragHandler.dragEnter(e);
}
public void drop(DropTargetDropEvent e) {
theRealDragHandler.drop(e);
}
public void dragExit(DropTargetEvent e) {
theRealDragHandler.dragExit(e);
}
public void dragOver(DropTargetDragEvent e) {
theRealDragHandler.dragOver(e);
}
public void dropActionChanged(DropTargetDragEvent e) {
theRealDragHandler.dropActionChanged(e);
}
}
/** @deprecated Use {@link DragHandlerNoImage} instead. */
@Deprecated
static public class DragHandlerNoImage extends AbstractDragHandler {
public DragHandlerNoImage() {
AbstractDragHandler.setTheDragHandler(new DragHandlerNonNative());
}
}
/** @deprecated Use {@link DragHandlerNative} instead. */
@Deprecated
static public class DragHandler extends AbstractDragHandler {
public DragHandler() {
AbstractDragHandler.setTheDragHandler(new DragHandlerNative());
}
}
/** @deprecated Use {@link DragHandlerImageMacOSX} instead. */
@Deprecated
static public class DragHandlerMacOSX extends AbstractDragHandler {
public DragHandlerMacOSX() {
AbstractDragHandler.setTheDragHandler(new DragHandlerNativeMacOSX());
}
}
}
|
package VASSAL.launch;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipFile;
import javax.swing.AbstractAction;
import javax.swing.SwingUtilities;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.SystemUtils;
import org.jdesktop.swingworker.SwingWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import VASSAL.Info;
import VASSAL.build.module.ExtensionsManager;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.metadata.AbstractMetaData;
import VASSAL.build.module.metadata.MetaDataFactory;
import VASSAL.build.module.metadata.ModuleMetaData;
import VASSAL.configure.DirectoryConfigurer;
import VASSAL.preferences.Prefs;
import VASSAL.preferences.ReadOnlyPrefs;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.ThrowableUtils;
import VASSAL.tools.WarningDialog;
import VASSAL.tools.concurrent.FutureUtils;
import VASSAL.tools.concurrent.listener.EventListener;
import VASSAL.tools.filechooser.FileChooser;
import VASSAL.tools.filechooser.ModuleFileFilter;
import VASSAL.tools.io.IOUtils;
import VASSAL.tools.io.ProcessLauncher;
import VASSAL.tools.io.ProcessWrapper;
import VASSAL.tools.ipc.IPCMessage;
import VASSAL.tools.ipc.IPCMessenger;
import VASSAL.tools.ipc.SimpleIPCMessage;
import VASSAL.tools.lang.MemoryUtils;
/**
*
* The base class for {@link Action}s which launch processes from the
* {@link ModuleManagerWindow}.
*
* @author Joel Uckelman
* @since 3.1.0
*/
public abstract class AbstractLaunchAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private static final Logger logger =
LoggerFactory.getLogger(AbstractLaunchAction.class);
// memory-related constants
protected static final int PHYS_MEMORY;
protected static final int DEFAULT_INITIAL_HEAP = 256;
protected static final int DEFAULT_MAXIMUM_HEAP = 512;
protected static final int FAILSAFE_INITIAL_HEAP = 64;
protected static final int FAILSAFE_MAXIMUM_HEAP = 128;
static {
// determine how much physical RAM this machine has
final long physMemoryBytes = MemoryUtils.getPhysicalMemory();
PHYS_MEMORY = physMemoryBytes < 0 ? -1 : (int)(physMemoryBytes >> 20);
}
protected final Window window;
protected final String entryPoint;
protected final LaunchRequest lr;
protected static final Set<File> editing =
Collections.synchronizedSet(new HashSet<File>());
protected static final Map<File,Integer> using =
Collections.synchronizedMap(new HashMap<File,Integer>());
/*
protected static final List<ObjectOutputStream> children =
Collections.synchronizedList(new ArrayList<ObjectOutputStream>());
*/
protected static final List<IPCMessenger> children =
Collections.synchronizedList(new ArrayList<IPCMessenger>());
protected static final AtomicInteger nextId = new AtomicInteger(1);
public AbstractLaunchAction(String name, Window window,
String entryPoint, LaunchRequest lr) {
super(name);
this.window = window;
this.entryPoint = entryPoint;
this.lr = lr;
}
/**
* @param file the file to check
* @return <code>true</code> iff the file is in use
*/
public static boolean isInUse(File file) {
return using.containsKey(file);
}
/**
* @param file the file to check
* @return <code>true</code> iff the file is being edited
*/
public static boolean isEditing(File file) {
return editing.contains(file);
}
/**
* Ask child processes to close.
*
* @return <code>true</code> iff all child processes will terminate
*/
public static boolean shutDown() {
ModuleManagerWindow.getInstance().toBack();
final List<Future<IPCMessage>> futures =
new ArrayList<Future<IPCMessage>>();
// must synchronize when iterating over a Collections.synchronizedList()
synchronized (children) {
for (IPCMessenger ipc : children) {
try {
futures.add(ipc.send(new Launcher.CloseRequest()));
}
catch (IOException e) {
// FIXME
e.printStackTrace();
}
}
}
// FIXME: not working!
for (Future<IPCMessage> f : futures) {
try {
if (f.get() instanceof Launcher.CloseReject) {
System.out.println("rejected!");
return false;
}
}
catch (ExecutionException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return true;
}
/** {@inheritDoc} */
public void actionPerformed(ActionEvent e) {
ModuleManagerWindow.getInstance().setWaitCursor(true);
getLaunchTask().execute();
}
protected abstract LaunchTask getLaunchTask();
protected File promptForFile() {
// prompt the user to pick a file
final FileChooser fc = FileChooser.createFileChooser(window,
(DirectoryConfigurer)
Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY));
addFileFilters(fc);
// loop until cancellation or we get an existing file
if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) {
lr.module = fc.getSelectedFile();
if (lr.module != null) {
if (lr.module.exists()) {
final AbstractMetaData metadata =
MetaDataFactory.buildMetaData(lr.module);
if (metadata == null || ! (metadata instanceof ModuleMetaData)) {
ErrorDialog.show(
"Error.invalid_vassal_module", lr.module.getAbsolutePath());
logger.error(
"-- Load of {} failed: Not a Vassal module",
lr.module.getAbsolutePath()
);
lr.module = null;
}
}
else {
lr.module = null;
}
// FIXME: do something to warn about nonexistant file
// FileNotFoundDialog.warning(window, lr.module);
}
}
return lr.module;
}
protected void addFileFilters(FileChooser fc) {
fc.addChoosableFileFilter(new ModuleFileFilter());
}
protected class LaunchTask extends SwingWorker<Void,Void> {
protected final int id = nextId.getAndIncrement();
// lr might be modified before the task is over, keep a local copy
protected final LaunchRequest lr =
new LaunchRequest(AbstractLaunchAction.this.lr);
protected ServerSocket serverSocket = null;
protected Socket clientSocket = null;
protected IPCMessenger ipc = null;
@Override
public Void doInBackground() throws InterruptedException,
IOException {
// FIXME: this should be in an abstract method and farmed out to subclasses
// send some basic information to the log
if (lr.module != null) {
logger.info("Loading module file {}", lr.module.getAbsolutePath());
// slice tiles for module
final String aname = lr.module.getAbsolutePath();
final ModuleMetaData meta = new ModuleMetaData(new ZipFile(aname));
final String hstr =
DigestUtils.shaHex(meta.getName() + "_" + meta.getVersion());
final File cdir = new File(Info.getConfDir(), "tiles/" + hstr);
final TilingHandler th = new TilingHandler(
aname,
cdir,
new Dimension(256, 256),
PHYS_MEMORY,
nextId.getAndIncrement()
);
try {
th.sliceTiles();
}
catch (CancellationException e) {
cancel(true);
return null;
}
// slice tiles for extensions
final ExtensionsManager mgr = new ExtensionsManager(lr.module);
for (File ext : mgr.getActiveExtensions()) {
final TilingHandler eth = new TilingHandler(
ext.getAbsolutePath(),
cdir,
new Dimension(256, 256),
PHYS_MEMORY,
nextId.getAndIncrement()
);
try {
eth.sliceTiles();
}
catch (CancellationException e) {
cancel(true);
return null;
}
}
}
if (lr.game != null) {
logger.info("Loading game file {}", lr.game.getAbsolutePath());
}
if (lr.importFile != null) {
logger.info(
"Importing module file {}",
lr.importFile.getAbsolutePath()
);
}
// end FIXME
// set default heap sizes
int initialHeap = DEFAULT_INITIAL_HEAP;
int maximumHeap = DEFAULT_MAXIMUM_HEAP;
String moduleName = null;
// FIXME: this should be in an abstract method and farmed out to subclasses,
// rather than a case structure for each kind of thing which may be loaded.
// find module-specific heap settings, if any
if (lr.module != null) {
final AbstractMetaData data = MetaDataFactory.buildMetaData(lr.module);
if (data == null) {
ErrorDialog.show(
"Error.invalid_vassal_file", lr.module.getAbsolutePath());
ModuleManagerWindow.getInstance().setWaitCursor(false);
return null;
}
if (data instanceof ModuleMetaData) {
moduleName = ((ModuleMetaData) data).getName();
// log the module name
logger.info("Loading module {}", moduleName);
// read module prefs
final ReadOnlyPrefs p = new ReadOnlyPrefs(moduleName);
// read initial heap size
initialHeap = getHeapSize(
p, GlobalOptions.INITIAL_HEAP, DEFAULT_INITIAL_HEAP);
// read maximum heap size
maximumHeap = getHeapSize(
p, GlobalOptions.MAXIMUM_HEAP, DEFAULT_MAXIMUM_HEAP);
}
}
else if (lr.importFile != null) {
final Prefs p = Prefs.getGlobalPrefs();
// read initial heap size
initialHeap = getHeapSize(
p, GlobalOptions.INITIAL_HEAP, DEFAULT_INITIAL_HEAP);
// read maximum heap size
maximumHeap = getHeapSize(
p, GlobalOptions.MAXIMUM_HEAP, DEFAULT_MAXIMUM_HEAP);
}
// end FIXME
// Heap size sanity checks: fall back to failsafe heap sizes in
// case the given initial or maximum heap is not usable.
// FIXME: The heap size messages are too nonspecific. They should
// differientiate between loading a module and importing a module,
// since the heap sizes are set in different places for those two
// actions.
// maximum heap must fit in physical RAM
if (maximumHeap > PHYS_MEMORY && PHYS_MEMORY > 0) {
initialHeap = FAILSAFE_INITIAL_HEAP;
maximumHeap = FAILSAFE_MAXIMUM_HEAP;
FutureUtils.wait(WarningDialog.show(
"Warning.maximum_heap_too_large",
FAILSAFE_MAXIMUM_HEAP
));
}
// maximum heap must be at least the failsafe size
else if (maximumHeap < FAILSAFE_MAXIMUM_HEAP) {
initialHeap = FAILSAFE_INITIAL_HEAP;
maximumHeap = FAILSAFE_MAXIMUM_HEAP;
FutureUtils.wait(WarningDialog.show(
"Warning.maximum_heap_too_small",
FAILSAFE_MAXIMUM_HEAP
));
}
// initial heap must be at least the failsafe size
else if (initialHeap < FAILSAFE_INITIAL_HEAP) {
initialHeap = FAILSAFE_INITIAL_HEAP;
maximumHeap = FAILSAFE_MAXIMUM_HEAP;
FutureUtils.wait(WarningDialog.show(
"Warning.initial_heap_too_small",
FAILSAFE_INITIAL_HEAP
));
}
// initial heap must be less than or equal to maximum heap
else if (initialHeap > maximumHeap) {
initialHeap = FAILSAFE_INITIAL_HEAP;
maximumHeap = FAILSAFE_MAXIMUM_HEAP;
FutureUtils.wait(WarningDialog.show(
"Warning.initial_heap_too_large",
FAILSAFE_INITIAL_HEAP
));
}
/*
final SignalServer ssrv = ModuleManager.getInstance().getSignalServer();
final int port = ssrv.getPort();
final SettableFuture<ObjectOutputStream> conn =
new SimpleFuture<ObjectOutputStream>();
final EventListener<ConnectionSignal> clistener =
new EventListener<ConnectionSignal>() {
public void receive(Object src, ConnectionSignal sig) {
if (sig.pid == id) {
ssrv.removeEventListener(ConnectionSignal.class, this);
conn.set(sig.out);
}
}
};
ssrv.addEventListener(ConnectionSignal.class, clistener);
*/
// create a socket for communicating which the child process
final InetAddress lo = InetAddress.getByName(null);
serverSocket = new ServerSocket(0, 0, lo);
final int port = serverSocket.getLocalPort();
// build the argument list
final ArrayList<String> al = new ArrayList<String>();
al.add(Info.javaBinPath);
al.add(""); // reserved for initial heap
al.add(""); // reserved for maximum heap
al.add("-DVASSAL.id=" + id); // instance id
al.add("-DVASSAL.port=" + port); // MM socket port
// pass on the user's home, if it's set
final String userHome = System.getProperty("user.home");
if (userHome != null) al.add("-Duser.home=" + userHome);
// set the classpath
al.add("-cp");
al.add(System.getProperty("java.class.path"));
if (SystemUtils.IS_OS_MAC_OSX) {
// set the MacOS X dock parameters
// use the module name for the dock if we found a module name
// FIXME: should "Unnamed module" be localized?
final String d_name = moduleName != null && moduleName.length() > 0
? moduleName : "Unnamed module";
// get the path to the app icon
final String d_icon = new File(Info.getBaseDir(),
"Contents/Resources/VASSAL.icns").getAbsolutePath();
al.add("-Xdock:name=" + d_name);
al.add("-Xdock:icon=" + d_icon);
// Quartz can cause font rendering problems; turn it off?
final Boolean disableQuartz =
(Boolean) Prefs.getGlobalPrefs().getValue(Prefs.DISABLE_QUARTZ);
al.add("-Dapple.awt.graphics.UseQuartz=" +
(Boolean.TRUE.equals(disableQuartz) ? "false" : "true")
);
}
else if (SystemUtils.IS_OS_WINDOWS) {
// Disable the 2D to Direct3D pipeline?
final Boolean disableD3d =
(Boolean) Prefs.getGlobalPrefs().getValue(Prefs.DISABLE_D3D);
if (Boolean.TRUE.equals(disableD3d)) {
al.add("-Dsun.java2d.d3d=false");
}
}
al.add(entryPoint);
al.addAll(Arrays.asList(lr.toArgs()));
final String[] args = al.toArray(new String[al.size()]);
// try to start a child process with the given heap sizes
args[1] = "-Xms" + initialHeap + "M";
args[2] = "-Xmx" + maximumHeap + "M";
ProcessWrapper proc = new ProcessLauncher().launch(args);
try {
proc.future.get(1000L, TimeUnit.MILLISECONDS);
}
catch (CancellationException e) {
cancel(true);
return null;
}
catch (ExecutionException e) {
logger.error("", e);
}
catch (TimeoutException e) {
// this is expected
}
// if launch failed, use conservative heap sizes
if (proc.future.isDone()) {
args[1] = "-Xms" + FAILSAFE_INITIAL_HEAP + "M";
args[2] = "-Xmx" + FAILSAFE_MAXIMUM_HEAP + "M";
proc = new ProcessLauncher().launch(args);
try {
proc.future.get(1000L, TimeUnit.MILLISECONDS);
}
catch (ExecutionException e) {
logger.error("", e);
}
catch (TimeoutException e) {
// this is expected
}
if (proc.future.isDone()) {
throw new IOException("failed to start child process");
}
else {
FutureUtils.wait(WarningDialog.show(
"Warning.maximum_heap_too_large",
FAILSAFE_MAXIMUM_HEAP
));
}
}
clientSocket = serverSocket.accept();
ipc = new IPCMessenger(clientSocket);
ipc.addEventListener(
NotifyOpenModuleOk.class,
new NotifyOpenModuleOkListener()
);
ipc.addEventListener(
NotifyNewModuleOk.class,
new NotifyNewModuleOkListener()
);
ipc.addEventListener(
NotifyImportModuleOk.class,
new NotifyImportModuleOkListener()
);
ipc.addEventListener(
NotifyOpenModuleFailed.class,
new NotifyOpenModuleFailedListener()
);
ipc.addEventListener(
NotifySaveFileOk.class,
new NotifySaveFileOkListener()
);
ipc.start();
children.add(ipc);
// block until the process ends
try {
proc.future.get();
}
catch (ExecutionException e) {
logger.error("", e);
}
return null;
}
protected int getHeapSize(ReadOnlyPrefs p, String key, int defaultHeap) {
// read heap size, if it exists
final String val = p.getStoredValue(key);
if (val == null) return defaultHeap;
try {
return Integer.parseInt(val);
}
catch (NumberFormatException ex) {
return -1;
}
}
protected int getHeapSize(Prefs p, String key, int defaultHeap) {
// read heap size, if it exists
final Object val = p.getValue(key);
if (val == null) return defaultHeap;
try {
return Integer.parseInt(val.toString());
}
catch (NumberFormatException ex) {
return -1;
}
}
@Override
protected void done() {
try {
get();
}
catch (CancellationException e) {
// this means that loading was cancelled
ModuleManagerWindow.getInstance().setWaitCursor(false);
}
catch (InterruptedException e) {
ErrorDialog.bug(e);
}
catch (ExecutionException e) {
// determine what kind of exception occurred
final Throwable c = e.getCause();
if (c instanceof IOException) {
ErrorDialog.showDetails(
e,
ThrowableUtils.getStackTrace(e),
"Error.socket_error"
);
}
else {
ErrorDialog.bug(e);
}
}
finally {
IOUtils.closeQuietly(clientSocket);
IOUtils.closeQuietly(serverSocket);
children.remove(ipc);
}
}
}
// Commands
protected abstract static class LaunchRequestMessage
extends SimpleIPCMessage {
protected final LaunchRequest lr;
public LaunchRequestMessage(LaunchRequest lr) {
this.lr = lr;
}
}
public static class NotifyOpenModuleOk extends LaunchRequestMessage {
private static final long serialVersionUID = 1L;
public NotifyOpenModuleOk(LaunchRequest lr) {
super(lr);
}
}
public static class NotifyNewModuleOk extends LaunchRequestMessage {
private static final long serialVersionUID = 1L;
public NotifyNewModuleOk(LaunchRequest lr) {
super(lr);
}
}
public static class NotifyImportModuleOk extends LaunchRequestMessage {
private static final long serialVersionUID = 1L;
public NotifyImportModuleOk(LaunchRequest lr) {
super(lr);
}
}
public static class NotifyOpenModuleFailed extends LaunchRequestMessage {
private static final long serialVersionUID = 1L;
public final Throwable thrown;
public NotifyOpenModuleFailed(LaunchRequest lr, Throwable thrown) {
super(lr);
this.thrown = thrown;
}
}
public static class NotifySaveFileOk extends SimpleIPCMessage {
private static final long serialVersionUID = 1L;
public final File file;
public NotifySaveFileOk(File file) {
this.file = file;
}
}
// Listeners
protected static class NotifyOpenModuleOkListener
implements EventListener<NotifyOpenModuleOk> {
public void receive(Object src, final NotifyOpenModuleOk msg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final ModuleManagerWindow mmw = ModuleManagerWindow.getInstance();
mmw.addModule(msg.lr.module);
mmw.setWaitCursor(false);
}
});
}
}
protected static class NotifyNewModuleOkListener
implements EventListener<NotifyNewModuleOk> {
public void receive(Object src, NotifyNewModuleOk msg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ModuleManagerWindow.getInstance().setWaitCursor(false);
}
});
}
}
protected static class NotifyImportModuleOkListener
implements EventListener<NotifyImportModuleOk> {
public void receive(Object src, NotifyImportModuleOk msg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ModuleManagerWindow.getInstance().setWaitCursor(false);
}
});
}
}
protected static class NotifyOpenModuleFailedListener
implements EventListener<NotifyOpenModuleFailed> {
public void receive(Object src, NotifyOpenModuleFailed msg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ModuleManagerWindow.getInstance().setWaitCursor(false);
}
});
ErrorDialog.showDetails(
msg.thrown,
ThrowableUtils.getStackTrace(msg.thrown),
"Error.module_load_failed",
msg.thrown.getMessage()
);
}
}
protected static class NotifySaveFileOkListener
implements EventListener<NotifySaveFileOk> {
public void receive(Object rc, final NotifySaveFileOk msg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ModuleManagerWindow.getInstance().update(msg.file);
}
});
}
}
}
|
package reciter.algorithm.cluster.similarity.clusteringstrategy.article;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reciter.algorithm.cluster.clusteringstrategy.article.AbstractClusteringStrategy;
import reciter.algorithm.cluster.model.ReCiterCluster;
import reciter.model.article.ReCiterArticle;
import reciter.model.article.ReCiterArticleGrant;
import reciter.model.article.ReCiterAuthor;
/**
* @author szd2013
* This class parses NIH grant identifiers for all articles in a standardized logic of Funding Agency-4 to 6 digit grant code. Then matches and form clusters.
* It also checks for transitive property matches as well.
*/
public class GrantFeatureClusteringStrategy extends AbstractClusteringStrategy {
private static final Logger slf4jLogger = LoggerFactory.getLogger(GrantFeatureClusteringStrategy.class);
@Override
public Map<Long, ReCiterCluster> cluster(List<ReCiterArticle> reCiterArticles) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<Long, ReCiterCluster> cluster(List<ReCiterArticle> reCiterArticles, Set<Long> seedPmids) {
// TODO Auto-generated method stub
return null;
}
/**
* This function will group from the email clusters with articles having an similar grant identifier
* @param clusters List of clusters from initial clustering
* @return list of clusters
*/
@Override
public Map<Long, ReCiterCluster> cluster(Map<Long, ReCiterCluster> clusters) {
for (Entry<Long, ReCiterCluster> entry : clusters.entrySet()) {
ReCiterCluster reCiterCluster = entry.getValue();
for (ReCiterArticle reCiterArticle : reCiterCluster.getArticleCluster()) {
checkForValidGrant(reCiterArticle);
}
}
//Compare each clusters with all other for matching grant ID
long mapSize = clusters.size();
for(long i=(long) 1 ; i <= mapSize ; i++) {
for(long j = (long) 1; j <= mapSize; j++) {
if(i==j) {
continue;
}
else {
if(clusters.get(i) != null && clusters.get(j) != null) {
if(clusters.get(i).compareTo(clusters.get(j), "grant") == 1) {
clusters.get(i).addAll(clusters.get(j).getArticleCluster());
clusters.remove(j);
}
}
}
}
}
return clusters;
}
private void checkForValidGrant(ReCiterArticle reCiterArticle) {
for (ReCiterArticleGrant grant : reCiterArticle.getGrantList()) {
if(grant.getGrantID() != null) {
String sanitizedGrant = sanitizeGrant(grant.getGrantID().replaceAll("[\\s\\-]", ""));
if(sanitizedGrant != null) {
grant.setSanitizedGrantID(sanitizedGrant);
}
}
}
}
private String sanitizeGrant(String grant) {
String fundingAgency = null;
String grantId = null;
Pattern pattern = Pattern.compile("([a-zA-Z][a-zA-Z]+)");
Matcher matcher = pattern.matcher(grant);
int matchCount = 0;
while(matcher.find()) {
matchCount++;
if(matchCount == 2) {
fundingAgency = matcher.group();
}
fundingAgency = matcher.group();
}
matchCount = 0;
pattern = Pattern.compile("[0-9]{4,6}");
matcher = pattern.matcher(grant);
while(matcher.find()) {
grantId = matcher.group().replaceFirst("^0*", "");
}
if(fundingAgency != null && grantId != null) {
return fundingAgency + "-" + grantId;
}
return null;
}
}
|
package uk.ac.susx.tag.classificationframework.featureextraction.tokenisation;
import uk.ac.susx.tag.classificationframework.Util;
import uk.ac.susx.tag.classificationframework.datastructures.AnnotatedToken;
import uk.ac.susx.tag.classificationframework.datastructures.Document;
import uk.ac.susx.tag.classificationframework.datastructures.Instance;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.util.StringUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.*;
public class TokeniserChineseStanford implements Tokeniser {
private static final long serialVersionUID = 0L;
private transient StanfordCoreNLP pipeline;
public TokeniserChineseStanford() throws IOException {
loadPipeline();
}
@Override
public Document tokenise(Instance document) {
Document tokenised = new Document(document);
if (!Util.isNullOrEmptyText(document)) {
int end = 0;
// need to handle unexpected surrogate characters.
Annotation annotation = new Annotation(document.text.replaceAll("[^\u0000-\uffff]", ""));
pipeline.annotate(annotation);
List<CoreLabel> tokens = annotation.get(CoreAnnotations.TokensAnnotation.class);
for (CoreLabel token : tokens) {
String word = token.get(CoreAnnotations.TextAnnotation.class);
int start = document.text.indexOf(word, end);
end = start + word.length();
AnnotatedToken annotatedToken = new AnnotatedToken(word);
annotatedToken.start(start);
annotatedToken.end(end);
tokenised.add(annotatedToken);
}
}
return tokenised;
}
@Override
public String configuration() {
return "";
}
public void loadPipeline(){
Properties props = StringUtils.argsToProperties("-props", "StanfordCoreNLP-chinese.properties");
props.setProperty("annotators", "tokenize");
pipeline = new StanfordCoreNLP(props);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
loadPipeline();
}
}
|
package com.gistlabs.mechanize.integration.test;
import static com.gistlabs.mechanize.query.QueryBuilder.*;
import static org.junit.Assert.*;
import org.junit.Test;
import com.gistlabs.mechanize.HtmlPage;
import com.gistlabs.mechanize.MechanizeAgent;
import com.gistlabs.mechanize.Page;
import com.gistlabs.mechanize.form.Form;
import com.gistlabs.mechanize.sequence.AbstractSequence;
/**
* @author Martin Kersten<Martin.Kersten.mk@gmail.com>
* @version 1.0
* @since 2012-09-12
*/
public class AmazonAddItemToCartAndUseASecondAgentToRemoveTheItemIT {
/**
* Adds the processor 'AMD FX 4100' to the shopping cart and using a second agent
* to remove it. This test also demonstrates how to copy session cookies (and other cookies)
* from one agent to another.
*/
@Test
public void testAddingAndRemovingAItemToAndFromShoppingCartUsingTwoAgents() {
AddItemToShoppingCartSequence addItemToShoppingCartSequence = new AddItemToShoppingCartSequence("B005UBNL0A");
RemoveItemFromShoppingCartSequence removeItemFromShoppingCartSequence = new RemoveItemFromShoppingCartSequence();
MechanizeAgent agentA = new MechanizeAgent();
MechanizeAgent agentB = new MechanizeAgent();
addItemToShoppingCartSequence.run(agentA);
assertTrue("Ensure session cookie is used", agentA.cookies().getCount() > 0);
agentB.cookies().addAllCloned(agentA.cookies().getAll());
assertTrue("Ensure session cookies has been transfered", agentB.cookies().getCount() > 0);
removeItemFromShoppingCartSequence.run(agentB);
assertTrue(removeItemFromShoppingCartSequence.wasShoppingCartEmpty());
}
private static class AddItemToShoppingCartSequence extends AbstractSequence {
private final String productCode;
public AddItemToShoppingCartSequence(String productCodeToBuy) {
this.productCode = productCodeToBuy;
}
@Override
protected void run() {
agent.get("http:
agent.idle(200);
Page amdProcessorPage = agent.get("http:
agent.idle(250);
Form form = amdProcessorPage.forms().get(byName("handleBuy"));
agent.idle(200);
form.submit();
agent.idle(200);
}
}
private static class RemoveItemFromShoppingCartSequence extends AbstractSequence {
private boolean wasShoppingCartEmpty;
@Override
protected void run() {
Page page = agent.get("http:
agent.idle(200);
Page cart = page.links().get(byId("nav-cart")).click();
Form cartForm = cart.forms().get(byName("cartViewForm"));
cartForm.get("quantity.C35RMYTCMZTEKE").setValue("0");
agent.idle(200);
HtmlPage response = (HtmlPage)cartForm.submit();
wasShoppingCartEmpty = response.getDocument().outerHtml().contains("Your Shopping Cart is empty.");
}
public boolean wasShoppingCartEmpty() {
return wasShoppingCartEmpty;
}
}
}
|
package com.splicemachine.derby.impl.sql.execute.operations;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import com.splicemachine.constants.bytes.BytesUtil;
import com.splicemachine.derby.hbase.SpliceDriver;
import com.splicemachine.derby.hbase.SpliceObserverInstructions;
import com.splicemachine.derby.iapi.storage.RowProviderIterator;
import com.splicemachine.derby.iapi.storage.ScanBoundary;
import com.splicemachine.derby.impl.job.operation.SuccessFilter;
import com.splicemachine.derby.impl.storage.BaseHashAwareScanBoundary;
import com.splicemachine.derby.utils.*;
import com.splicemachine.derby.utils.marshall.*;
import com.splicemachine.encoding.MultiFieldDecoder;
import com.splicemachine.encoding.MultiFieldEncoder;
import com.splicemachine.job.JobStats;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.io.FormatableArrayHolder;
import org.apache.derby.iapi.services.loader.GeneratedMethod;
import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.sql.execute.ExecRow;
import org.apache.derby.iapi.sql.execute.NoPutResultSet;
import org.apache.derby.iapi.store.access.ColumnOrdering;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.impl.sql.GenericStorablePreparedStatement;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.log4j.Logger;
import com.splicemachine.constants.SpliceConstants;
import com.splicemachine.derby.hbase.SpliceOperationCoprocessor;
import com.splicemachine.derby.iapi.sql.execute.SpliceOperation;
import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext;
import com.splicemachine.derby.iapi.storage.RowProvider;
import com.splicemachine.derby.impl.storage.ClientScanProvider;
import com.splicemachine.derby.impl.storage.SimpleRegionAwareRowProvider;
import com.splicemachine.derby.stats.Accumulator;
import com.splicemachine.derby.stats.TimingStats;
import com.splicemachine.utils.SpliceLogUtils;
import org.datanucleus.sco.backed.Map;
public class GroupedAggregateOperation extends GenericAggregateOperation {
private static Logger LOG = Logger.getLogger(GroupedAggregateOperation.class);
protected boolean isInSortedOrder;
protected boolean isRollup;
protected int orderingItem;
protected List<Integer> keyColumns;
protected List<Integer> groupByColumns;
protected List<Integer> nonGroupByUniqueColumns;
protected List<Boolean> groupByDescAscInfo;
protected List<Boolean> descAscInfo;
protected List<Integer> allKeyColumns;
HashMap<Integer,List<DataValueDescriptor>> distinctValues;
private int numDistinctAggs = 0;
protected ColumnOrdering[] order;
private HashBuffer<ByteBuffer,ExecRow> currentAggregations = new HashBuffer<ByteBuffer,ExecRow>(SpliceConstants.ringBufferSize);
private ExecRow[] resultRows;
private boolean completedExecution = false;
protected KeyMarshall hasher;
protected byte[] currentKey;
protected MultiFieldEncoder sinkEncoder;
protected RowProvider rowProvider;
private Accumulator scanAccumulator = TimingStats.uniformAccumulator();
private HashBufferSource hbs;
private boolean isTemp;
public GroupedAggregateOperation () {
super();
SpliceLogUtils.trace(LOG,"instantiate without parameters");
}
public GroupedAggregateOperation(NoPutResultSet s,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
Activation a,
GeneratedMethod ra,
int maxRowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isRollup) throws StandardException {
super(s,aggregateItem,a,ra,resultSetNumber,optimizerEstimatedRowCount,optimizerEstimatedCost);
SpliceLogUtils.trace(LOG, "instantiate with isInSortedOrder %s, aggregateItem %d, orderingItem %d, isRollup %s",isInSortedOrder,aggregateItem,orderingItem,isRollup);
this.isInSortedOrder = isInSortedOrder;
this.isRollup = isRollup;
this.orderingItem = orderingItem;
recordConstructorTime();
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
isInSortedOrder = in.readBoolean();
isRollup = in.readBoolean();
orderingItem = in.readInt();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeBoolean(isInSortedOrder);
out.writeBoolean(isRollup);
out.writeInt(orderingItem);
}
@Override
public void init(SpliceOperationContext context) throws StandardException{
SpliceLogUtils.trace(LOG, "init called");
super.init(context);
((SpliceOperation)source).init(context);
GenericStorablePreparedStatement statement = context.getPreparedStatement();
order = (ColumnOrdering[])
((FormatableArrayHolder) (statement.getSavedObject(orderingItem))).getArray(ColumnOrdering.class);
keyColumns = new ArrayList<Integer>();
nonGroupByUniqueColumns = new ArrayList<Integer>();
groupByColumns = new ArrayList<Integer>();
descAscInfo = new ArrayList<Boolean>();
groupByDescAscInfo = new ArrayList<Boolean>();
final int[] keyCols = new int[order.length];
for (int index = 0; index < order.length; index++) {
keyColumns.add(order[index].getColumnId());
descAscInfo.add(order[index].getIsAscending());
keyCols[index] = order[index].getColumnId();
}
for(SpliceGenericAggregator agg: aggregates){
if(agg.isDistinct()) {
if (!keyColumns.contains(agg.getAggregatorInfo().getInputColNum()))
nonGroupByUniqueColumns.add(agg.getAggregatorInfo().getInputColNum());
numDistinctAggs++;
}
}
// Create the Distinct Values Map
distinctValues = new HashMap<Integer,List<DataValueDescriptor>>();
// Make sure the lists are clear, who is unique and who is group by
if (numDistinctAggs > 0) {
groupByColumns.addAll(keyColumns.subList(0, keyColumns.size()-1));
nonGroupByUniqueColumns.add(nonGroupByUniqueColumns.size(),keyColumns.get(keyColumns.size()-1));
groupByDescAscInfo.addAll(descAscInfo.subList(0, descAscInfo.size()-1));
for (Integer unique: nonGroupByUniqueColumns) {
groupByDescAscInfo.add(true);
}
} else {
groupByColumns.addAll(keyColumns);
groupByDescAscInfo.addAll(descAscInfo);
}
sinkEncoder = MultiFieldEncoder.create(SpliceDriver.getKryoPool(),groupByColumns.size() + nonGroupByUniqueColumns.size()+1);
sinkEncoder.setRawBytes(uniqueSequenceID).mark();
// scanEncoder = MultiFieldEncoder.create(groupByColumns.size());
allKeyColumns = new ArrayList<Integer>(groupByColumns);
allKeyColumns.addAll(nonGroupByUniqueColumns);
if(regionScanner==null){
isTemp = true;
} else {
isTemp = !context.isSink() || context.getTopOperation()!=this;
if(isTemp){
RowEncoder scanEncoder = RowEncoder.create(sourceExecIndexRow.nColumns(),convertIntegers(allKeyColumns),convertBooleans(groupByDescAscInfo),
sinkEncoder.getEncodedBytes(0),
KeyType.FIXED_PREFIX,
RowMarshaller.packed());
//build a ScanBoundary based off the type of the entries
final DataValueDescriptor[] cols = sourceExecIndexRow.getRowArray();
ScanBoundary boundary = new BaseHashAwareScanBoundary(SpliceConstants.DEFAULT_FAMILY_BYTES){
@Override
public byte[] getStartKey(Result result) {
MultiFieldDecoder fieldDecoder = MultiFieldDecoder.wrap(result.getRow(),SpliceDriver.getKryoPool());
fieldDecoder.seek(9); //skip the prefix value
return DerbyBytesUtil.slice(fieldDecoder,keyCols,cols);
}
@Override
public byte[] getStopKey(Result result) {
byte[] start = getStartKey(result);
BytesUtil.unsignedIncrement(start,start.length-1);
return start;
}
};
rowProvider = new SimpleRegionAwareRowProvider(
"groupedAggregateRowProvider",
SpliceUtils.NA_TRANSACTION_ID,
context.getRegion(),
context.getScan(),
SpliceConstants.TEMP_TABLE_BYTES,
SpliceConstants.DEFAULT_FAMILY_BYTES,
scanEncoder.getDual(sourceExecIndexRow),
boundary); // Make sure the partitioner (Region Aware) worries about group by keys, not the additonal unique keys
rowProvider.open();
}
}
hasher = KeyType.BARE;
MultiFieldEncoder mfe = MultiFieldEncoder.create(SpliceDriver.getKryoPool(),groupByColumns.size() + nonGroupByUniqueColumns.size()+1);
boolean[] groupByDescAscArray = convertBooleans(groupByDescAscInfo);
int[] keyColumnArray = convertIntegers(allKeyColumns);
RowProviderIterator<ExecRow> sourceProvider = createSourceIterator();
hbs = new HashBufferSource(uniqueSequenceID, keyColumnArray, sourceProvider, merger, KeyType.BARE, mfe, groupByDescAscArray, aggregateFinisher);
}
@Override
public RowProvider getReduceRowProvider(SpliceOperation top,RowDecoder decoder) throws StandardException {
try {
reduceScan = Scans.buildPrefixRangeScan(uniqueSequenceID,SpliceUtils.NA_TRANSACTION_ID);
} catch (IOException e) {
throw Exceptions.parseException(e);
}
SuccessFilter filter = new SuccessFilter(failedTasks);
reduceScan.setFilter(filter);
SpliceUtils.setInstructions(reduceScan, activation, top);
return new ClientScanProvider("groupedAggregateReduce",SpliceOperationCoprocessor.TEMP_TABLE,reduceScan,decoder);
}
@Override
public RowProvider getMapRowProvider(SpliceOperation top, RowDecoder decoder) throws StandardException {
return getReduceRowProvider(top,decoder);
}
@Override
protected JobStats doShuffle() throws StandardException {
long start = System.currentTimeMillis();
final RowProvider rowProvider = ((SpliceOperation)source).getMapRowProvider(this, getRowEncoder().getDual(getExecRowDefinition()));
nextTime+= System.currentTimeMillis()-start;
SpliceObserverInstructions soi = SpliceObserverInstructions.create(getActivation(),this);
return rowProvider.shuffleRows(soi);
}
@Override
public RowEncoder getRowEncoder() throws StandardException {
return RowEncoder.create(sourceExecIndexRow.nColumns(), convertIntegers(allKeyColumns),convertBooleans(groupByDescAscInfo), null, new KeyMarshall() {
@Override
public void encodeKey(DataValueDescriptor[] columns,
int[] keyColumns,
boolean[] sortOrder,
byte[] keyPostfix,
MultiFieldEncoder keyEncoder) throws StandardException {
//TODO -sf- this might break DistinctGroupedAggregations
byte[] key = BytesUtil.concatenate(currentKey,SpliceUtils.getUniqueKey());
keyEncoder.setRawBytes(key);
keyEncoder.setRawBytes(keyPostfix);
}
@Override
public void decode(DataValueDescriptor[] columns,
int[] reversedKeyColumns,
boolean[] sortOrder,
MultiFieldDecoder rowDecoder) throws StandardException {
hasher.decode(columns, reversedKeyColumns, sortOrder, rowDecoder);
}
@Override
public int getFieldCount(int[] keyColumns) {
return 2;
}
}, RowMarshaller.packed());
}
@Override
public void cleanup() {
}
@Override
public ExecRow getNextSinkRow() throws StandardException {
ExecRow row = doSinkAggregation();
if (LOG.isTraceEnabled())
SpliceLogUtils.trace(LOG, "getNextSinkRow %s",row);
return row;
}
@Override
public ExecRow getNextRowCore() throws StandardException {
ExecRow row = doScanAggregation();
if (LOG.isTraceEnabled())
SpliceLogUtils.trace(LOG, "getNextRowCore %s",row);
return row;
}
private final HashMerger merger = new HashMerger<ByteBuffer,ExecRow>() {
@Override
public ExecRow shouldMerge(HashBuffer<ByteBuffer, ExecRow> hashBuffer, ByteBuffer key){
return hashBuffer.get(key);
}
@Override
public void merge(HashBuffer<ByteBuffer, ExecRow> hashBuffer, ExecRow curr,ExecRow next){
try {
mergeVectorAggregates(next,curr);
} catch (StandardException e) {
SpliceLogUtils.logAndThrowRuntime(LOG, e);
}
}};
private ExecRow doSinkAggregation() throws StandardException {
if(resultRows==null){
resultRows = isRollup?new ExecRow[groupByColumns.size()+1]:new ExecRow[1]; // Need to fix Group By Columns
}
Pair<ByteBuffer,ExecRow> nextRow = hbs.getNextAggregatedRow();
ExecRow rowResult = null;
if(nextRow != null){
makeCurrent(nextRow.getFirst(),nextRow.getSecond());
rowResult = nextRow.getSecond();
}else{
SpliceLogUtils.trace(LOG, "finalizeResults");
completedExecution=true;
}
if (LOG.isTraceEnabled())
SpliceLogUtils.trace(LOG,"next aggregated row = %s",nextRow);
return rowResult;
}
private ExecRow doScanAggregation() throws StandardException {
if (completedExecution) {
if (currentAggregations.size()>0) {
ByteBuffer key = currentAggregations.keySet().iterator().next();
return makeCurrent(key,currentAggregations.remove(key));
} else
return null; // Done
}
long start = System.nanoTime();
if(resultRows==null)
resultRows = new ExecRow[1];
ExecRow nextRow = getNextRowFromScan();
if(nextRow ==null)
return finalizeResults();
//TODO -sf- stash these away somewhere so we're not constantly autoboxing
int[] groupByCols = convertIntegers(groupByColumns);
long rowsScanned = 0l;
do{
resultRows[0] = nextRow;
ExecRow[] rolledUpRows = resultRows;
for(ExecRow rolledUpRow:rolledUpRows) {
sinkEncoder.reset();
((KeyMarshall)hasher).encodeKey(rolledUpRow.getRowArray(), groupByCols, null, null, sinkEncoder);
ByteBuffer keyBuffer = ByteBuffer.wrap(sinkEncoder.build());
if(!currentAggregations.merge(keyBuffer, rolledUpRow, merger)){
ExecRow row = rolledUpRow.getClone();
refreshDistinctValues(row);
Map.Entry<ByteBuffer,ExecRow> finalized = currentAggregations.add(keyBuffer,row);
if(finalized!=null&&finalized !=row){
return makeCurrent(finalized.getKey(),finishAggregation(finalized.getValue()));
}
}
}
nextRow = getNextRowFromScan();
if(scanAccumulator.shouldCollectStats()){
scanAccumulator.tick(System.nanoTime()-start);
start = System.nanoTime();
}else{
rowsScanned++;
}
} while (nextRow!=null);
if( !scanAccumulator.shouldCollectStats() ){
scanAccumulator.tickRecords(rowsScanned);
}
ExecRow next = finalizeResults();
if (LOG.isTraceEnabled())
SpliceLogUtils.trace(LOG,"next aggregated row = %s",next);
return next;
}
private void refreshDistinctValues(ExecRow row) throws StandardException {
distinctValues.clear();
for (int i = 0; i < aggregates.length; i++) {
SpliceGenericAggregator agg = aggregates[i];
if(agg.isDistinct()) {
DataValueDescriptor value = agg.getInputColumnValue(row);
List<DataValueDescriptor> values;
values = new ArrayList<DataValueDescriptor>();
values.add(value);
distinctValues.put(i, values);
}
}
}
private ExecRow[] getRolledUpRows(ExecRow rowToRollUp) throws StandardException {
if(!isRollup){
resultRows[0] = rowToRollUp;
return resultRows;
}
int rollUpPos = groupByColumns.size();
int pos = 0;
ExecRow nextRow = rowToRollUp.getClone();
SpliceLogUtils.trace(LOG,"setting rollup cols to null");
do{
SpliceLogUtils.trace(LOG,"adding row %s",nextRow);
resultRows[pos] = nextRow;
//strip out the next key in the rollup
if(rollUpPos>0){
nextRow = nextRow.getClone();
DataValueDescriptor rollUpCol = nextRow.getColumn(order[rollUpPos-1].getColumnId()+1);
rollUpCol.setToNull();
}
rollUpPos
pos++;
}while(rollUpPos>=0);
return resultRows;
}
protected void initializeVectorAggregation(ExecRow row) throws StandardException{
for(SpliceGenericAggregator aggregator: aggregates){
aggregator.initialize(row);
aggregator.accumulate(row, row);
}
}
private void mergeVectorAggregates(ExecRow newRow, ExecRow currRow) throws StandardException {
for (int i=0; i< aggregates.length; i++) {
SpliceGenericAggregator agg = aggregates[i];
DataValueDescriptor value = agg.getInputColumnValue(newRow).cloneValue(false);
if(agg.isDistinct()) {
if (!isTemp)
continue;
else {
List<DataValueDescriptor> values;
if (distinctValues.containsKey(i)) {
values = distinctValues.get(i);
if (values.contains(value)) {
continue; // Already there, skip...
}
values.add(value);
distinctValues.put(i, values);
} else {
values = new ArrayList<DataValueDescriptor>();
values.add(value);
distinctValues.put(i, values);
}
}
}
agg.merge(newRow,currRow);
}
}
protected ExecRow getNextRowFromScan() throws StandardException {
SpliceLogUtils.trace(LOG,"getting next row from scan");
if(rowProvider.hasNext())
return rowProvider.next();
else return null;
}
private ExecRow getNextRowFromSource() throws StandardException{
ExecRow sourceRow;
ExecRow inputRow = null;
if ((sourceRow = source.getNextRowCore())!=null){
sourceExecIndexRow.execRowToExecIndexRow(sourceRow);
inputRow = sourceExecIndexRow;
}
return inputRow;
}
private ExecRow finalizeResults() throws StandardException {
SpliceLogUtils.trace(LOG, "finalizeResults");
completedExecution=true;
currentAggregations = currentAggregations.finishAggregates(aggregateFinisher);
if(currentAggregations.size()>0) {
ByteBuffer key = currentAggregations.keySet().iterator().next();
return makeCurrent(key,currentAggregations.remove(key));
}
else
return null;
}
private ExecRow makeCurrent(ByteBuffer key, ExecRow row) throws StandardException{
setCurrentRow(row);
currentKey = key.array();
return row;
}
@Override
public ExecRow getExecRowDefinition() {
SpliceLogUtils.trace(LOG,"getExecRowDefinition");
return sourceExecIndexRow.getClone();
}
@Override
public String toString() {
return "GroupedAggregateOperation {source="+source;
}
public boolean isInSortedOrder() {
return this.isInSortedOrder;
}
public boolean hasDistinctAggregate() {
return this.numDistinctAggs>0;
}
@Override
public long getTimeSpent(int type)
{
long totTime = constructorTime + openTime + nextTime + closeTime;
if (type == NoPutResultSet.CURRENT_RESULTSET_ONLY)
return totTime - source.getTimeSpent(ENTIRE_RESULTSET_TREE);
else
return totTime;
}
@Override
public void close() throws StandardException
{
if(hbs!=null)
hbs.close();
SpliceLogUtils.trace(LOG, "close in GroupedAggregate");
beginTime = getCurrentTimeMillis();
if ( isOpen )
{
if(reduceScan!=null)
SpliceDriver.driver().getTempCleaner().deleteRange(uniqueSequenceID,reduceScan.getStartRow(),reduceScan.getStopRow());
// we don't want to keep around a pointer to the
// row ... so it can be thrown away.
// REVISIT: does this need to be in a finally
// block, to ensure that it is executed?
clearCurrentRow();
source.close();
super.close();
}
closeTime += getElapsedMillis(beginTime);
isOpen = false;
}
public Properties getSortProperties() {
Properties sortProperties = new Properties();
sortProperties.setProperty("numRowsInput", ""+getRowsInput());
sortProperties.setProperty("numRowsOutput", ""+getRowsOutput());
return sortProperties;
}
@Override
public String prettyPrint(int indentLevel) {
return "Grouped"+super.prettyPrint(indentLevel);
}
public static int[] convertIntegers(List<Integer> integers) {
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++) {
ret[i] = integers.get(i).intValue();
}
return ret;
}
public static boolean[] convertBooleans(List<Boolean> booleans) {
boolean[] ret = new boolean[booleans.size()];
for (int i=0; i < ret.length; i++) {
ret[i] = booleans.get(i).booleanValue();
}
return ret;
}
private RowProviderIterator<ExecRow> createSourceIterator() {
return new RowProviderIterator<ExecRow>(){
private Iterator<ExecRow> rolledUpRows = Collections.<ExecRow>emptyList().iterator();
private boolean populated;
@Override
public boolean hasNext() throws StandardException {
if(!populated && rolledUpRows != null && !rolledUpRows.hasNext()){
ExecRow nextRow = getNextRowFromSource();
if(nextRow != null){
rolledUpRows = Arrays.asList(getRolledUpRows(nextRow)).iterator();
populated = true;
}else{
rolledUpRows = null;
populated = true;
}
}
return rolledUpRows != null && rolledUpRows.hasNext();
}
@Override
public ExecRow next() throws StandardException {
if(!populated){
hasNext();
}
ExecRow nextRow = null;
if( rolledUpRows != null){
nextRow = rolledUpRows.next();
populated = false;
initializeVectorAggregation(nextRow);
}
return nextRow;
}
};
}
}
|
package com.datayumyum.pos;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class GridViewActivity extends Activity {
final static String TAG = "com.datayumyum.pos.GridViewActivity";
private ItemRepository itemRepository;
private ShoppingCart shoppingCart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
final String jsonCatalog = readJsonCatalog();
itemRepository = new ItemRepository(jsonCatalog);
shoppingCart = new ShoppingCart();
configureCategoryViews();
configureLineItemView();
}
private void configureCategoryViews() {
GridView gridview = (GridView) findViewById(R.id.gridview);
List<View> itemButtonList = createButtonsFor("Entrees");
gridview.setAdapter(new CategoryAdapter(itemButtonList));
}
private void configureLineItemView() {
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(shoppingCart);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(listView, new SwipeDismissListViewTouchListener.DismissCallbacks() {
@Override
public boolean canDismiss(int position) {
return true;
}
@Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
shoppingCart.remove(position);
}
}
});
listView.setOnTouchListener(touchListener);
listView.setOnScrollListener(touchListener.makeScrollListener());
}
private List<View> createButtonsFor(String category) {
List<Item> itemList = itemRepository.groupItemByCategory(category);
List<View> buttonList = new ArrayList<View>();
for (Item item : itemList) {
String name = (String) item.get("name");
buttonList.add(createImageButton(name));
}
return buttonList;
}
private View createImageButton(final String label) {
LayoutInflater inflater = LayoutInflater.from(this);
View itemButton = inflater.inflate(R.layout.item_button, null);
ImageButton imageButton = (ImageButton) itemButton.findViewById(R.id.item_image_button);
int i = new Random().nextInt(mThumbIds.length - 1);
imageButton.setImageResource(mThumbIds[i]);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.w(TAG, label);
shoppingCart.add(label);
}
});
TextView itemLabel = (TextView) itemButton.findViewById(R.id.item_label);
itemLabel.setText(label);
return itemButton;
}
private String readJsonCatalog() {
BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.catalog)));
String json = "";
try {
String line;
do {
line = reader.readLine();
if (line != null)
json += line + "\n";
} while (line != null);
} catch (IOException ex) {
Log.e(TAG, ex.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
return json.trim();
}
private class ShoppingCart extends BaseAdapter {
ArrayList<HashMap> lineItems;
ShoppingCart() {
lineItems = new ArrayList<HashMap>();
}
@Override
public int getCount() {
return lineItems.size();
}
@Override
public Object getItem(int position) {
return lineItems.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
Map<String, TextView> textViewMap;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row, null);
TextView tv1 = (TextView) convertView.findViewById(R.id.QUANTITY_CELL);
TextView tv2 = (TextView) convertView.findViewById(R.id.DESCRIPTION_CELL);
TextView tv3 = (TextView) convertView.findViewById(R.id.PRICE_CELL);
TextView tv4 = (TextView) convertView.findViewById(R.id.SUB_TOTAL_CELL);
textViewMap = new HashMap<String, TextView>();
textViewMap.put("quantity", tv1);
textViewMap.put("description", tv2);
textViewMap.put("price", tv3);
textViewMap.put("subTotal", tv4);
convertView.setTag(textViewMap);
} else {
textViewMap = (Map) convertView.getTag();
}
HashMap<String, String> map = lineItems.get(position);
textViewMap.get("quantity").setText(map.get("quantity"));
textViewMap.get("description").setText(map.get("description"));
textViewMap.get("price").setText(map.get("price"));
textViewMap.get("subTotal").setText(map.get("subTotal"));
return convertView;
}
public void remove(int position) {
lineItems.remove(position);
notifyDataSetChanged();
}
public void add(String str) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("quantity", "1");
item.put("description", str);
item.put("price", str);
item.put("subTotal", str);
lineItems.add(item);
notifyDataSetChanged();
}
public void add(Item item) {
}
}
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}
|
package com.splicemachine.derby.hbase;
import com.splicemachine.constants.SpliceConstants;
import com.splicemachine.derby.impl.job.scheduler.SimpleThreadedTaskScheduler;
import com.splicemachine.pipeline.api.WriteBufferFactory;
import com.splicemachine.pipeline.coprocessor.BatchProtocol;
import com.splicemachine.pipeline.exception.IndexNotSetUpException;
import com.splicemachine.hbase.KVPair;
import com.splicemachine.pipeline.api.Code;
import com.splicemachine.pipeline.api.Service;
import com.splicemachine.pipeline.api.WriteContext;
import com.splicemachine.pipeline.impl.BulkWrite;
import com.splicemachine.pipeline.impl.BulkWriteResult;
import com.splicemachine.pipeline.impl.BulkWrites;
import com.splicemachine.pipeline.impl.BulkWritesResult;
import com.splicemachine.pipeline.impl.WriteResult;
import com.splicemachine.pipeline.utils.PipelineUtils;
import com.splicemachine.pipeline.writecontextfactory.LocalWriteContextFactory;
import com.splicemachine.pipeline.writehandler.IndexSharedCallBuffer;
import com.splicemachine.pipeline.writehandler.IndexWriteBufferFactory;
import com.splicemachine.si.api.TxnSupplier;
import com.splicemachine.si.api.TxnView;
import com.splicemachine.si.impl.TransactionStorage;
import com.splicemachine.si.impl.TransactionalRegions;
import com.splicemachine.si.api.TransactionalRegion;
import com.splicemachine.utils.SpliceLogUtils;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.Timer;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.NotServingRegionException;
import org.apache.hadoop.hbase.RegionTooBusyException;
import org.apache.hadoop.hbase.coprocessor.BaseEndpointCoprocessor;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.regionserver.metrics.RegionServerMetrics;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.log4j.Logger;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import javax.management.*;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SpliceIndexEndpoint extends BaseEndpointCoprocessor implements BatchProtocol{
private static final Logger LOG = Logger.getLogger(SpliceIndexEndpoint.class);
// protected static AtomicInteger activeWriteThreads = new AtomicInteger(0);
public static volatile int ipcReserved = 10;
private static volatile int taskWorkers = SpliceConstants.taskWorkers;
private static volatile int maxWorkers = 10;
private static volatile int flushQueueSizeBlock = SpliceConstants.flushQueueSizeBlock;
private static volatile int compactionQueueSizeBlock = SpliceConstants.compactionQueueSizeBlock;
private static volatile WriteSemaphore control = new WriteSemaphore((SpliceConstants.ipcThreads-taskWorkers-ipcReserved)/2,(SpliceConstants.ipcThreads-taskWorkers-ipcReserved)/2,SpliceConstants.maxDependentWrites,SpliceConstants.maxIndependentWrites);
public static ConcurrentMap<Long,Pair<LocalWriteContextFactory,AtomicInteger>> factoryMap = new NonBlockingHashMap<Long, Pair<LocalWriteContextFactory, AtomicInteger>>();
static{
factoryMap.put(-1l,Pair.newPair(LocalWriteContextFactory.unmanagedContextFactory(),new AtomicInteger(1)));
}
private static MetricName receptionName = new MetricName("com.splicemachine","receiverStats","time");
private static MetricName throughputMeterName = new MetricName("com.splicemachine","receiverStats","success");
private static MetricName failedMeterName = new MetricName("com.splicemachine","receiverStats","failed");
private static MetricName rejectedMeterName = new MetricName("com.splicemachine","receiverStats","rejected");
private long conglomId;
private TransactionalRegion region;
private Timer timer=SpliceDriver.driver().getRegistry().newTimer(receptionName, TimeUnit.MILLISECONDS, TimeUnit.SECONDS);
private Meter throughputMeter = SpliceDriver.driver().getRegistry().newMeter(throughputMeterName, "successfulRows", TimeUnit.SECONDS);
private Meter failedMeter =SpliceDriver.driver().getRegistry().newMeter(failedMeterName,"failedRows",TimeUnit.SECONDS);
private Meter rejectedMeter =SpliceDriver.driver().getRegistry().newMeter(rejectedMeterName,"rejectedRows",TimeUnit.SECONDS);
// private volatile RegionServerMetrics metrics;
// private volatile TxnSupplier txnStore;
private RegionCoprocessorEnvironment rce;
@Override
public void start(CoprocessorEnvironment env) {
rce = ((RegionCoprocessorEnvironment)env);
HRegionServer rs = (HRegionServer) rce.getRegionServerServices();
// metrics = rs.getMetrics();
String tableName = rce.getRegion().getTableDesc().getNameAsString();
try{
conglomId = Long.parseLong(tableName);
maxWorkers = env.getConfiguration().getInt("splice.task.maxWorkers",SimpleThreadedTaskScheduler.DEFAULT_MAX_WORKERS);
final Pair<LocalWriteContextFactory,AtomicInteger> factoryPair = Pair.newPair(new LocalWriteContextFactory(conglomId), new AtomicInteger(1));
Pair<LocalWriteContextFactory, AtomicInteger> originalPair = factoryMap.putIfAbsent(conglomId, factoryPair);
if(originalPair!=null){
//someone else already created the factory
originalPair.getSecond().incrementAndGet();
}else{
Service service = new Service() {
@Override public boolean shutdown() { return true; }
@Override
public boolean start() {
factoryPair.getFirst().prepare();
SpliceDriver.driver().deregisterService(this);
return true;
}
};
SpliceDriver.driver().registerService(service);
}
}catch(NumberFormatException nfe){
SpliceLogUtils.debug(LOG, "Unable to parse conglomerate id for table %s, " +
"index management for batch operations will be diabled",tableName);
conglomId=-1;
}
Service service = new Service() {
@Override public boolean shutdown() { return true; }
@Override
public boolean start() {
if(conglomId>=0){
region = TransactionalRegions.get(rce.getRegion());
// txnStore = TransactionStorage.getTxnSupplier();
}else{
region = TransactionalRegions.nonTransactionalRegion(rce.getRegion());
}
SpliceDriver.driver().deregisterService(this);
return true;
}
};
SpliceDriver.driver().registerService(service);
super.start(env);
}
@Override
public void stop(CoprocessorEnvironment env) {
Pair<LocalWriteContextFactory,AtomicInteger> factoryPair = factoryMap.get(conglomId);
if(factoryPair!=null && factoryPair.getSecond().decrementAndGet()<=0){
factoryMap.remove(conglomId);
}
}
/**
*
* Can it fail here?
*
* @param bulkWrites
* @return
* @throws IOException
*/
public BulkWritesResult bulkWrite(BulkWrites bulkWrites) throws IOException {
if (LOG.isTraceEnabled())
SpliceLogUtils.trace(LOG, "bulkWrite %s ",bulkWrites);
BulkWritesResult result = new BulkWritesResult();
Object[] buffer = bulkWrites.getBulkWrites().buffer;
int size = bulkWrites.getBulkWrites().size();
long start = System.nanoTime();
// start
List<Pair<BulkWriteResult,SpliceIndexEndpoint>> startPoints = new ArrayList<Pair<BulkWriteResult,SpliceIndexEndpoint>>();
WriteBufferFactory indexWriteBufferFactory = new IndexWriteBufferFactory();
boolean dependent = isDependent();
WriteSemaphore.Status status;
int kvPairSize = bulkWrites.numEntries();
status = (dependent)?control.acquireDependentPermit(kvPairSize):control.acquireIndependentPermit(kvPairSize);
if(status== WriteSemaphore.Status.REJECTED) {
rejectAll(result, size);
return result;
}
try {
for (int i = 0; i< size; i++) {
BulkWrite bulkWrite = (BulkWrite) buffer[i];
assert bulkWrite!=null;
// Grab the instances endpoint and not this one
SpliceIndexEndpoint endpoint = SpliceDriver.driver().getSpliceIndexEndpoint(bulkWrite.getEncodedStringName());
if (endpoint == null) {
if (LOG.isDebugEnabled())
SpliceLogUtils.debug(LOG, "endpoint not found for region %s on region %s",bulkWrite.getEncodedStringName(), rce.getRegion().getRegionNameAsString());
startPoints.add(Pair.newPair(new BulkWriteResult(new WriteResult(Code.NOT_SERVING_REGION, String.format("endpoint not found for region %s on region %s",bulkWrite.getEncodedStringName(), rce.getRegion().getRegionNameAsString()))), endpoint));
}
else {
startPoints.add(Pair.newPair(sendUpstream(bulkWrite,endpoint,indexWriteBufferFactory), endpoint));
}
}
// complete
for (int i = 0; i< size; i++) {
BulkWrite bulkWrite = (BulkWrite) buffer[i];
Pair<BulkWriteResult,SpliceIndexEndpoint> pair = startPoints.get(i);
result.addResult(flushAndClose(pair.getFirst(),bulkWrite,pair.getSecond()));
}
timer.update(System.nanoTime()-start,TimeUnit.NANOSECONDS);
return result;
} finally {
switch (status) {
case REJECTED:
break;
case DEPENDENT:
control.releaseDependentPermit(kvPairSize);
break;
case INDEPENDENT:
control.releaseIndependentPermit(kvPairSize);
break;
}
}
}
private void rejectAll(BulkWritesResult result, int numResults) {
this.rejectedMeter.mark();
for (int i = 0; i < numResults; i++) {
result.addResult(new BulkWriteResult(WriteResult.pipelineTooBusy(rce.getRegion().getRegionNameAsString())));
}
}
private static BulkWriteResult sendUpstream(BulkWrite bulkWrite, SpliceIndexEndpoint endpoint, WriteBufferFactory indexWriteBufferFactory) throws IOException {
assert bulkWrite.getTxn()!=null;
assert endpoint != null;
HRegion region = endpoint.rce.getRegion();
try {
region.startRegionOperation();
}
catch (NotServingRegionException nsre) {
SpliceLogUtils.debug(LOG, "hbase not serving region %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.NOT_SERVING_REGION,region.getRegionNameAsString()));
}
catch (RegionTooBusyException nsre) {
SpliceLogUtils.debug(LOG, "hbase region too busy %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.REGION_TOO_BUSY,region.getRegionNameAsString()));
}
catch (InterruptedIOException ioe) {
SpliceLogUtils.error(LOG, "hbase region interrupted %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.INTERRUPTED_EXCEPTON,region.getRegionNameAsString()));
}
try{
WriteContext context;
try {
context = endpoint.getWriteContext(indexWriteBufferFactory,bulkWrite.getTxn(),endpoint.region,endpoint.rce,bulkWrite.getMutations().size());
} catch (InterruptedException e) {
SpliceLogUtils.debug(LOG, "write context interrupted %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.INTERRUPTED_EXCEPTON));
} catch (IndexNotSetUpException e) {
SpliceLogUtils.debug(LOG, "write context index not setup exception %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.INDEX_NOT_SETUP_EXCEPTION));
}
Object[] bufferArray = bulkWrite.getBuffer();
int size = bulkWrite.getSize();
for (int i = 0; i<size; i++) {
context.sendUpstream((KVPair) bufferArray[i]); //send all writes along the pipeline
}
return new BulkWriteResult(context,WriteResult.success());
}
finally {
region.closeRegionOperation();
}
}
private static BulkWriteResult flushAndClose(BulkWriteResult writeResult, BulkWrite bulkWrite,SpliceIndexEndpoint endpoint) throws IOException {
WriteContext context = writeResult.getWriteContext();
if (context==null)
return writeResult; // Already Failed
HRegion region = endpoint.rce.getRegion();
try {
region.startRegionOperation();
}
catch (NotServingRegionException nsre) {
SpliceLogUtils.debug(LOG, "hbase not serving region %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.NOT_SERVING_REGION,region.getRegionNameAsString()));
}
catch (RegionTooBusyException nsre) {
SpliceLogUtils.debug(LOG, "hbase region too busy %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.REGION_TOO_BUSY,region.getRegionNameAsString()));
}
catch (InterruptedIOException ioe) {
SpliceLogUtils.error(LOG, "hbase region interrupted %s",region.getRegionNameAsString());
return new BulkWriteResult(new WriteResult(Code.INTERRUPTED_EXCEPTON,region.getRegionNameAsString()));
}
try {
Object[] bufferArray = bulkWrite.getBuffer();
context.flush();
Map<KVPair,WriteResult> resultMap = context.close();
BulkWriteResult response = new BulkWriteResult();
int failed=0;
int size = bulkWrite.getSize();
for (int i = 0; i<size; i++) {
@SuppressWarnings("RedundantCast") WriteResult result = resultMap.get((KVPair)bufferArray[i]);
if(!result.isSuccess()){
/*
if (!result.canRetry()) {
response.setGlobalStatus(result); // Blow up now...
return response;
}
*/
failed++;
}
response.addResult(i,result);
}
if (failed > 0)
response.setGlobalStatus(WriteResult.partial());
else
response.setGlobalStatus(WriteResult.success());
SpliceLogUtils.trace(LOG,"Returning response %s",response);
int numSuccessWrites = size-failed;
endpoint.throughputMeter.mark(numSuccessWrites);
endpoint.failedMeter.mark(failed);
return response;
} finally {
region.closeRegionOperation();
}
}
@Override
public byte[] bulkWrites(byte[] bulkWriteBytes) throws IOException {
try {
assert bulkWriteBytes!=null;
BulkWrites bulkWrites = PipelineUtils.fromCompressedBytes(bulkWriteBytes, BulkWrites.class);
return PipelineUtils.toCompressedBytes(bulkWrite(bulkWrites));
} finally {
bulkWriteBytes = null; // Dereference bytes passed.
}
}
private WriteContext getWriteContext(WriteBufferFactory indexWriteBufferFactory, TxnView txn, TransactionalRegion region, RegionCoprocessorEnvironment rce,int writeSize) throws IOException, InterruptedException {
Pair<LocalWriteContextFactory, AtomicInteger> ctxFactoryPair = getContextPair(conglomId);
return ctxFactoryPair.getFirst().create(indexWriteBufferFactory,txn,region,rce);
}
private boolean isDependent() throws IOException {
Pair<LocalWriteContextFactory, AtomicInteger> ctxFactoryPair = getContextPair(conglomId);
return ctxFactoryPair.getFirst().hasDependentWrite();
}
private static Pair<LocalWriteContextFactory, AtomicInteger> getContextPair(long conglomId) {
Pair<LocalWriteContextFactory, AtomicInteger> ctxFactoryPair = factoryMap.get(conglomId);
if(ctxFactoryPair==null){
ctxFactoryPair = Pair.newPair(new LocalWriteContextFactory(conglomId),new AtomicInteger());
Pair<LocalWriteContextFactory, AtomicInteger> existing = factoryMap.putIfAbsent(conglomId, ctxFactoryPair);
if(existing!=null){
ctxFactoryPair = existing;
}
}
return ctxFactoryPair;
}
public static LocalWriteContextFactory getContextFactory(long baseConglomId) {
Pair<LocalWriteContextFactory,AtomicInteger> ctxPair = getContextPair(baseConglomId);
return ctxPair.getFirst();
}
public static void registerJMX(MBeanServer mbs) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
ObjectName coordinatorName = new ObjectName("com.splicemachine.derby.hbase:type=ActiveWriteHandlers");
mbs.registerMBean(ActiveWriteHandlers.get(),coordinatorName);
}
public static class ActiveWriteHandlers implements ActiveWriteHandlersIface {
private static final ActiveWriteHandlers INSTANCE = new ActiveWriteHandlers();
private ActiveWriteHandlers () {}
public static ActiveWriteHandlers get(){ return INSTANCE; }
@Override public int getIpcReservedPool() { return ipcReserved; }
@Override public void setIpcReservedPool(int ipcReservedPool) { ipcReserved = ipcReservedPool; }
@Override public int getFlushQueueSizeLimit() { return flushQueueSizeBlock; }
@Override public void setFlushQueueSizeLimit(int flushQueueSizeLimit) { flushQueueSizeBlock = flushQueueSizeLimit; }
@Override public int getCompactionQueueSizeLimit(){ return compactionQueueSizeBlock; }
@Override public void setCompactionQueueSizeLimit(int compactionQueueSizeLimit) { compactionQueueSizeBlock = compactionQueueSizeLimit; }
@Override public int getDependentWriteThreads() { return control.getDependentThreadCount(); }
@Override public int getIndependentWriteThreads() { return control.getIndependentThreadCount(); }
@Override public int getDependentWriteCount() {return control.getDependentRowPermitCount(); }
@Override public int getIndependentWriteCount() { return control.getIndependentRowPermitCount(); }
}
@MXBean
@SuppressWarnings("UnusedDeclaration")
public interface ActiveWriteHandlersIface {
public int getIpcReservedPool();
public void setIpcReservedPool(int rpcReservedPool);
public int getFlushQueueSizeLimit();
public void setFlushQueueSizeLimit(int flushQueueSizeLimit);
public int getCompactionQueueSizeLimit();
public void setCompactionQueueSizeLimit(int compactionQueueSizeLimit);
public int getDependentWriteThreads();
public int getIndependentWriteThreads();
public int getDependentWriteCount();
public int getIndependentWriteCount();
}
}
|
package org.voltdb_testprocs.regressionsuites.failureprocs;
import org.voltdb.SQLStmt;
import org.voltdb.VoltProcedure;
import org.voltdb.VoltTable;
public class InsertReplicatedAfterDupPartitionedInsert extends VoltProcedure {
public final SQLStmt insertPartitionedRow = new SQLStmt(
"INSERT INTO NEW_ORDER VALUES (?, ?, ?)");
public final SQLStmt insertReplicatedRow = new SQLStmt(
"INSERT INTO BAD_COMPARES VALUES (?, ?, ?, ?)");
public VoltTable[] run(int missingId)
{
voltQueueSQL(insertPartitionedRow, -1, 63, 63);
voltQueueSQL(insertPartitionedRow, -1, 63, 63);
voltQueueSQL(insertReplicatedRow, -1, "ABCDEF", 3.4, 8.0);
return voltExecuteSQL();
}
}
|
package fi.helsinki.cs.tmc.intellij.ui.submissionresult;
import static fi.helsinki.cs.tmc.intellij.ui.submissionresult.feedback.Boxer.hbox;
import static fi.helsinki.cs.tmc.intellij.ui.submissionresult.feedback.Boxer.hglue;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackQuestion;
import fi.helsinki.cs.tmc.core.domain.submission.SubmissionResult;
import fi.helsinki.cs.tmc.intellij.holders.TmcCoreHolder;
import fi.helsinki.cs.tmc.intellij.services.PathResolver;
import fi.helsinki.cs.tmc.intellij.services.errors.ErrorMessageService;
import fi.helsinki.cs.tmc.intellij.services.exercises.NextExerciseFetcher;
import fi.helsinki.cs.tmc.intellij.ui.submissionresult.feedback.FeedbackQuestionPanel;
import fi.helsinki.cs.tmc.intellij.ui.submissionresult.feedback.FeedbackQuestionPanelFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import icons.TmcIcons;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SuccessfulSubmissionDialog extends JDialog {
private static final Logger logger = LoggerFactory.getLogger(SuccessfulSubmissionDialog.class);
private JButton okButton;
private JButton nextExerciseButton;
private List<FeedbackQuestionPanel> feedbackQuestionPanels;
public SuccessfulSubmissionDialog(Exercise exercise, SubmissionResult result, Project project) {
logger.info("Creating SuccessfulSubmissionDialog. @SuccessfulSubmissionDialog");
this.setTitle(exercise.getName() + " passed");
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
setContentPane(contentPane);
addYayLabel();
addVSpace(6);
if (exercise.requiresReview() && !result.getMissingReviewPoints().isEmpty()) {
addRequiresReviewLabels();
}
addVSpace(6);
addPointsLabel(result);
addVSpace(10);
addModelSolutionButton(result, project);
addVSpace(20);
addFeedbackQuestions(result); //TODO: maybe put in box
addVSpace(10);
addOkButton();
addNextExerciseButton();
addNextExerciseListener(result, project);
addOkListener(result, project);
setAlwaysOnTop(true);
pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.requestFocusInWindow(true);
}
public void addOkListener(final SubmissionResult result, final Project project) {
logger.info("Adding action listener for ok button. @SuccessfulSubmissionDialog");
this.okButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
logger.info("Ok button pressed. @SuccessfulSubmissionDialog");
sendFeedback(result, project);
setVisible(false);
dispose();
}
});
}
public void addNextExerciseListener(final SubmissionResult result, final Project project) {
logger.info("Adding action listener for next exercise button. @SuccessfulSubmissionDialog");
this.nextExerciseButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
logger.info("Next Exercise button pressed. @SuccessfulSubmissionDialog");
String path = project.getBasePath();
NextExerciseFetcher fetcher =
new NextExerciseFetcher(
PathResolver.getCourseName(path),
PathResolver.getExercise(path),
project);
fetcher.tryToOpenNext();
setVisible(false);
dispose();
}
});
}
private void sendFeedback(SubmissionResult result, Project project) {
logger.info("Checking if feedback exists. @SuccessfulSubmissionDialog");
List<FeedbackAnswer> answers = getFeedbackAnswers();
if (answers.size() == 0) {
logger.info("No feedback. @SuccessfulSubmissionDialog");
return;
}
try {
logger.info("Trying to send feedback. @SuccessfulSubmissionDialog");
TmcCoreHolder.get()
.sendFeedback(
ProgressObserver.NULL_OBSERVER,
getFeedbackAnswers(),
new URI(result.getFeedbackAnswerUrl()))
.call();
} catch (Exception ex) {
logger.warn(
"Failed to send feedback. Problems with internet. "
+ "@SuccessfulSubmissionDialog",
ex,
ex.getStackTrace());
String errorMessage = "Problems with internet.\n" + ex.getMessage();
Messages.showErrorDialog(project, errorMessage, "Problem with internet");
}
}
public List<FeedbackAnswer> getFeedbackAnswers() {
logger.info("Getting feedback answer. @SuccessfulSubmissionDialog");
List<FeedbackAnswer> answers = new ArrayList<>();
for (FeedbackQuestionPanel panel : feedbackQuestionPanels) {
FeedbackAnswer answer = panel.getAnswer();
if (answer == null) {
continue;
}
answers.add(answer);
}
return answers;
}
private void addVSpace(int height) {
add(Box.createVerticalStrut(height));
}
private Box leftAligned(Component component) {
return hbox(component, hglue());
}
private void addYayLabel() {
logger.info("Adding yay label. @SuccessfulSubmissionDialog");
JLabel yayLabel = new JLabel("All tests passed on the server.");
Font font = yayLabel.getFont();
font = font.deriveFont(Font.BOLD, font.getSize2D() * 1.2f);
yayLabel.setFont(font);
yayLabel.setForeground(new java.awt.Color(0, 153, 51));
yayLabel.setIcon(TmcIcons.SUCCESS);
//URL imageUrl = new URL("/fi/helsinki/cs/tmc/intellij/smile.gif");
//ImageIcon icon = new ImageIcon(getClass().getResource("/smiley.gif"));
//yayLabel.setIcon(icon);
//new ImageIcon(getClass().getResource("/fi/helsinki/cs/tmc/smile.gif"));
//yayLabel.setIcon(ConvenientDialogDisplayer.getDefault().getSmileyIcon());
getContentPane().add(leftAligned(yayLabel));
}
private void addRequiresReviewLabels() {
logger.info("Adding required review labels. @SuccessfulSubmissionDialog");
JLabel lbl1 = new JLabel("This exercise requires a code review.");
String message = "It will have a yellow marker until it's accepted by an instructor.";
JLabel lbl2 = new JLabel(message);
getContentPane().add(leftAligned(lbl1));
getContentPane().add(leftAligned(lbl2));
}
private void addPointsLabel(SubmissionResult result) {
logger.info("Adding points label. @SuccessfulSubmissionDialog");
JLabel pointsLabel = new JLabel(getPointsMsg(result));
pointsLabel.setFont(pointsLabel.getFont().deriveFont(Font.BOLD));
getContentPane().add(leftAligned(pointsLabel));
}
private String getPointsMsg(SubmissionResult result) {
logger.info("Getting points message. @SuccessfulSubmissionDialog");
if (result.getPoints().isEmpty()) {
return "";
}
String msg =
"Points permanently awarded: " + StringUtils.join(result.getPoints(), ", ") + ".";
String str = StringEscapeUtils.escapeHtml4(msg).replace("\n", "<br />\n");
return "<html>" + str + "</html>";
}
private void addModelSolutionButton(SubmissionResult result, final Project project) {
logger.info("Adding model solution button. @SuccessfulSubmissionDialog");
if (result.getSolutionUrl() == null) {
return;
}
final String solutionUrl = result.getSolutionUrl();
JButton solutionButton =
new JButton(getAbstractAction("View model solution", solutionUrl, project));
getContentPane().add(leftAligned(solutionButton));
}
private AbstractAction getAbstractAction(
String message, final String solutionUrl, final Project project) {
return new AbstractAction(message) {
@Override
public void actionPerformed(ActionEvent ev) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) {
String errorMessage = "Your OS doesn't support java.awt.Desktop.browser";
Messages.showErrorDialog(project, errorMessage, "Os problem");
return;
}
try {
desktop.browse(new URI(solutionUrl));
} catch (Exception ex) {
logger.warn(
"Failed to open browser. "
+ "Problem with browser. @SuccessfulSubmissionDialog",
ex,
ex.getStackTrace());
new ErrorMessageService()
.showMessage(ex, "Failed to open browser. Problem with browser.", true);
String errorMessage = "Failed to open browser.\n" + ex.getMessage();
Messages.showErrorDialog(project, errorMessage, "Problem with browser");
}
}
};
}
private void addFeedbackQuestions(SubmissionResult result) {
logger.info("Adding feedback questions. @SuccessfulSubmissionDialog");
this.feedbackQuestionPanels = new ArrayList<>();
if (result.getFeedbackQuestions().isEmpty() || result.getFeedbackQuestions() == null) {
return;
}
createQuestionPanelAndAddToPanelList(result.getFeedbackQuestions());
if (feedbackQuestionPanels.isEmpty()) { // Some failsafety
feedbackQuestionPanels = null;
return;
}
JLabel feedbackLabel = new JLabel("Feedback (leave empty to not send)");
feedbackLabel.setFont(feedbackLabel.getFont().deriveFont(Font.BOLD));
getContentPane().add(leftAligned(feedbackLabel));
for (FeedbackQuestionPanel panel : feedbackQuestionPanels) {
getContentPane().add(leftAligned(panel));
}
}
private void createQuestionPanelAndAddToPanelList(List<FeedbackQuestion> questions) {
logger.info(
"Getting question panel and add questions to the panel. "
+ "@SuccessfulSubmissionDialog");
for (FeedbackQuestion question : questions) {
try {
FeedbackQuestionPanel panel =
FeedbackQuestionPanelFactory.getPanelForQuestion(question);
feedbackQuestionPanels.add(panel);
} catch (IllegalArgumentException e) {
logger.warn(
"Failed to add panel. This should not cause any problems. "
+ " @SuccessfulSubmissionDialog");
continue;
}
}
}
private void addOkButton() {
logger.info("Adding ok button. @SuccessfulSubmissionDialog");
okButton = new JButton("OK");
okButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent action) {
setVisible(false);
dispose();
}
});
getContentPane().add(hbox(hglue(), okButton));
}
private void addNextExerciseButton() {
logger.info("Adding next exercise button. @SuccessfulSubmissionDialog");
nextExerciseButton = new JButton("Open Next Exercise");
nextExerciseButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent action) {
setVisible(false);
dispose();
}
});
getContentPane().add(hbox(hglue(), nextExerciseButton));
}
}
|
package simdevice;
/**
*
* @author andreaswassmer
*/
public class TemperatureSensor extends Sensor implements Measuring, SensorType {
public TemperatureSensor() {
super();
this.setRange(-10, 100);
this.type = SensorType.TEMPERATURE;
this.name = "Temperature";
}
@Override
public String measure() {
int res = this.readValueAsInt();
return String.valueOf(res);
}
}
|
package org.opendaylight.yangtools.yang.model.repo.util;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
@Beta
public class InMemorySchemaSourceCache<T extends SchemaSourceRepresentation> extends AbstractSchemaSourceCache<T> {
private static final class CacheEntry<T extends SchemaSourceRepresentation> {
private final SchemaSourceRegistration<T> reg;
private final T source;
public CacheEntry(final T source, final SchemaSourceRegistration<T> reg) {
this.source = Preconditions.checkNotNull(source);
this.reg = Preconditions.checkNotNull(reg);
}
}
private static final RemovalListener<SourceIdentifier, CacheEntry<?>> LISTENER = new RemovalListener<SourceIdentifier, CacheEntry<?>>() {
@Override
public void onRemoval(final RemovalNotification<SourceIdentifier, CacheEntry<?>> notification) {
notification.getValue().reg.close();
}
};
private final Cache<SourceIdentifier, CacheEntry<T>> cache;
protected InMemorySchemaSourceCache(final SchemaSourceRegistry consumer, final Class<T> representation, final CacheBuilder<Object, Object> builder) {
super(consumer, representation, Costs.IMMEDIATE);
cache = builder.removalListener(LISTENER).build();
}
public static <R extends SchemaSourceRepresentation> InMemorySchemaSourceCache<R> createSoftCache(final SchemaSourceRegistry consumer, final Class<R> representation) {
return new InMemorySchemaSourceCache<>(consumer, representation, CacheBuilder.newBuilder().softValues());
}
@Override
public CheckedFuture<? extends T, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
final CacheEntry<T> present = cache.getIfPresent(sourceIdentifier);
if (present != null) {
return Futures.immediateCheckedFuture(present.source);
}
return Futures.<T, SchemaSourceException>immediateFailedCheckedFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
}
@Override
protected void offer(final T source) {
final CacheEntry<T> present = cache.getIfPresent(source.getIdentifier());
if (present == null) {
final SchemaSourceRegistration<T> reg = register(source.getIdentifier());
cache.put(source.getIdentifier(), new CacheEntry<T>(source, reg));
}
}
}
|
package org.osmdroid.samplefragments.drawing;
import android.content.ContentValues;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.osmdroid.R;
import org.osmdroid.samplefragments.BaseSampleFragment;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.Polyline;
import org.osmdroid.views.overlay.advancedpolyline.ColorMappingForScalarContainer;
import org.osmdroid.views.overlay.advancedpolyline.ColorMappingVariationHue;
import org.osmdroid.views.overlay.advancedpolyline.MonochromaticPaintList;
import org.osmdroid.views.overlay.advancedpolyline.PolychromaticPaintList;
import java.util.ArrayList;
/**
* Simple example to show scalar mapping invalidation.
* @author Matthias Dittmer
*/
public class ShowAdvancedPolylineStylesInvalidation extends BaseSampleFragment implements View.OnClickListener {
/*
* Example data
*/
private boolean mLineExtended = false;
private TextView textViewCurrentLocation;
private Button btnProceed;
private Polyline mPolyline = null;
private ColorMappingVariationHue mMapping = null;
private ColorMappingForScalarContainer mContainer = null;
private ArrayList<GeoPoint> points = new ArrayList<>();
private ArrayList<Float> scalars = new ArrayList<>();
@Override
public String getSampleTitle() {
return "Show advanced polyline (with invalidation)";
}
@Override
public void addOverlays() {
super.addOverlays();
setupLine();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_advanced_polyline_invalidate, null);
// setup UI references
mMapView = v.findViewById(R.id.mapview);
textViewCurrentLocation = v.findViewById(R.id.textInformation);
btnProceed = v.findViewById(R.id.btnProceed);
btnProceed.setOnClickListener(this);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
centerToLine();
}
/*
* Creates new line with an initial mapping.
*/
private void setupLine() {
// remove previous data
if(mPolyline != null) {
mMapView.getOverlayManager().remove(mPolyline);
mPolyline = null;
mMapping = null;
mContainer = null;
}
points.clear();
points.add(new GeoPoint(37.0, -11.0));
points.add(new GeoPoint(37.5, -11.5));
points.add(new GeoPoint(38.0, -11.0));
points.add(new GeoPoint(38.5, -11.5));
points.add(new GeoPoint(39.0, -11.0));
points.add(new GeoPoint(39.5, -11.5));
// create new polyline
mPolyline = new Polyline(mMapView, false, false);
final Paint paintBorder = new Paint();
paintBorder.setColor(Color.BLACK);
paintBorder.setAntiAlias(true);
paintBorder.setStrokeWidth(25);
paintBorder.setStyle(Paint.Style.STROKE);
paintBorder.setStrokeJoin(Paint.Join.ROUND);
paintBorder.setStrokeCap(Paint.Cap.ROUND);
paintBorder.setAntiAlias(true);
mPolyline.getOutlinePaintLists().add(new MonochromaticPaintList(paintBorder));
// add points and scalars
mPolyline.setPoints(points);
scalars.clear();
scalars.add(0.0f);
scalars.add(20.0f);
scalars.add(10.0f);
scalars.add(30.0f);
scalars.add(50.0f);
scalars.add(25.0f);
mMapping = new ColorMappingVariationHue(0,50, 0,120, 1.0f, 0.5f);
mContainer = new ColorMappingForScalarContainer(mMapping);
// add scalars to mapping and container
for (final float scalar : scalars) {
mMapping.add(scalar);
mContainer.add(scalar);
}
final Paint paintMapping = new Paint();
paintMapping.setAntiAlias(true);
paintMapping.setStrokeWidth(20);
paintMapping.setStyle(Paint.Style.FILL_AND_STROKE);
paintMapping.setStrokeJoin(Paint.Join.ROUND);
paintMapping.setStrokeCap(Paint.Cap.ROUND);
paintMapping.setAntiAlias(true);
mPolyline.getOutlinePaintLists().add(new PolychromaticPaintList(paintMapping, mMapping, true));
// update UI
mMapView.getOverlayManager().add(mPolyline);
// force a redraw (normally triggered when map is moved for example)
mMapView.invalidate();
textViewCurrentLocation.setText("Scalar range from 0 to 50\nfor hue ranging from 0 to 120.");
btnProceed.setText("Extend Polyline");
}
/*
* Extends the line and invalidates the mapping with a new range.
*/
private void extendAndInvalidateLine() {
// add new points with higher scalars
mPolyline.addPoint(new GeoPoint(40.0, -11.0));
mPolyline.addPoint(new GeoPoint(40.5, -11.5));
mPolyline.addPoint(new GeoPoint(41.0, -11.0));
mPolyline.addPoint(new GeoPoint(41.5, -11.5));
// add scalars to mapping and container
mMapping.add(80.f);
mMapping.add(60.f);
mMapping.add(100.f);
mMapping.add(100.f);
mContainer.add(80.f);
mContainer.add(60.f);
mContainer.add(100.f);
mContainer.add(100.f);
// update mapping with scalar end updated from 50 to 100
mMapping.init(0,100, 0,120);
// call refresh to update line
mContainer.refresh();
// force a redraw (normally triggered when map is moved for example)
mMapView.invalidate();
// update UI
textViewCurrentLocation.setText("New scalar range from 0 to 100\nfor hue ranging from 0 to 120.");
btnProceed.setText("Reset Polyline");
}
void centerToLine() {
mMapView.getController().setCenter(new GeoPoint(38.5, -11.5));
mMapView.getController().zoomTo(6.0f);
}
@Override
public void onClick(View view) {
// simple toggle logic
if (view.getId() == R.id.btnProceed) {
if (mLineExtended) {
setupLine();
mLineExtended = false;
} else {
extendAndInvalidateLine();
mLineExtended = true;
}
}
}
}
|
package nodomain.freeyourgadget.gadgetbridge.service.devices.lefun.requests;
import nodomain.freeyourgadget.gadgetbridge.devices.lefun.commands.NotificationCommand;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.devices.lefun.LefunDeviceSupport;
public class SendNotificationRequest extends AbstractSendNotificationRequest {
NotificationSpec notification;
public SendNotificationRequest(LefunDeviceSupport support, TransactionBuilder builder) {
super(support, builder);
}
@Override
protected byte getNotificationType() {
switch (notification.type) {
case GENERIC_PHONE:
return NotificationCommand.SERVICE_TYPE_CALL;
case GENERIC_SMS:
case GENERIC_EMAIL:
default:
return NotificationCommand.SERVICE_TYPE_TEXT;
case WECHAT:
return NotificationCommand.SERVICE_TYPE_WECHAT;
case FACEBOOK:
case FACEBOOK_MESSENGER:
case TWITTER:
case LINKEDIN:
case WHATSAPP:
case LINE:
case KAKAO_TALK:
return NotificationCommand.SERVICE_TYPE_EXTENDED;
}
}
@Override
protected byte getExtendedNotificationType() {
switch (notification.type) {
case GENERIC_PHONE:
case GENERIC_SMS:
case GENERIC_EMAIL:
default:
case WECHAT:
return 0;
case FACEBOOK:
case FACEBOOK_MESSENGER:
return NotificationCommand.EXTENDED_SERVICE_TYPE_FACEBOOK;
case TWITTER:
return NotificationCommand.EXTENDED_SERVICE_TYPE_TWITTER;
case LINKEDIN:
return NotificationCommand.EXTENDED_SERVICE_TYPE_LINKEDIN;
case WHATSAPP:
return NotificationCommand.EXTENDED_SERVICE_TYPE_WHATSAPP;
case LINE:
return NotificationCommand.EXTENDED_SERVICE_TYPE_LINE;
case KAKAO_TALK:
return NotificationCommand.EXTENDED_SERVICE_TYPE_KAKAOTALK;
}
}
public NotificationSpec getNotification() {
return notification;
}
public void setNotification(NotificationSpec notification) {
this.notification = notification;
}
@Override
protected String getMessage() {
// Based on nodomain.freeyourgadget.gadgetbridge.service.devices.id115.SendNotificationOperation
String message = "";
if (notification.phoneNumber != null && !notification.phoneNumber.isEmpty()) {
message += notification.phoneNumber + ": ";
}
if (notification.sender != null && !notification.sender.isEmpty()) {
message += notification.sender + " - ";
} else if (notification.title != null && !notification.title.isEmpty()) {
message += notification.title + " - ";
} else if (notification.subject != null && !notification.subject.isEmpty()) {
message += notification.subject + " - ";
}
if (notification.body != null && !notification.body.isEmpty()) {
message += notification.body;
}
return message;
}
}
|
package org.ovirt.engine.api.restapi.resource;
import static org.ovirt.engine.api.restapi.resource.BackendHostsResource.SUB_COLLECTIONS;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.ovirt.engine.api.common.util.StatusUtils;
import org.ovirt.engine.api.model.Action;
import org.ovirt.engine.api.model.Agent;
import org.ovirt.engine.api.model.Cluster;
import org.ovirt.engine.api.model.CreationStatus;
import org.ovirt.engine.api.model.Fault;
import org.ovirt.engine.api.model.FenceType;
import org.ovirt.engine.api.model.Host;
import org.ovirt.engine.api.model.IscsiDetails;
import org.ovirt.engine.api.model.LogicalUnit;
import org.ovirt.engine.api.model.PowerManagement;
import org.ovirt.engine.api.model.PowerManagementStatus;
import org.ovirt.engine.api.model.StorageDomains;
import org.ovirt.engine.api.resource.ActionResource;
import org.ovirt.engine.api.resource.AssignedPermissionsResource;
import org.ovirt.engine.api.resource.AssignedTagsResource;
import org.ovirt.engine.api.resource.FenceAgentsResource;
import org.ovirt.engine.api.resource.HostNicsResource;
import org.ovirt.engine.api.resource.HostNumaNodesResource;
import org.ovirt.engine.api.resource.HostResource;
import org.ovirt.engine.api.resource.HostStorageResource;
import org.ovirt.engine.api.resource.StatisticsResource;
import org.ovirt.engine.api.restapi.model.AuthenticationMethod;
import org.ovirt.engine.api.restapi.types.DeprecatedPowerManagementMapper;
import org.ovirt.engine.api.restapi.types.FenceAgentMapper;
import org.ovirt.engine.api.utils.LinkHelper;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.ApproveVdsParameters;
import org.ovirt.engine.core.common.action.ChangeVDSClusterParameters;
import org.ovirt.engine.core.common.action.FenceVdsActionParameters;
import org.ovirt.engine.core.common.action.FenceVdsManualyParameters;
import org.ovirt.engine.core.common.action.FenceAgentCommandParameterBase;
import org.ovirt.engine.core.common.action.ForceSelectSPMParameters;
import org.ovirt.engine.core.common.action.MaintenanceNumberOfVdssParameters;
import org.ovirt.engine.core.common.action.StorageServerConnectionParametersBase;
import org.ovirt.engine.core.common.action.UpdateVdsActionParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdsActionParameters;
import org.ovirt.engine.core.common.action.VdsOperationActionParameters;
import org.ovirt.engine.core.common.businessentities.FenceActionType;
import org.ovirt.engine.core.common.businessentities.FenceAgent;
import org.ovirt.engine.core.common.businessentities.FenceStatusReturnValue;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSType;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.queries.DiscoverSendTargetsQueryParameters;
import org.ovirt.engine.core.common.queries.GetPermissionsForObjectParameters;
import org.ovirt.engine.core.common.queries.GetUnregisteredBlockStorageDomainsParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.NameQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.queries.VdsIdParametersBase;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
public class BackendHostResource extends AbstractBackendActionableResource<Host, VDS> implements
HostResource {
private static final String DEFAULT_ISCSI_PORT = "3260";
private BackendHostsResource parent;
public BackendHostResource(String id, BackendHostsResource parent) {
super(id, Host.class, VDS.class, SUB_COLLECTIONS);
this.parent = parent;
}
@Override
public Host get() {
if (isForce()) {
performAction(VdcActionType.RefreshHostCapabilities,
new VdsActionParameters(guid));
}
Host host = performGet(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(guid));
deprecatedAddLinksToAgents(host);
return host;
}
@Override
public Host update(Host incoming) {
validateEnums(Host.class, incoming);
QueryIdResolver<Guid> hostResolver = new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class);
VDS entity = getEntity(hostResolver, true);
if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) {
Guid clusterId = lookupClusterId(incoming);
if (!clusterId.equals(entity.getVdsGroupId())) {
performAction(VdcActionType.ChangeVDSCluster,
new ChangeVDSClusterParameters(clusterId, guid));
// After changing the cluster with the specialized command we need to reload the entity, so that it
// contains the new cluster id. If we don't do this the next command will think that we are trying
// to change the cluster, and it will explicitly refuse to perform the update.
entity = getEntity(hostResolver, true);
}
}
// deprecatedUpdateFenceAgents(incoming);
Host host = performUpdate(incoming,
entity,
map(entity),
hostResolver,
VdcActionType.UpdateVds,
new UpdateParametersProvider());
deprecatedAddLinksToAgents(host);
return host;
}
@Deprecated
private void deprecatedAddLinksToAgents(Host host) {
if (host.isSetPowerManagement() && host.getPowerManagement().isSetAgents()
&& host.getPowerManagement().getAgents().isSetAgents()) {
for (Agent agent : host.getPowerManagement().getAgents().getAgents()) {
Host host2 = new Host();
host2.setId(host.getId());
agent.setHost(host2);
LinkHelper.addLinks(uriInfo, agent);
}
}
}
@SuppressWarnings("unused")
@Deprecated
/**
* In the past fence-agents appeared in-line in a host, and updating them was done through an update
* of the host. This is maintained for backwards-compatibility (for simplicity, agents are removed and
* re-added). Update of 3+ agents is not supported, since traditionally there were at most 2.
* This method does not handle deleting only one of the agents (existing bug).
*/
private void deprecatedUpdateFenceAgents(Host incoming) {
List<FenceAgent> agents =
DeprecatedPowerManagementMapper.map(incoming.getPowerManagement(),
getFenceAgentsResource().getFenceAgents());
if (agents.isEmpty()) {
FenceAgentCommandParameterBase params = new FenceAgentCommandParameterBase();
params.setVdsId(guid);
performAction(VdcActionType.RemoveFenceAgentsByVdsId, params);
} else if (agents.size() < 3) {
for (FenceAgent agent : agents) {
getFenceAgentsResource().remove(agent.getId().toString());
getFenceAgentsResource().add(FenceAgentMapper.map(agent, null));
}
}
}
@Override
public Response install(Action action) {
// REVISIT fencing options
VDS vds = getEntity();
validateEnums(Action.class, action);
UpdateVdsActionParameters params = new UpdateVdsActionParameters(vds.getStaticData(), action.getRootPassword(), true);
params = (UpdateVdsActionParameters) getMapper
(Action.class, VdsOperationActionParameters.class).map(action, (VdsOperationActionParameters) params);
if (vds.getVdsType()==VDSType.oVirtNode) {
params.setIsReinstallOrUpgrade(true);
if (action.isSetImage()) {
params.setoVirtIsoFile(action.getImage());
}
}
return doAction(VdcActionType.UpdateVds,
params,
action);
}
@Override
public Response activate(Action action) {
return doAction(VdcActionType.ActivateVds,
new VdsActionParameters(guid),
action);
}
@Override
public Response approve(Action action) {
if (action.isSetCluster() && (action.getCluster().isSetId() || action.getCluster().isSetName())) {
update(setCluster(get(), action.getCluster()));
}
validateEnums(Action.class, action);
ApproveVdsParameters params = new ApproveVdsParameters(guid);
params = (ApproveVdsParameters) getMapper
(Action.class, VdsOperationActionParameters.class).map(action, (VdsOperationActionParameters) params);
// Set pk authentication as default
params.setAuthMethod(VdsOperationActionParameters.AuthenticationMethod.PublicKey);
if (action.isSetRootPassword()) {
params.setAuthMethod(VdsOperationActionParameters.AuthenticationMethod.Password);
params.setRootPassword(action.getRootPassword());
}
else if (action.isSetSsh() && action.getSsh().isSetAuthenticationMethod()) {
if (action.getSsh().getAuthenticationMethod().equals(
AuthenticationMethod.PASSWORD.value())) {
params.setAuthMethod(VdsOperationActionParameters.AuthenticationMethod.Password);
if (action.getSsh().isSetUser() && action.getSsh().getUser().isSetPassword()) {
params.setPassword(action.getSsh().getUser().getPassword());
}
}
}
return doAction(VdcActionType.ApproveVds,
params,
action);
}
private Host setCluster(Host host, Cluster cluster) {
if (cluster.isSetId()) {
host.setCluster(cluster);
} else {
host.setCluster(new Cluster());
host.getCluster().setId(lookupClusterByName(cluster.getName()).getId().toString());
}
return host;
}
protected Guid lookupClusterId(Host host) {
return host.getCluster().isSetId() ? asGuid(host.getCluster().getId())
:
lookupClusterByName(host.getCluster().getName()).getId();
}
protected VDSGroup lookupClusterByName(String name) {
return getEntity(VDSGroup.class,
VdcQueryType.GetVdsGroupByName,
new NameQueryParameters(name),
"Cluster: name=" + name);
}
@Override
public Response deactivate(Action action) {
return doAction(VdcActionType.MaintenanceNumberOfVdss,
new MaintenanceNumberOfVdssParameters(asList(guid), false),
action);
}
@Override
public Response forceSelectSPM(Action action) {
return doAction(VdcActionType.ForceSelectSPM,
new ForceSelectSPMParameters(guid), action);
}
@Override
public Response iscsiLogin(Action action) {
validateParameters(action, "iscsi.address", "iscsi.target");
StorageServerConnections cnx = new StorageServerConnections();
IscsiDetails iscsiDetails = action.getIscsi();
cnx.setconnection(iscsiDetails.getAddress());
cnx.setiqn(iscsiDetails.getTarget());
cnx.setstorage_type(org.ovirt.engine.core.common.businessentities.StorageType.ISCSI);
if (iscsiDetails.isSetPort()) {
cnx.setport(iscsiDetails.getPort().toString());
} else {
cnx.setport(DEFAULT_ISCSI_PORT);
}
if (iscsiDetails.isSetUsername()) {
cnx.setuser_name(iscsiDetails.getUsername());
}
if (iscsiDetails.isSetPassword()) {
cnx.setpassword(iscsiDetails.getPassword());
}
StorageServerConnectionParametersBase connectionParms = new StorageServerConnectionParametersBase(cnx, guid);
return doAction(VdcActionType.ConnectStorageToVds, connectionParms, action);
}
@Override
public Response unregisteredStorageDomainsDiscover(Action action) {
validateParameters(action, "iscsi.address");
// Validate if the Host exists.
getEntity();
List<StorageServerConnections> storageServerConnections = new ArrayList<>();
for (String iscsiTarget : action.getIscsiTargets()) {
StorageServerConnections connectionDetails = getInitializedConnectionIscsiDetails(action);
connectionDetails.setiqn(iscsiTarget);
storageServerConnections.add(connectionDetails);
}
GetUnregisteredBlockStorageDomainsParameters unregisteredBlockStorageDomainsParameters =
new GetUnregisteredBlockStorageDomainsParameters(guid, StorageType.ISCSI, storageServerConnections);
try {
Pair<List<StorageDomain>, List<StorageServerConnections>> pair =
getEntity(Pair.class,
VdcQueryType.GetUnregisteredBlockStorageDomains,
unregisteredBlockStorageDomainsParameters,
"GetUnregisteredBlockStorageDomains", true);
List<StorageDomain> storageDomains = pair.getFirst();
return actionSuccess(mapToStorageDomains(action, storageDomains));
} catch (Exception e) {
return handleError(e, false);
}
}
@Override
public Response iscsiDiscover(Action action) {
validateParameters(action, "iscsi.address");
List<StorageServerConnections> result = getBackendCollection(StorageServerConnections.class,
VdcQueryType.DiscoverSendTargets,
createDiscoveryQueryParams(action));
return actionSuccess(mapTargets(action, result));
}
private Action mapTargets(Action action, List<StorageServerConnections> targets) {
if (targets != null) {
for (StorageServerConnections cnx : targets) {
action.getIscsiTargets().add(map(cnx).getTarget());
}
}
return action;
}
private Action mapToStorageDomains(Action action, List<StorageDomain> storageDomains) {
if (storageDomains != null) {
action.setStorageDomains(new StorageDomains());
for (StorageDomain storageDomain : storageDomains) {
action.getStorageDomains().getStorageDomains().add(map(storageDomain));
}
}
return action;
}
protected LogicalUnit map(StorageServerConnections cnx) {
return getMapper(StorageServerConnections.class, LogicalUnit.class).map(cnx, null);
}
protected org.ovirt.engine.api.model.StorageDomain map(StorageDomain storageDomain) {
return getMapper(StorageDomain.class, org.ovirt.engine.api.model.StorageDomain.class).map(storageDomain, null);
}
private DiscoverSendTargetsQueryParameters createDiscoveryQueryParams(Action action) {
StorageServerConnections connectionDetails = getInitializedConnectionIscsiDetails(action);
return new DiscoverSendTargetsQueryParameters(guid, connectionDetails);
}
private StorageServerConnections getInitializedConnectionIscsiDetails(Action action) {
StorageServerConnections connectionDetails = new StorageServerConnections();
IscsiDetails iscsiDetails = action.getIscsi();
connectionDetails.setconnection(iscsiDetails.getAddress());
connectionDetails.setstorage_type(org.ovirt.engine.core.common.businessentities.StorageType.ISCSI);
if (iscsiDetails.isSetPort()) {
connectionDetails.setport(iscsiDetails.getPort().toString());
} else {
connectionDetails.setport(DEFAULT_ISCSI_PORT);
}
if (iscsiDetails.isSetUsername()) {
connectionDetails.setuser_name(iscsiDetails.getUsername());
}
if (iscsiDetails.isSetPassword()) {
connectionDetails.setpassword(iscsiDetails.getPassword());
}
return connectionDetails;
}
@Override
public Response commitNetConfig(Action action) {
return doAction(VdcActionType.CommitNetworkChanges,
new VdsActionParameters(guid),
action);
}
@Override
public Response fence(Action action) {
validateParameters(action, "fenceType");
FenceType fenceType = validateEnum(FenceType.class, action.getFenceType().toUpperCase());
switch (fenceType) {
case MANUAL:
return fenceManually(action);
case RESTART:
return fence(action, VdcActionType.RestartVds, FenceActionType.Restart);
case START:
return fence(action, VdcActionType.StartVds, FenceActionType.Start);
case STOP:
return fence(action, VdcActionType.StopVds, FenceActionType.Stop);
case STATUS:
return getFenceStatus(action);
default:
return null;
}
}
private Response getFenceStatus(Action action) {
VDSReturnValue result = getEntity(VDSReturnValue.class, VdcQueryType.GetVdsFenceStatus, new VdsIdParametersBase(guid), guid.toString());
FenceStatusReturnValue fenceResult = (FenceStatusReturnValue) result.getReturnValue();
if (fenceResult.getIsSucceeded()) {
PowerManagement pm = new PowerManagement();
pm.setStatus(fenceResult.getStatus().toLowerCase().equals("on") ? StatusUtils.create(PowerManagementStatus.ON)
: fenceResult.getStatus().toLowerCase().equals("off") ? StatusUtils.create(PowerManagementStatus.OFF)
: fenceResult.getStatus().toLowerCase().equals("unknown") ? StatusUtils.create(PowerManagementStatus.UNKNOWN)
: null);
action.setPowerManagement(pm);
return actionSuccess(action);
} else {
return handleFailure(action, fenceResult.getMessage());
}
}
private Response handleFailure(Action action, String message) {
action.setStatus(StatusUtils.create(CreationStatus.FAILED));
action.setFault(new Fault());
action.getFault().setReason(message);
return Response.ok().entity(action).build();
}
private Response fence(Action action, VdcActionType vdcAction, FenceActionType fenceType) {
return doAction(vdcAction, new FenceVdsActionParameters(guid, fenceType), action);
}
private Response fenceManually(Action action) {
FenceVdsManualyParameters params = new FenceVdsManualyParameters(true);
params.setVdsId(guid);
params.setStoragePoolId(getEntity().getStoragePoolId());
return doAction(VdcActionType.FenceVdsManualy, params, action);
}
@Override
public HostNumaNodesResource getHostNumaNodesResource() {
return inject(new BackendHostNumaNodesResource(id));
}
@Override
public HostNicsResource getHostNicsResource() {
return inject(new BackendHostNicsResource(id));
}
@Override
public HostStorageResource getHostStorageResource() {
return inject(new BackendHostStorageResource(id));
}
@Override
public AssignedTagsResource getTagsResource() {
return inject(new BackendHostTagsResource(id));
}
@Override
public AssignedPermissionsResource getPermissionsResource() {
return inject(new BackendAssignedPermissionsResource(guid,
VdcQueryType.GetPermissionsForObject,
new GetPermissionsForObjectParameters(guid),
Host.class,
VdcObjectType.VDS));
}
@Override
public StatisticsResource getStatisticsResource() {
EntityIdResolver<Guid> resolver = new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class);
HostStatisticalQuery query = new HostStatisticalQuery(resolver, newModel(id));
return inject(new BackendStatisticsResource<Host, VDS>(entityType, guid, query));
}
@Override
public ActionResource getActionSubresource(String action, String ids) {
return inject(new BackendActionResource(action, ids));
}
@Override
protected VDS getEntity() {
return getEntity(VDS.class, VdcQueryType.GetVdsByVdsId, new IdQueryParameters(guid), id);
}
protected class UpdateParametersProvider implements ParametersProvider<Host, VDS> {
@Override
public VdcActionParametersBase getParameters(Host incoming, VDS entity) {
VdsStatic updated = getMapper(modelType, VdsStatic.class).map(incoming,
entity.getStaticData());
UpdateVdsActionParameters updateParams = new UpdateVdsActionParameters(updated, incoming.getRootPassword(), false);
// Updating Fence-agents is deprecated from this context, so the original, unchanged, list of agents is
// passed to the engine.
updateParams.setFenceAgents(entity.getFenceAgents());
if (incoming.isSetOverrideIptables()) {
updateParams.setOverrideFirewall(incoming.isOverrideIptables());
}
updateParams = (UpdateVdsActionParameters) getMapper
(Host.class, VdsOperationActionParameters.class).map(incoming, (VdsOperationActionParameters) updateParams);
return updateParams;
}
}
@Override
protected Host doPopulate(Host model, VDS entity) {
Host host = parent.addHostedEngineIfConfigured(model, entity);
return host;
}
@Override
protected Host deprecatedPopulate(Host model, VDS entity) {
parent.addStatistics(model, entity);
parent.addCertificateInfo(model);
return model;
}
public BackendHostsResource getParent() {
return this.parent;
}
@Override
@Path("hooks")
public BackendHostHooksResource getHooksResource() {
return inject(new BackendHostHooksResource(id));
}
@Override
@Path("fenceagents")
public FenceAgentsResource getFenceAgentsResource() {
return inject(new BackendFenceAgentsResource(id));
}
}
|
package org.openhab.binding.zwave.internal.protocol;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openhab.binding.zwave.internal.HexToIntegerConverter;
import org.openhab.binding.zwave.internal.protocol.ZWaveDeviceClass.Basic;
import org.openhab.binding.zwave.internal.protocol.ZWaveDeviceClass.Generic;
import org.openhab.binding.zwave.internal.protocol.ZWaveDeviceClass.Specific;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveAssociationCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiInstanceCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveNodeNamingCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveVersionCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveWakeUpCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveNodeStatusEvent;
import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeInitStage;
import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeStageAdvancer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* Z-Wave node class. Represents a node in the Z-Wave network.
*
* @author Brian Crosby
* @author Chris Jackson
* @since 1.3.0
*/
@XStreamAlias("node")
public class ZWaveNode {
@XStreamOmitField
private static final Logger logger = LoggerFactory.getLogger(ZWaveNode.class);
private final ZWaveDeviceClass deviceClass;
@XStreamOmitField
private ZWaveController controller;
@XStreamOmitField
private ZWaveNodeStageAdvancer nodeStageAdvancer;
@XStreamOmitField
private ZWaveNodeState nodeState;
@XStreamConverter(HexToIntegerConverter.class)
private int homeId = Integer.MAX_VALUE;
private int nodeId = Integer.MAX_VALUE;
private int version = Integer.MAX_VALUE;
private String name;
private String location;
@XStreamConverter(HexToIntegerConverter.class)
private int manufacturer = Integer.MAX_VALUE;
@XStreamConverter(HexToIntegerConverter.class)
private int deviceId = Integer.MAX_VALUE;
@XStreamConverter(HexToIntegerConverter.class)
private int deviceType = Integer.MAX_VALUE;
private boolean listening; // i.e. sleeping
private boolean frequentlyListening;
private boolean routing;
private String healState;
@SuppressWarnings("unused")
private boolean security;
@SuppressWarnings("unused")
private boolean beaming;
@SuppressWarnings("unused")
private int maxBaudRate;
// Keep the NIF - just used for information and debug in the XML
@SuppressWarnings("unused")
private List<Integer> nodeInformationFrame = null;
private Map<CommandClass, ZWaveCommandClass> supportedCommandClasses = new HashMap<CommandClass, ZWaveCommandClass>();
private List<Integer> nodeNeighbors = new ArrayList<Integer>();
private Date lastSent = null;
private Date lastReceived = null;
@XStreamOmitField
private boolean applicationUpdateReceived = false;
@XStreamOmitField
private int resendCount = 0;
@XStreamOmitField
private int receiveCount = 0;
@XStreamOmitField
private int sendCount = 0;
@XStreamOmitField
private int deadCount = 0;
@XStreamOmitField
private Date deadTime;
@XStreamOmitField
private int retryCount = 0;
/**
* Constructor. Creates a new instance of the ZWaveNode class.
*
* @param homeId the home ID to use.
* @param nodeId the node ID to use.
* @param controller the wave controller instance
*/
public ZWaveNode(int homeId, int nodeId, ZWaveController controller) {
nodeState = ZWaveNodeState.ALIVE;
this.homeId = homeId;
this.nodeId = nodeId;
this.controller = controller;
this.nodeStageAdvancer = new ZWaveNodeStageAdvancer(this, controller);
this.deviceClass = new ZWaveDeviceClass(Basic.NOT_KNOWN, Generic.NOT_KNOWN, Specific.NOT_USED);
}
/**
* Configures the node after it's been restored from file.
* NOTE: XStream doesn't run any default constructor. So, any initialisation
* made in a constructor, or statically, won't be performed!!!
* Set defaults here if it's important!!!
*
* @param controller the wave controller instance
*/
public void setRestoredFromConfigfile(ZWaveController controller) {
nodeState = ZWaveNodeState.ALIVE;
this.controller = controller;
// Create the initialisation advancer and tell it we've loaded from file
this.nodeStageAdvancer = new ZWaveNodeStageAdvancer(this, controller);
this.nodeStageAdvancer.setRestoredFromConfigfile();
nodeStageAdvancer.setCurrentStage(ZWaveNodeInitStage.EMPTYNODE);
}
/**
* Gets the node ID.
*
* @return the node id
*/
public int getNodeId() {
return nodeId;
}
/**
* Gets whether the node is listening.
*
* @return boolean indicating whether the node is listening or not.
*/
public boolean isListening() {
return listening;
}
/**
* Sets whether the node is listening.
*
* @param listening
*/
public void setListening(boolean listening) {
this.listening = listening;
}
/**
* Gets whether the node is frequently listening.
* Frequently listening is responding to a beam signal. Apart from
* increased latency, nothing else is noticeable from the serial api
* side.
*
* @return boolean indicating whether the node is frequently
* listening or not.
*/
public boolean isFrequentlyListening() {
return frequentlyListening;
}
/**
* Sets whether the node is frequently listening.
* Frequently listening is responding to a beam signal. Apart from
* increased latency, nothing else is noticeable from the serial api
* side.
*
* @param frequentlyListening indicating whether the node is frequently
* listening or not.
*/
public void setFrequentlyListening(boolean frequentlyListening) {
this.frequentlyListening = frequentlyListening;
}
/**
* Gets the Heal State of the node.
*
* @return String indicating the node Heal State.
*/
public String getHealState() {
return healState;
}
/**
* Sets the Heal State of the node.
*
* @param healState
*/
public void setHealState(String healState) {
this.healState = healState;
}
/**
* Gets whether the node is dead.
*
* @return
*/
public boolean isDead() {
if (nodeState == ZWaveNodeState.DEAD || nodeState == ZWaveNodeState.FAILED) {
return true;
} else {
return false;
}
}
/**
* Sets the node to be 'undead'.
*/
public void setNodeState(ZWaveNodeState state) {
// Make sure we only handle real state changes
if (state == nodeState) {
return;
}
switch (state) {
case ALIVE:
logger.debug("NODE {}: Node has risen from the DEAD. Init stage is {}:{}.", nodeId,
this.getNodeInitializationStage().toString());
// Reset the resend counter
this.resendCount = 0;
break;
case DEAD:
// If the node is failed, then we don't allow transitions to DEAD
// The only valid state change from FAILED is to ALIVE
if (nodeState == ZWaveNodeState.FAILED) {
return;
}
case FAILED:
this.deadCount++;
this.deadTime = Calendar.getInstance().getTime();
logger.debug("NODE {}: Node is DEAD.", this.nodeId);
break;
}
// Don't alert state changes while we're still initialising
if (nodeStageAdvancer.isInitializationComplete() == true) {
ZWaveEvent zEvent = new ZWaveNodeStatusEvent(this.getNodeId(), ZWaveNodeState.DEAD);
controller.notifyEventListeners(zEvent);
} else {
logger.debug("NODE {}: Initialisation incomplete, not signalling state change.", this.nodeId);
}
nodeState = state;
}
/**
* Gets the home ID
*
* @return the homeId
*/
public Integer getHomeId() {
return homeId;
}
/**
* Gets the node name.
* If Node Naming Command Class is supported get name from device,
* else return the name stored in binding
*
* @return the name
*/
public String getName() {
ZWaveNodeNamingCommandClass commandClass = (ZWaveNodeNamingCommandClass) getCommandClass(
CommandClass.NODE_NAMING);
if (commandClass == null) {
return this.name;
}
return commandClass.getName();
}
/**
* Sets the node name.
* If Node Naming Command Class is supported set name in the device,
* else set it in locally in the binding
*
* @param name the name to set
*/
public void setName(String name) {
ZWaveNodeNamingCommandClass commandClass = (ZWaveNodeNamingCommandClass) getCommandClass(
CommandClass.NODE_NAMING);
if (commandClass == null) {
this.name = name;
return;
}
SerialMessage m = commandClass.setNameMessage(name);
this.controller.sendData(m);
m = commandClass.getNameMessage();
this.controller.sendData(m);
}
/**
* Gets the node location.
* If Node Naming Command Class is supported get location from device,
* else return the location stored in binding
*
* @return the location
*/
public String getLocation() {
ZWaveNodeNamingCommandClass commandClass = (ZWaveNodeNamingCommandClass) getCommandClass(
CommandClass.NODE_NAMING);
if (commandClass == null) {
return this.location;
}
return commandClass.getLocation();
}
/**
* Sets the node location.
* If Node Naming Command Class is supported set location in the device,
* else set it in locally in the binding
*
* @param location the location to set
*/
public void setLocation(String location) {
ZWaveNodeNamingCommandClass commandClass = (ZWaveNodeNamingCommandClass) getCommandClass(
CommandClass.NODE_NAMING);
if (commandClass == null) {
this.location = location;
return;
}
SerialMessage m = commandClass.setLocationMessage(location);
this.controller.sendData(m);
m = commandClass.getLocationMessage();
this.controller.sendData(m);
}
/**
* Gets the manufacturer of the node.
*
* @return the manufacturer
*/
public int getManufacturer() {
return manufacturer;
}
/**
* Sets the manufacturer of the node.
*
* @param tempMan the manufacturer to set
*/
public void setManufacturer(int tempMan) {
this.manufacturer = tempMan;
}
/**
* Gets the device id of the node.
*
* @return the deviceId
*/
public int getDeviceId() {
return deviceId;
}
/**
* Sets the device id of the node.
*
* @param tempDeviceId the device to set
*/
public void setDeviceId(int tempDeviceId) {
this.deviceId = tempDeviceId;
}
/**
* Gets the device type of the node.
*
* @return the deviceType
*/
public int getDeviceType() {
return deviceType;
}
/**
* Sets the device type of the node.
*
* @param tempDeviceType the deviceType to set
*/
public void setDeviceType(int tempDeviceType) {
this.deviceType = tempDeviceType;
}
/**
* Get the date/time the node was last updated (ie a frame was received from it).
*
* @return the lastUpdated time
*/
public Date getLastReceived() {
return lastReceived;
}
/**
* Get the date/time we last sent a frame to the node.
*
* @return the lastSent
*/
public Date getLastSent() {
return lastSent;
}
/**
* Gets the node state.
*
* @return the nodeState
*/
public ZWaveNodeState getNodeState() {
return this.nodeState;
}
/**
* Gets the node stage.
*
* @return the nodeStage
*/
public ZWaveNodeInitStage getNodeInitializationStage() {
return this.nodeStageAdvancer.getCurrentStage();
}
/**
* Gets the initialization state
*
* @return true if initialization has been completed
*/
public boolean isInitializationComplete() {
return this.nodeStageAdvancer.isInitializationComplete();
}
/**
* Sets the node stage.
*
* @param nodeStage the nodeStage to set
*/
public void setNodeStage(ZWaveNodeInitStage nodeStage) {
nodeStageAdvancer.setCurrentStage(nodeStage);
}
/**
* Gets the node version
*
* @return the version
*/
public int getVersion() {
return version;
}
/**
* Sets the node version.
*
* @param version the version to set
*/
public void setVersion(int version) {
this.version = version;
}
/**
* Gets the node application firmware version
*
* @return the version
*/
public String getApplicationVersion() {
ZWaveVersionCommandClass versionCmdClass = (ZWaveVersionCommandClass) this
.getCommandClass(CommandClass.VERSION);
if (versionCmdClass == null) {
return "0.0";
}
String appVersion = versionCmdClass.getApplicationVersion();
if (appVersion == null) {
logger.trace("NODE {}: App version requested but version is unknown", this.getNodeId());
return "0.0";
}
return appVersion;
}
/**
* Gets whether the node is routing messages.
*
* @return the routing
*/
public boolean isRouting() {
return routing;
}
/**
* Sets whether the node is routing messages.
*
* @param routing the routing to set
*/
public void setRouting(boolean routing) {
this.routing = routing;
}
/**
* Gets the time stamp the node was last queried.
*
* @return the queryStageTimeStamp
*/
public Date getQueryStageTimeStamp() {
return this.nodeStageAdvancer.getQueryStageTimeStamp();
}
/**
* Increments the resend counter.
* On three increments the node stage is set to DEAD and no
* more messages will be sent.
* This is only used for SendData messages.
*/
public void incrementResendCount() {
if (++resendCount >= 3) {
setNodeState(ZWaveNodeState.DEAD);
}
this.retryCount++;
}
/**
* Resets the resend counter and possibly resets the
* node stage to DONE when previous initialization was
* complete.
* Note that if the node is DEAD, then the nodeStage stays DEAD
*/
public void resetResendCount() {
this.resendCount = 0;
if (this.nodeStageAdvancer.isInitializationComplete() && this.isDead() == false) {
nodeStageAdvancer.setCurrentStage(ZWaveNodeInitStage.DONE);
}
}
/**
* Returns the device class of the node.
*
* @return the deviceClass
*/
public ZWaveDeviceClass getDeviceClass() {
return deviceClass;
}
/**
* Returns the Command classes this node implements.
*
* @return the command classes.
*/
public Collection<ZWaveCommandClass> getCommandClasses() {
return supportedCommandClasses.values();
}
/**
* Returns a commandClass object this node implements.
* Returns null if command class is not supported by this node.
*
* @param commandClass The command class to get.
* @return the command class.
*/
public ZWaveCommandClass getCommandClass(CommandClass commandClass) {
return supportedCommandClasses.get(commandClass);
}
/**
* Returns whether a node supports this command class.
*
* @param commandClass the command class to check
* @return true if the command class is supported, false otherwise.
*/
public boolean supportsCommandClass(CommandClass commandClass) {
return supportedCommandClasses.containsKey(commandClass);
}
/**
* Adds a command class to the list of supported command classes by this node.
* Does nothing if command class is already added.
*
* @param commandClass the command class instance to add.
*/
public void addCommandClass(ZWaveCommandClass commandClass) {
CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
logger.debug("NODE {}: Adding command class {} to the list of supported command classes.", nodeId,
commandClass.getCommandClass().getLabel());
supportedCommandClasses.put(key, commandClass);
if (commandClass instanceof ZWaveEventListener) {
this.controller.addEventListener((ZWaveEventListener) commandClass);
}
}
}
/**
* Removes a command class from the node.
* This is used to remove classes that a node may report it supports
* but it doesn't respond to.
*
* @param commandClass The command class key
*/
public void removeCommandClass(CommandClass commandClass) {
supportedCommandClasses.remove(commandClass);
}
/**
* Resolves a command class for this node. First endpoint is checked.
* If endpoint == 0 or (endpoint != 1 and version of the multi instance
* command == 1) then return a supported command class on the node itself.
* If endpoint != 1 and version of the multi instance command == 2 then
* first try command classes of endpoints. If not found the return a
* supported command class on the node itself.
* Returns null if a command class is not found.
*
* @param commandClass The command class to resolve.
* @param endpointId the endpoint / instance to resolve this command class for.
* @return the command class.
*/
public ZWaveCommandClass resolveCommandClass(CommandClass commandClass, int endpointId) {
if (commandClass == null) {
return null;
}
if (endpointId == 0) {
return getCommandClass(commandClass);
}
ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass) supportedCommandClasses
.get(CommandClass.MULTI_INSTANCE);
if (multiInstanceCommandClass == null) {
return null;
} else if (multiInstanceCommandClass.getVersion() == 2) {
ZWaveEndpoint endpoint = multiInstanceCommandClass.getEndpoint(endpointId);
if (endpoint != null) {
ZWaveCommandClass result = endpoint.getCommandClass(commandClass);
if (result != null) {
return result;
}
}
} else if (multiInstanceCommandClass.getVersion() == 1) {
ZWaveCommandClass result = getCommandClass(commandClass);
if (result != null && endpointId <= result.getInstances()) {
return result;
}
} else {
logger.warn("NODE {}: Unsupported multi instance command version: {}.", nodeId,
multiInstanceCommandClass.getVersion());
}
return null;
}
/**
* Initialise the node
*/
public void initialiseNode() {
this.nodeStageAdvancer.startInitialisation();
}
/**
* Encapsulates a serial message for sending to a
* multi-instance instance/ multi-channel endpoint on
* a node.
*
* @param serialMessage the serial message to encapsulate
* @param commandClass the command class used to generate the message.
* @param endpointId the instance / endpoint to encapsulate the message for
* @param node the destination node.
* @return SerialMessage on success, null on failure.
*/
public SerialMessage encapsulate(SerialMessage serialMessage, ZWaveCommandClass commandClass, int endpointId) {
ZWaveMultiInstanceCommandClass multiInstanceCommandClass;
if (serialMessage == null) {
return null;
}
// no encapsulation necessary.
if (endpointId == 0) {
return serialMessage;
}
multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass) this.getCommandClass(CommandClass.MULTI_INSTANCE);
if (multiInstanceCommandClass != null) {
logger.debug("NODE {}: Encapsulating message, instance / endpoint {}", this.getNodeId(), endpointId);
switch (multiInstanceCommandClass.getVersion()) {
case 2:
if (commandClass.getEndpoint() != null) {
serialMessage = multiInstanceCommandClass.getMultiChannelEncapMessage(serialMessage,
commandClass.getEndpoint());
return serialMessage;
}
break;
case 1:
default:
if (commandClass.getInstances() >= endpointId) {
serialMessage = multiInstanceCommandClass.getMultiInstanceEncapMessage(serialMessage,
endpointId);
return serialMessage;
}
break;
}
}
logger.warn("NODE {}: Encapsulating message, instance / endpoint {} failed, will discard message.",
this.getNodeId(), endpointId);
return null;
}
/**
* Return a list with the nodes neighbors
*
* @return list of node IDs
*/
public List<Integer> getNeighbors() {
return nodeNeighbors;
}
/**
* Clear the neighbor list
*/
public void clearNeighbors() {
nodeNeighbors.clear();
}
/**
* Updates a nodes routing information
* Generation of routes uses associations
*
* @param nodeId
*/
public ArrayList<Integer> getRoutingList() {
logger.debug("NODE {}: Update return routes", nodeId);
// Create a list of nodes this device is configured to talk to
ArrayList<Integer> routedNodes = new ArrayList<Integer>();
// Only update routes if this is a routing node
if (isRouting() == false) {
logger.debug("NODE {}: Node is not a routing node. No routes can be set.", nodeId);
return null;
}
// Get the number of association groups reported by this node
ZWaveAssociationCommandClass associationCmdClass = (ZWaveAssociationCommandClass) getCommandClass(
CommandClass.ASSOCIATION);
if (associationCmdClass == null) {
logger.debug("NODE {}: Node has no association class. No routes can be set.", nodeId);
return null;
}
int groups = associationCmdClass.getGroupCount();
if (groups != 0) {
// Loop through each association group and add the node ID to the list
for (int group = 1; group <= groups; group++) {
for (Integer associationNodeId : associationCmdClass.getGroupMembers(group)) {
routedNodes.add(associationNodeId);
}
}
}
// Add the wakeup destination node to the list for battery devices
ZWaveWakeUpCommandClass wakeupCmdClass = (ZWaveWakeUpCommandClass) getCommandClass(CommandClass.WAKE_UP);
if (wakeupCmdClass != null) {
Integer wakeupNodeId = wakeupCmdClass.getTargetNodeId();
routedNodes.add(wakeupNodeId);
}
// Are there any nodes to which we need to set routes?
if (routedNodes.size() == 0) {
logger.debug("NODE {}: No return routes required.", nodeId);
return null;
}
return routedNodes;
}
/**
* Add a node ID to the neighbor list
*
* @param nodeId the node to add
*/
public void addNeighbor(Integer nodeId) {
nodeNeighbors.add(nodeId);
}
/**
* Gets the number of times the node has been determined as DEAD
*
* @return dead count
*/
public int getDeadCount() {
return deadCount;
}
/**
* Gets the number of times the node has been determined as DEAD
*
* @return dead count
*/
public Date getDeadTime() {
return deadTime;
}
/**
* Gets the number of packets that have been resent to the node
*
* @return retry count
*/
public int getRetryCount() {
return retryCount;
}
/**
* Increments the sent packet counter and records the last sent time
* This is simply used for statistical purposes to assess the health
* of a node.
*/
public void incrementSendCount() {
sendCount++;
this.lastSent = Calendar.getInstance().getTime();
}
/**
* Increments the received packet counter and records the last received time
* This is simply used for statistical purposes to assess the health
* of a node.
*/
public void incrementReceiveCount() {
receiveCount++;
this.lastReceived = Calendar.getInstance().getTime();
}
/**
* Gets the number of packets sent to the node
*
* @return send count
*/
public int getSendCount() {
return sendCount;
}
/**
* Gets the applicationUpdateReceived flag.
* This is set to indicate that we have received the required information from the device
*
* @return true if information received
*/
public boolean getApplicationUpdateReceived() {
return applicationUpdateReceived;
}
/**
* Sets the applicationUpdateReceived flag.
* This is set to indicate that we have received the required information from the device
*
* @param received true if received
*/
public void setApplicationUpdateReceived(boolean received) {
applicationUpdateReceived = received;
}
public void updateNIF(List<Integer> nif) {
nodeInformationFrame = nif;
}
public void setSecurity(boolean security) {
this.security = security;
}
public void setBeaming(boolean beaming) {
this.beaming = beaming;
}
public void setMaxBaud(int maxBaudRate) {
this.maxBaudRate = maxBaudRate;
}
}
|
package org.motechproject.testing.uifunctionaltests;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.motechproject.uitest.TestBase;
import org.motechproject.uitest.page.DataServicesPage;
public class DataServicesUIFT extends TestBase {
private static final String ENTITY_NAME = "newEntity";
private static final String EMAIL_RECORD_ENTITY = "EmailRecord";
private static final String NEW_FIELD_NAME = "fieldName";
private static final String NEW_FIELD_DISPLAY_NAME = "Field Name";
private DataServicesPage dataServicesPage;
@Before
public void initialize() {
dataServicesPage = new DataServicesPage(getDriver());
login();
}
@After
public void cleanUp() throws InterruptedException {
logout();
}
public void newEntityTest () throws Exception {
dataServicesPage.goToPage();
assertEquals(ENTITY_NAME, dataServicesPage.createNewEntity(ENTITY_NAME));
dataServicesPage.goToPage();
dataServicesPage.goToEntityTable(ENTITY_NAME);
}
@Test
public void editEntityTest() throws InterruptedException {
dataServicesPage.goToEditEntity(EMAIL_RECORD_ENTITY);
dataServicesPage.addNewBooleanField(NEW_FIELD_DISPLAY_NAME, NEW_FIELD_NAME);
dataServicesPage.goToEntityTable(EMAIL_RECORD_ENTITY);
assertTrue(dataServicesPage.checkFieldExists(NEW_FIELD_NAME));
}
}
|
package com.mesosphere.dcos.cassandra.common.offer;
import com.google.inject.Inject;
import com.mesosphere.dcos.cassandra.common.config.CassandraSchedulerConfiguration;
import com.mesosphere.dcos.cassandra.common.config.DefaultConfigurationManager;
import com.mesosphere.dcos.cassandra.common.placementrule.AvailiabilityZonePlacementRule;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraContainer;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.config.ConfigStoreException;
import org.apache.mesos.offer.InvalidRequirementException;
import org.apache.mesos.offer.OfferRequirement;
import org.apache.mesos.offer.constrain.AndRule;
import org.apache.mesos.offer.constrain.MarathonConstraintParser;
import org.apache.mesos.offer.constrain.PassthroughRule;
import org.apache.mesos.offer.constrain.PlacementRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
public class PersistentOfferRequirementProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(
PersistentOfferRequirementProvider.class);
private DefaultConfigurationManager configurationManager;
public static final String CONFIG_TARGET_KEY = "config_target";
private static Map<String, String> nodeToZoneCodeMap;
@Inject
public PersistentOfferRequirementProvider(DefaultConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
}
public Optional<OfferRequirement> getNewOfferRequirement(CassandraContainer container) {
LOGGER.info("Getting new offer requirement for: ", container.getId());
LOGGER.info("Nodes to zone map: {}", nodeToZoneCodeMap);
Optional<PlacementRule> placementRule = Optional.empty();
try {
placementRule = getPlacementRule();
} catch (IOException e) {
LOGGER.error("Failed to construct PlacementRule with Exception: ", e);
return Optional.empty();
}
try {
final Collection<Protos.TaskInfo> taskInfos = container.getTaskInfos();
final UUID targetName = configurationManager.getTargetName();
final Collection<Protos.TaskInfo> updatedTaskInfos = updateConfigLabel(taskInfos, targetName.toString());
if (nodeToZoneCodeMap != null && !nodeToZoneCodeMap.isEmpty()) {
String zone = nodeToZoneCodeMap.get(container.getDaemonTask().getName());
LOGGER.info("Zone : {}", zone);
if (zone != null) {
Optional<PlacementRule> availabilityZonePlacementRule = getAvailiabiltyZonePlacementRule(zone);
placementRule = availabilityZonePlacementRule;// mergeRules(placementRule,
// availabilityZonePlacementRule);
}
}
return Optional.of(OfferRequirement.create(
container.getDaemonTask().getType().name(),
clearTaskIds(updatedTaskInfos),
Optional.of(clearExecutorId(container.getExecutorInfo())),
placementRule));
} catch (InvalidRequirementException | ConfigStoreException e) {
LOGGER.error("Failed to construct OfferRequirement with Exception: ", e);
return Optional.empty();
} catch (IOException e) {
LOGGER.error("Failed to construct OfferRequirement with Exception, zone issue: ", e);
return Optional.empty();
}
}
public Optional<OfferRequirement> getReplacementOfferRequirement(CassandraContainer container) {
LOGGER.info("Getting replacement requirement for task: {}", container.getId());
try {
return Optional.of(OfferRequirement.create(
container.getDaemonTask().getType().name(),
clearTaskIds(container.getTaskInfos()),
Optional.of(clearExecutorId(container.getExecutorInfo())),
Optional.empty()));
} catch (InvalidRequirementException e) {
LOGGER.error("Failed to construct OfferRequirement with Exception: ", e);
return Optional.empty();
}
}
private Optional<PlacementRule> getAvailiabiltyZonePlacementRule(String az) throws IOException {
return Optional.of(new AvailiabilityZonePlacementRule(az));
}
private Optional<PlacementRule> mergeRules(Optional<PlacementRule> rule1, Optional<PlacementRule> rule2) {
AndRule andRule = new AndRule(rule1.get(), rule2.get());
return Optional.of(andRule);
}
private Optional<PlacementRule> getPlacementRule() throws IOException {
// Due to all cassandra nodes always requiring the same port, they will never colocate.
// Therefore we don't bother with explicit node avoidance in placement rules here.
// If we did want to enforce that here, we'd use PlacementUtils.getAgentPlacementRule(), and
// merge the result with the marathon placement (if any) using MarathonConstraintParser.parseWith().
String marathonPlacement =
((CassandraSchedulerConfiguration)configurationManager.getTargetConfig()).getPlacementConstraint();
PlacementRule rule = MarathonConstraintParser.parse(marathonPlacement);
if (rule instanceof PassthroughRule) {
LOGGER.info("No placement constraints found for marathon-style constraint '{}': {}", marathonPlacement, rule);
return Optional.empty();
}
LOGGER.info("Created placement rule for marathon-style constraint '{}': {}", marathonPlacement, rule);
return Optional.of(rule);
}
private static Collection<Protos.TaskInfo> updateConfigLabel(Collection<Protos.TaskInfo> taskInfos, String configName) {
Collection<Protos.TaskInfo> updatedTaskInfos = new ArrayList<>();
for (Protos.TaskInfo taskInfo : taskInfos) {
final Protos.TaskInfo updatedTaskInfo = updateConfigLabel(configName, taskInfo);
updatedTaskInfos.add(updatedTaskInfo);
}
return updatedTaskInfos;
}
private static Protos.TaskInfo updateConfigLabel(String configName, Protos.TaskInfo taskInfo) {
final Protos.Labels.Builder labelsBuilder = Protos.Labels.newBuilder();
final Protos.Labels labels = taskInfo.getLabels();
for (Protos.Label label : labels.getLabelsList()) {
final String key = label.getKey();
if (!CONFIG_TARGET_KEY.equals(key)) {
labelsBuilder.addLabels(label);
}
}
labelsBuilder.addLabels(Protos.Label.newBuilder()
.setKey(CONFIG_TARGET_KEY)
.setValue(configName));
return Protos.TaskInfo.newBuilder(taskInfo)
.clearLabels()
.setLabels(labelsBuilder.build())
.build();
}
private static List<Protos.TaskInfo> clearTaskIds(Collection<Protos.TaskInfo> taskInfos) {
List<Protos.TaskInfo> outTaskInfos = new ArrayList<>();
for (Protos.TaskInfo restartTaskInfo : taskInfos) {
outTaskInfos.add(
Protos.TaskInfo.newBuilder(restartTaskInfo)
.setTaskId(Protos.TaskID.newBuilder().setValue(""))
.build());
}
return outTaskInfos;
}
private static ExecutorInfo clearExecutorId(ExecutorInfo executorInfo) {
return ExecutorInfo.newBuilder(executorInfo)
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("").build())
.build();
}
public static void setNodeToZoneInformationMap(Map<String, String> nodeToZoneCodeMap){
PersistentOfferRequirementProvider.nodeToZoneCodeMap = nodeToZoneCodeMap;
}
}
|
package agentgui.core.common;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import agentgui.core.application.Application;
import agentgui.core.application.Language;
import agentgui.core.gui.CoreWindow;
import java.awt.Color;
import java.io.File;
public class ZipperMonitor extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private final static String PathImage = Application.RunInfo.PathImageIntern();
private final ImageIcon iconAgentGUI = new ImageIcon( this.getClass().getResource( PathImage + "AgentGUI.png") );
private final Image imageAgentGUI = iconAgentGUI.getImage();
private JPanel jContentPane = null;
private JLabel jLabelProcess = null;
private JProgressBar jProgressBarProcess = null;
private JLabel jLabelSingleFile = null;
private JButton jButtonCancel = null;
private boolean canceled = false;
private JLabel jLabelDummy = null;
/**
* @param owner
*/
public ZipperMonitor(Frame owner) {
super(owner);
initialize();
}
/**
* This method initializes this
* @return void
*/
private void initialize() {
this.setSize(542, 194);
this.setContentPane(getJContentPane());
this.setTitle(Application.RunInfo.getApplicationTitle() + ": Zip-Monitor");
this.setIconImage(imageAgentGUI);
this.setLookAndFeel();
this.setDefaultCloseOperation(CoreWindow.DO_NOTHING_ON_CLOSE);
this.getContentPane().setPreferredSize(this.getSize());
this.setLocationRelativeTo(null);
this.setAlwaysOnTop(true);
jButtonCancel.setText(Language.translate("Abbruch"));
}
private void setLookAndFeel() {
String lnfClassname = Application.RunInfo.AppLnF();
try {
if (lnfClassname == null) {
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
}
UIManager.setLookAndFeel(lnfClassname);
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception e) {
System.err.println("Cannot install " + lnfClassname + " on this platform:" + e.getMessage());
}
}
/**
* This method initializes jContentPane
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
gridBagConstraints4.gridx = 0;
gridBagConstraints4.fill = GridBagConstraints.VERTICAL;
gridBagConstraints4.weighty = 1.0;
gridBagConstraints4.gridy = 5;
jLabelDummy = new JLabel();
jLabelDummy.setText("");
jLabelDummy.setPreferredSize(new Dimension(100, 10));
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
gridBagConstraints3.gridx = 0;
gridBagConstraints3.insets = new Insets(15, 20, 0, 20);
gridBagConstraints3.anchor = GridBagConstraints.WEST;
gridBagConstraints3.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints3.gridy = 2;
jLabelSingleFile = new JLabel();
jLabelSingleFile.setText("Datei:");
jLabelSingleFile.setFont(new Font("Dialog", Font.BOLD, 12));
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
gridBagConstraints2.insets = new Insets(15, 0, 0, 10);
gridBagConstraints2.gridy = 4;
gridBagConstraints2.weightx = 1.0;
gridBagConstraints2.gridx = 0;
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.anchor = GridBagConstraints.WEST;
gridBagConstraints1.insets = new Insets(20, 20, 0, 20);
gridBagConstraints1.gridwidth = 2;
gridBagConstraints1.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints1.gridy = 0;
jLabelProcess = new JLabel();
jLabelProcess.setText("Entpacke Verzeichnis ...");
jLabelProcess.setFont(new Font("Dialog", Font.BOLD, 12));
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.insets = new Insets(10, 20, 0, 20);
gridBagConstraints.gridwidth = 1;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.gridy = 1;
jContentPane = new JPanel();
jContentPane.setLayout(new GridBagLayout());
jContentPane.add(getJProgressBarProcess(), gridBagConstraints);
jContentPane.add(jLabelProcess, gridBagConstraints1);
jContentPane.add(getJButtonCancel(), gridBagConstraints2);
jContentPane.add(jLabelSingleFile, gridBagConstraints3);
jContentPane.add(jLabelDummy, gridBagConstraints4);
}
return jContentPane;
}
/**
* This method initializes jProgressBarBenchmark
* @return javax.swing.JProgressBar
*/
private JProgressBar getJProgressBarProcess() {
if (jProgressBarProcess == null) {
jProgressBarProcess = new JProgressBar();
jProgressBarProcess.setPreferredSize(new Dimension(200, 22));
}
return jProgressBarProcess;
}
public void setNumberOfFilesMax(int nuberOfFiles) {
jProgressBarProcess.setMinimum(0);
jProgressBarProcess.setMaximum(nuberOfFiles);
}
public void setNumberNextFile() {
jProgressBarProcess.setValue(jProgressBarProcess.getValue()+1);
}
public void setProcessDescription(boolean zip, String srcName) {
int maxLength = 60;
String shortNameOfFileOrFolder = null;
if (srcName.length()<=maxLength) {
shortNameOfFileOrFolder = srcName;
shortNameOfFileOrFolder = " '" + srcName + "':";
} else {
shortNameOfFileOrFolder = srcName.substring(srcName.length()-maxLength , srcName.length());
shortNameOfFileOrFolder = " '..." + shortNameOfFileOrFolder + "':";
}
if (zip==true) {
jLabelProcess.setText(Language.translate("Packe") + shortNameOfFileOrFolder);
} else {
jLabelProcess.setText(Language.translate("Entpacke") + shortNameOfFileOrFolder);
}
}
public void setCurrentJobFile(String fileName) {
File file = new File(fileName);
jLabelSingleFile.setText(Language.translate("Datei:") + " '" + file.getName() + "':");
}
/**
* This method initializes jButtonCancel
* @return javax.swing.JButton
*/
private JButton getJButtonCancel() {
if (jButtonCancel == null) {
jButtonCancel = new JButton();
jButtonCancel.setText("Abbruch");
jButtonCancel.setPreferredSize(new Dimension(134, 28));
jButtonCancel.setForeground(new Color(204, 0, 0));
jButtonCancel.setFont(new Font("Dialog", Font.BOLD, 12));
jButtonCancel.addActionListener(this);
}
return jButtonCancel;
}
/**
* @param canceld the canceld to set
*/
public void setCanceled(boolean canceld) {
this.canceled = canceld;
}
/**
* @return the canceld
*/
public boolean isCanceled() {
return canceled;
}
@Override
public void actionPerformed(ActionEvent act) {
Object actor = act.getSource();
if (actor.equals(jButtonCancel)) {
this.setCanceled(true);
}
}
} // @jve:decl-index=0:visual-constraint="59,16"
|
package org.openhealthtools.mdht.uml.cda.core.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.common.util.UML2Util;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.util.UMLSwitch;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationship;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationshipKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Inline;
import org.openhealthtools.mdht.uml.cda.core.profile.LogicalConstraint;
import org.openhealthtools.mdht.uml.cda.core.profile.LogicalOperator;
import org.openhealthtools.mdht.uml.cda.core.profile.SeverityKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Validation;
import org.openhealthtools.mdht.uml.cda.core.profile.ValidationKind;
import org.openhealthtools.mdht.uml.common.util.NamedElementUtil;
import org.openhealthtools.mdht.uml.common.util.PropertyList;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.BindingKind;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;
import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;
public class CDAModelUtil {
public static final String CDA_PACKAGE_NAME = "cda";
public static final String DATATYPES_NS_URI = "http:
/** This base URL may be set from preferences or Ant task options. */
public static String INFOCENTER_URL = "http:
public static final String SEVERITY_ERROR = "ERROR";
public static final String SEVERITY_WARNING = "WARNING";
public static final String SEVERITY_INFO = "INFO";
private static final String EPACKAGE = "Ecore::EPackage";
private static final String EREFERENCE = "Ecore::EReference";
public static final String XMLNAMESPACE = "xmlNamespace";
private static final String NSPREFIX = "nsPrefix";
private static final String NSURI = "nsURI";
// This message may change in the future to specify certain nullFlavor Types (such as the implementation, NI)
private static final String NULLFLAVOR_SECTION_MESSAGE = "If section/@nullFlavor is not present, ";
public static boolean cardinalityAfterElement = false;
public static boolean disablePdfGeneration = false;
public static boolean isAppendConformanceRules = false;
public static Class getCDAClass(Classifier templateClass) {
Class cdaClass = null;
// if the provided class is from CDA and not a template
if (isCDAModel(templateClass) && templateClass instanceof Class) {
return (Class) templateClass;
}
for (Classifier parent : templateClass.allParents()) {
// nearest package may be null if CDA model is not available
if (parent.getNearestPackage() != null) {
if (isCDAModel(parent) && parent instanceof Class) {
cdaClass = (Class) parent;
break;
}
}
}
return cdaClass;
}
public static Property getCDAProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
// if the provided property is from a CDA class/datatype and not a template
if (isCDAModel(templateProperty) || isDatatypeModel(templateProperty)) {
return templateProperty;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName() != null && inherited.getName().equals(templateProperty.getName()) &&
(isCDAModel(inherited) || isDatatypeModel(inherited))) {
return inherited;
}
}
}
return null;
}
/**
* Returns the nearest inherited property with the same name, or null if not found.
*
* @deprecated Use the {@link UMLUtil#getInheritedProperty(Property)} API, instead.
*/
@Deprecated
public static Property getInheritedProperty(Property templateProperty) {
// for CDA, we restrict to Classes, not other classifiers
if (templateProperty.getClass_() == null) {
return null;
}
return UMLUtil.getInheritedProperty(templateProperty);
}
public static boolean isDatatypeModel(Element element) {
if (element != null && element.getNearestPackage() != null) {
Stereotype ePackage = element.getNearestPackage().getAppliedStereotype("Ecore::EPackage");
if (ePackage != null) {
return DATATYPES_NS_URI.equals(element.getNearestPackage().getValue(ePackage, "nsURI"));
}
}
return false;
}
/**
* isCDAModel - use get top package to support nested uml packages within CDA model
* primarily used for extensions
*
*/
public static boolean isCDAModel(Element element) {
if (element != null) {
Package neareastPackage = element.getNearestPackage();
if (neareastPackage != null) {
Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(neareastPackage);
return CDA_PACKAGE_NAME.equals((topPackage != null)
? topPackage.getName()
: "");
}
}
return false;
}
public static Class getCDADatatype(Classifier datatype) {
Class result = null;
// if the provided class is from CDA datatypes
if (isDatatypeModel(datatype) && (datatype instanceof Class)) {
result = (Class) datatype;
} else {
for (Classifier parent : datatype.allParents()) {
// nearest package may be null if CDA datatypes model is not available
if (parent.getNearestPackage() != null) {
if (isDatatypeModel(parent) && (parent instanceof Class)) {
result = (Class) parent;
break;
}
}
}
}
return result;
}
public static boolean isCDAType(Type templateClass, String typeName) {
if (templateClass instanceof Class && typeName != null) {
Class cdaClass = getCDAClass((Class) templateClass);
if (cdaClass != null && typeName.equals(cdaClass.getName())) {
return true;
}
}
return false;
}
public static boolean isClinicalDocument(Type templateClass) {
return isCDAType(templateClass, "ClinicalDocument");
}
public static boolean isSection(Type templateClass) {
return isCDAType(templateClass, "Section");
}
public static boolean isOrganizer(Type templateClass) {
return isCDAType(templateClass, "Organizer");
}
public static boolean isEntry(Type templateClass) {
return isCDAType(templateClass, "Entry");
}
public static boolean isClinicalStatement(Type templateClass) {
if (templateClass instanceof Class) {
Class cdaClass = getCDAClass((Class) templateClass);
String cdaName = cdaClass == null
? null
: cdaClass.getName();
if (cdaClass != null && ("Act".equals(cdaName) || "Encounter".equals(cdaName) ||
"Observation".equals(cdaName) || "ObservationMedia".equals(cdaName) ||
"Organizer".equals(cdaName) || "Procedure".equals(cdaName) || "RegionOfInterest".equals(cdaName) ||
"SubstanceAdministration".equals(cdaName) || "Supply".equals(cdaName))) {
return true;
}
}
return false;
}
public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {
final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(Collections.singletonList(element));
while (iterator != null && iterator.hasNext()) {
EObject child = iterator.next();
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
iterator.prune();
return association;
}
@Override
public Object caseClass(Class umlClass) {
String message = computeConformanceMessage(umlClass, markup);
stream.println(message);
return umlClass;
}
@Override
public Object caseGeneralization(Generalization generalization) {
String message = computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
stream.println(message);
}
return generalization;
}
@Override
public Object caseProperty(Property property) {
String message = computeConformanceMessage(property, markup);
if (message.length() > 0) {
stream.println(message);
}
return property;
}
@Override
public Object caseConstraint(Constraint constraint) {
String message = computeConformanceMessage(constraint, markup);
if (message.length() > 0) {
stream.println(message);
}
return constraint;
}
};
umlSwitch.doSwitch(child);
}
}
public static String getValidationMessage(Element element) {
return getValidationMessage(element, ICDAProfileConstants.VALIDATION);
}
/**
* Obtains the user-specified validation message recorded in the given stereotype, or else
* {@linkplain #computeConformanceMessage(Element, boolean) computes} a suitable conformance message if none.
*
* @param element
* an element on which a validation constraint stereotype is defined
* @param validationStereotypeName
* the stereotype name (may be the abstract {@linkplain ICDAProfileConstants#VALIDATION Validation} stereotype)
*
* @return the most appropriate validation/conformance message
*
* @see #computeConformanceMessage(Element, boolean)
*/
public static String getValidationMessage(Element element, String validationStereotypeName) {
String message = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);
if (validationSupport != null) {
message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);
}
if (message == null || message.length() == 0) {
message = computeConformanceMessage(element, false);
}
return message;
}
public static String computeConformanceMessage(Element element, final boolean markup) {
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
String message = null;
Property property = getNavigableEnd(association);
if (property != null) {
message = computeConformanceMessage(property, false);
}
return message;
}
@Override
public Object caseClass(Class umlClass) {
return computeConformanceMessage(umlClass, markup);
}
@Override
public Object caseGeneralization(Generalization generalization) {
return computeConformanceMessage(generalization, markup);
}
@Override
public Object caseProperty(Property property) {
return computeConformanceMessage(property, markup);
}
@Override
public Object caseConstraint(Constraint constraint) {
return computeConformanceMessage(constraint, markup);
}
};
return (String) umlSwitch.doSwitch(element);
}
public static String computeConformanceMessage(Class template, final boolean markup) {
String templateId = getTemplateId(template);
String templateVersion = getTemplateVersion(template);
String ruleIds = getConformanceRuleIds(template);
if (templateId == null) {
templateId = "";
}
String templateMultiplicity = CDATemplateComputeBuilder.getMultiplicityRange(getMultiplicityRange(template));
final String templateIdAsBusinessName = "=\"" + templateId + "\"";
final String templateVersionAsBusinessName = "=\"" + templateVersion + "\"";
final String multiplicityRange = templateMultiplicity.isEmpty()
? ""
: " [" + templateMultiplicity + "]";
CDATemplateComputeBuilder cdaTemplater = new CDATemplateComputeBuilder() {
@Override
public String addTemplateIdMultiplicity() {
return multiplicityElementToggle(markup, "templateId", multiplicityRange, "");
}
@Override
public String addRootMultiplicity() {
return multiplicityElementToggle(markup, "@root", " [1..1]", templateIdAsBusinessName);
}
@Override
public String addTemplateVersion() {
return multiplicityElementToggle(markup, "@extension", " [1..1]", templateVersionAsBusinessName);
}
};
return cdaTemplater.setRequireMarkup(markup).setRuleIds(ruleIds).setTemplateVersion(
templateVersion).setMultiplicity(multiplicityRange).compute().toString();
}
public static String computeConformanceMessage(Generalization generalization, boolean markup) {
return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));
}
public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {
Class general = (Class) generalization.getGeneral();
StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource));
appendConformanceRuleIds(generalization, message, markup);
return message.toString();
}
public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
String prefix = !UMLUtil.isSameModel(xrefSource, general)
? getModelPrefix(general) + " "
: "";
String xref = computeXref(xrefSource, general);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
Class cdaGeneral = getCDAClass(general);
if (cdaGeneral != null) {
message.append(markup
? "<b>"
: "");
message.append("SHALL");
message.append(markup
? "</b>"
: "");
message.append(" conform to ");
} else {
message.append("Extends ");
}
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(general));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(general);
String templateVersion = getTemplateVersion(general);
if (templateId != null) {
message.append(" template (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
// if there is an extension, add a colon followed by its value
if (!StringUtils.isEmpty(templateVersion)) {
message.append(":" + templateVersion);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String getBusinessName(NamedElement property) {
String businessName = NamedElementUtil.getBusinessName(property);
if (!property.getName().equals(businessName)) {
return (" (" + businessName + ")");
}
return "";
}
private static StringBuffer multiplicityElementToggle(Property property, boolean markup, String elementName) {
StringBuffer message = new StringBuffer();
message.append(
multiplicityElementToggle(markup, elementName, getMultiplicityRange(property), getBusinessName(property)));
return message;
}
private static String multiplicityElementToggle(boolean markup, String elementName, String multiplicityRange,
String businessName) {
StringBuffer message = new StringBuffer();
if (!cardinalityAfterElement) {
message.append(multiplicityRange);
}
message.append(" ");
message.append(markup
? "<tt><b>"
: "");
message.append(elementName);
message.append(markup
? "</b>"
: "");
message.append(businessName);
message.append(markup
? "</tt>"
: "");
if (cardinalityAfterElement) {
message.append(multiplicityRange);
}
return message.toString();
}
public static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource,
boolean appendNestedConformanceRules) {
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (!isInlineClass(endType) && getTemplateId(property.getClass_()) != null) {
return computeTemplateAssociationConformanceMessage(
property, markup, xrefSource, appendNestedConformanceRules);
}
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeywordWithPropertyRange(association, property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
if (property.getUpper() == 0 && isClosed(property)) {
message.append("any ");
}
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
if (property.getUpper() == 0 && isClosed(property)) {
message.append("any ");
}
}
String elementName = getCDAElementName(property);
message.append(getMultiplicityText(property));
message.append(multiplicityElementToggle(property, markup, elementName));
// appendSubsetsNotation(property, message, markup, xrefSource);
if (appendNestedConformanceRules && endType != null) {
if (markup && isInlineClass(endType) && !isPublishSeperately(endType)) {
StringBuilder sb = new StringBuilder();
message.append(openOrClosed(property));
// message.append(", where its type is ");
appendConformanceRuleIds(association, message, markup);
appendPropertyComments(sb, property, markup);
// // (property.getUpper() == 1,? "This "
// : "Such ") +
// (property.getUpper() == 1
// ? elementName
// : NameUtilities.pluralize(elementName)) +
appendConformanceRules(sb, endType, "", markup);
message.append(" " + sb + " ");
} else {
message.append(", where its type is ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
appendConformanceRuleIds(association, message, markup);
}
} else {
appendConformanceRuleIds(association, message, markup);
}
return message.toString();
}
private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup,
Package xrefSource, boolean appendNestedConformanceRules) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
String elementName = getCDAElementName(property);
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
// errata 384 message support: if the class owner is a section, and it has an association
// to either a clinical statement or an Entry (Act, Observation, etc.), append the message
for (Property p : association.getMemberEnds()) {
if ((p.getName() != null && !p.getName().isEmpty()) && (p.getOwner() != null && p.getType() != null) &&
(isSection((Class) p.getOwner()) && isClinicalStatement(p.getType()) || isEntry(p.getType()))) {
message.append(NULLFLAVOR_SECTION_MESSAGE);
}
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
message.append(multiplicityElementToggle(property, markup, elementName));
appendConformanceRuleIds(association, message, markup);
if (appendNestedConformanceRules && property.getType() instanceof Class) {
Class inlinedClass = (Class) property.getType();
if (markup && isInlineClass(inlinedClass)) {
StringBuilder sb = new StringBuilder();
appendPropertyComments(sb, property, markup);
appendConformanceRules(sb, inlinedClass, (property.getUpper() == 1
? "This "
: "Such ") +
(property.getUpper() == 1
? elementName
: NameUtilities.pluralize(elementName)) +
" ",
markup);
message.append(" " + sb);
}
}
if (!markup) {
String assocConstraints = computeAssociationConstraints(property, markup);
if (assocConstraints.length() > 0) {
message.append(assocConstraints);
}
}
return message.toString();
}
public static String computeAssociationConstraints(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
Package xrefSource = UMLUtil.getTopPackage(property);
EntryRelationship entryRelationship = CDAProfileUtil.getEntryRelationship(association);
EntryRelationshipKind typeCode = entryRelationship != null
? entryRelationship.getTypeCode()
: null;
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (typeCode != null) {
message.append(markup
? "\n<li>"
: " ");
message.append("Contains ");
message.append(markup
? "<tt><b>"
: "").append("@typeCode=\"").append(
markup
? "</b>"
: "");
message.append(typeCode).append("\" ");
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<i>"
: "");
message.append(typeCode.getLiteral());
message.append(markup
? "</i>"
: "");
message.append(markup
? "</li>"
: ", and");
}
// TODO: what I should really do is test for an *implied* ActRelationship or Participation association
if (endType != null && getCDAClass(endType) != null && !(isInlineClass(endType)) &&
!isInlineClass(property.getClass_())) {
message.append(markup
? "\n<li>"
: " ");
message.append("Contains exactly one [1..1] ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(endType);
String templateVersion = getTemplateVersion(endType);
if (templateId != null) {
message.append(" (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
// if there is an extension, add a colon followed by its value
if (!StringUtils.isEmpty(templateVersion)) {
message.append(":" + templateVersion);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
message.append(markup
? "</li>"
: "");
}
return message.toString();
}
public static String computeConformanceMessage(Property property, boolean markup) {
return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));
}
private static String getNameSpacePrefix(Property property) {
Property cdaBaseProperty = CDAModelUtil.getCDAProperty(property);
String nameSpacePrefix = null;
if (cdaBaseProperty != null) {
Stereotype eReferenceStereoetype = cdaBaseProperty.getAppliedStereotype(CDAModelUtil.EREFERENCE);
if (eReferenceStereoetype != null) {
String nameSpace = (String) cdaBaseProperty.getValue(eReferenceStereoetype, CDAModelUtil.XMLNAMESPACE);
if (!StringUtils.isEmpty(nameSpace)) {
Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(
cdaBaseProperty.getNearestPackage());
Stereotype ePackageStereoetype = topPackage.getApplicableStereotype(CDAModelUtil.EPACKAGE);
if (ePackageStereoetype != null) {
if (nameSpace.equals(topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {
nameSpacePrefix = (String) topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSPREFIX);
} else {
for (Package nestedPackage : topPackage.getNestedPackages()) {
if (nameSpace.equals(nestedPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {
nameSpacePrefix = (String) nestedPackage.getValue(
ePackageStereoetype, CDAModelUtil.NSPREFIX);
}
}
}
}
}
}
}
return nameSpacePrefix;
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {
return computeConformanceMessage(property, markup, xrefSource, true);
}
private static String openOrClosed(Property property) {
if (isClosed(property)) {
return " ";
} else {
return " such that it ";
}
}
private static boolean isClosed(Property property) {
Validation validation = org.eclipse.uml2.uml.util.UMLUtil.getStereotypeApplication(
(property.getAssociation() != null
? property.getAssociation()
: property),
Validation.class);
if (validation != null && validation.getKind().equals(ValidationKind.CLOSED)) {
return true;
} else {
return false;
}
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource,
boolean appendNestedConformanceRules) {
if (property.getType() == null) {
System.out.println("Property has null type: " + property.getQualifiedName());
}
if (property.getAssociation() != null && property.isNavigable()) {
return computeAssociationConformanceMessage(property, markup, xrefSource, appendNestedConformanceRules);
}
StringBuffer message = new StringBuffer();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeywordWithPropertyRange(property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
if (property.getUpper() == 0 && isClosed(property)) {
message.append("any ");
}
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
if (property.getUpper() == 0 && isClosed(property)) {
message.append("any ");
}
}
message.append(getMultiplicityText(property));
if (!cardinalityAfterElement) {
message.append(getMultiplicityRange(property));
}
message.append(" ");
message.append(markup
? "<tt><b>"
: "");
// classCode/moodCode
if (isXMLAttribute(property)) {
message.append("@");
}
String propertyPrefix = getNameSpacePrefix(property);
// Try to get CDA Name
IExtensionRegistry reg = Platform.getExtensionRegistry();
IExtensionPoint ep = reg.getExtensionPoint("org.openhealthtools.mdht.uml.cda.core.TransformProvider");
IExtension[] extensions = ep.getExtensions();
TransformProvider newContributor = null;
Property cdaProperty = null;
try {
newContributor = (TransformProvider) extensions[0].getConfigurationElements()[0].createExecutableExtension(
"transform-class");
cdaProperty = newContributor.GetTransform(property);
} catch (Exception e) {
e.printStackTrace();
}
String propertyCdaName = null;
if (cdaProperty != null) {
propertyCdaName = getCDAName(cdaProperty);
} else {
propertyCdaName = getCDAElementName(property);
}
message.append(propertyPrefix != null
? propertyPrefix + ":" + propertyCdaName
: propertyCdaName);
message.append(markup
? "</b>"
: "");
message.append(getBusinessName(property));
if (property.getDefault() != null) {
message.append("=\"").append(property.getDefault()).append("\" ");
}
message.append(markup
? "</tt>"
: "");
if (cardinalityAfterElement) {
message.append(getMultiplicityRange(property));
}
Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.NULL_FLAVOR);
Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property, ICDAProfileConstants.TEXT_VALUE);
if (nullFlavorSpecification != null) {
String nullFlavor = getLiteralValue(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);
Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(
ICDAProfileConstants.NULL_FLAVOR_KIND);
String nullFlavorLabel = getLiteralValueLabel(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);
if (nullFlavor != null) {
message.append(markup
? "<tt>"
: "");
message.append("/@nullFlavor");
message.append(markup
? "</tt>"
: "");
message.append(" = \"").append(nullFlavor).append("\" ");
message.append(markup
? "<i>"
: "");
message.append(nullFlavorLabel);
message.append(markup
? "</i>"
: "");
}
}
if (textValue != null) {
String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);
if (value != null && value.length() > 0) {
SeverityKind level = (SeverityKind) property.getValue(
textValue, ICDAProfileConstants.VALIDATION_SEVERITY);
message.append(" and ").append(markup
? "<b>"
: "").append(
level != null
? getValidationKeyword(level.getLiteral())
: keyword).append(
markup
? "</b>"
: "").append(" equal \"").append(value).append("\"");
}
}
if (property.getType() instanceof Classifier && cdaProperty != null &&
cdaProperty.getType() instanceof Classifier) {
Classifier propertyType = (Classifier) property.getType();
Classifier cdaPropertyType = (Classifier) cdaProperty.getType();
Class propertyCdaType = CDAModelUtil.getCDAClass(propertyType);
if (propertyCdaType == null)
propertyCdaType = CDAModelUtil.getCDADatatype(propertyType);
// if the datatype is not different from the immediate parent, then the xsi:type shouldn't be printed
if (propertyCdaType != null && cdaPropertyType != null && propertyCdaType != cdaPropertyType &&
propertyCdaType.getName() != null && !propertyCdaType.getName().isEmpty()) {
message.append(" with " + "@xsi:type=\"");
message.append(propertyCdaType.getName());
message.append("\"");
}
}
// for vocab properties, put rule ID at end, use terminology constraint if specified
if (isHL7VocabAttribute(property)) {
String ruleIds = getTerminologyConformanceRuleIds(property);
// if there are terminology rule IDs, then include property rule IDs here
if (ruleIds.length() > 0) {
appendConformanceRuleIds(property, message, markup);
}
} else {
// PropertyConstraint stereotype ruleIds, if specified
appendConformanceRuleIds(property, message, markup);
}
Stereotype codeSystemConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
Stereotype valueSetConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
if (codeSystemConstraint != null) {
String vocab = computeCodeSystemMessage(property, markup);
message.append(vocab);
} else if (valueSetConstraint != null) {
String vocab = computeValueSetMessage(property, markup, xrefSource);
message.append(vocab);
} else if (isHL7VocabAttribute(property) && property.getDefault() != null) {
String vocab = computeHL7VocabAttributeMessage(property, markup);
message.append(vocab);
}
// for vocab properties, put rule ID at end, use terminology constraint if specified
if (isHL7VocabAttribute(property)) {
String ruleIds = getTerminologyConformanceRuleIds(property);
if (ruleIds.length() > 0) {
appendTerminologyConformanceRuleIds(property, message, markup);
} else {
appendConformanceRuleIds(property, message, markup);
}
} else {
// rule IDs for the terminology constraint
appendTerminologyConformanceRuleIds(property, message, markup);
}
if (property.getType() != null && appendNestedConformanceRules && property.getType() instanceof Class) {
if (isInlineClass((Class) property.getType())) {
if (isPublishSeperately((Class) property.getType())) {
String xref = (property.getType() instanceof Classifier &&
UMLUtil.isSameProject(property, property.getType()))
? computeXref(xrefSource, (Classifier) property.getType())
: null;
boolean showXref = markup && (xref != null);
if (showXref) {
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(UMLUtil.splitName(property.getType()));
message.append(showXref
? "</xref>"
: "");
}
} else {
StringBuilder sb = new StringBuilder();
boolean hadSideEffect = appendPropertyComments(sb, property, markup);
if (isAppendConformanceRules) {
int len = sb.length();
appendConformanceRules(sb, (Class) property.getType(), "", markup);
hadSideEffect |= sb.length() > len;
}
if (hadSideEffect) {
message.append(" " + sb);
}
}
}
}
return message.toString();
}
/**
* getCDAName
*
* recursively, depth first, check the object graph for a CDA Name using the root of the "redefined"
* property if it exists.
*
* Also handle special cases like sectionId which has a cdaName of ID
*
* @param cdaProperty
* an MDHT property
* @return string
* the calculated CDA name
*/
private static String getCDAName(Property cdaProperty) {
EList<Property> redefines = cdaProperty.getRedefinedProperties();
// if there is a stereotype name, use it
String name = getStereotypeName(cdaProperty);
if (name != null) {
return name;
}
// if there are redefines, check for more but only along the first branch (0)
if (redefines != null && redefines.size() > 0) {
return getCDAName(redefines.get(0));
}
// eventually return the property Name of the root redefined element;
return cdaProperty.getName();
}
/**
* Get the CDA name from a stereotype if it exists
*
* @param cdaProperty
* a Property
* @return the xmlName or null if no stereotype exists
*/
private static String getStereotypeName(Property cdaProperty) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
String name = null;
if (eAttribute != null) {
name = (String) cdaProperty.getValue(eAttribute, "xmlName");
}
return name;
}
private static void appendSubsetsNotation(Property property, StringBuffer message, boolean markup,
Package xrefSource) {
StringBuffer notation = new StringBuffer();
for (Property subsets : property.getSubsettedProperties()) {
if (subsets.getClass_() == null) {
// eliminate NPE when publishing stereotype references to UML metamodel
continue;
}
if (notation.length() == 0) {
notation.append(" {subsets ");
} else {
notation.append(", ");
}
String xref = computeXref(xrefSource, subsets.getClass_());
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
notation.append(showXref
? " <xref " + format + "href=\"" + xref + "\">"
: " ");
notation.append(UMLUtil.splitName(subsets.getClass_()));
notation.append(showXref
? "</xref>"
: "");
notation.append("::" + subsets.getName());
}
if (notation.length() > 0) {
notation.append("}");
}
message.append(notation);
}
private static final String[] OL = { "<ol>", "</ol>" };
private static final String[] LI = { "<li>", "</li>" };
private static final String[] NOOL = { "", " " };
private static final String[] NOLI = { "", " " };
static private void appendConformanceRules(StringBuilder appendB, Class umlClass, String prefix, boolean markup) {
String[] ol = markup
? OL
: NOOL;
String[] li = markup
? LI
: NOLI;
StringBuilder sb = new StringBuilder();
boolean hasRules = false;
if (!CDAModelUtil.isInlineClass(umlClass)) {
for (Generalization generalization : umlClass.getGeneralizations()) {
Classifier general = generalization.getGeneral();
if (!RIMModelUtil.isRIMModel(general) && !CDAModelUtil.isCDAModel(general)) {
String message = CDAModelUtil.computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
hasRules = true;
sb.append(li[0] + prefix + message + li[1]);
}
}
}
}
// categorize constraints by constrainedElement name
List<Constraint> unprocessedConstraints = new ArrayList<Constraint>();
// propertyName -> constraints
Map<String, List<Constraint>> constraintMap = new HashMap<String, List<Constraint>>();
// constraint -> sub-constraints
Map<Constraint, List<Constraint>> subConstraintMap = new HashMap<Constraint, List<Constraint>>();
for (Constraint constraint : umlClass.getOwnedRules()) {
unprocessedConstraints.add(constraint);
// Do not associate logical constraints with a property because they are a class and not a property constraint
if (CDAProfileUtil.getLogicalConstraint(constraint) == null) {
for (Element element : constraint.getConstrainedElements()) {
if (element instanceof Property) {
String name = ((Property) element).getName();
List<Constraint> rules = constraintMap.get(name);
if (rules == null) {
rules = new ArrayList<Constraint>();
constraintMap.put(name, rules);
}
rules.add(constraint);
} else if (element instanceof Constraint) {
Constraint subConstraint = (Constraint) element;
List<Constraint> rules = subConstraintMap.get(subConstraint);
if (rules == null) {
rules = new ArrayList<Constraint>();
subConstraintMap.put(subConstraint, rules);
}
rules.add(constraint);
}
}
}
}
PropertyList propertyList = new PropertyList(umlClass, CDAModelUtil.isInlineClass(umlClass));
// XML attributes
for (Property property : propertyList.getAttributes()) {
hasRules = hasRules | appendPropertyList(
umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,
subConstraintMap);
}
// XML elements
for (Property property : propertyList.getAssociationEnds()) {
hasRules = hasRules | appendPropertyList(
umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,
subConstraintMap);
}
for (Constraint constraint : unprocessedConstraints) {
hasRules = true;
sb.append(li[0] + prefix + CDAModelUtil.computeConformanceMessage(constraint, markup) + li[1]);
}
if (hasRules) {
appendB.append(ol[0]);
appendB.append(sb);
appendB.append(ol[1]);
}
}
private static boolean appendPropertyList(Element umlClass, Property property, boolean markup, String[] ol,
StringBuilder sb, String prefix, String[] li, Map<String, List<Constraint>> constraintMap,
List<Constraint> unprocessedConstraints, Map<Constraint, List<Constraint>> subConstraintMap) {
boolean result = false;
if (!CDAModelUtil.isCDAModel(umlClass) && !CDAModelUtil.isCDAModel(property) &&
!CDAModelUtil.isDatatypeModel(property)) {
result = true;
String ccm = CDAModelUtil.computeConformanceMessage(property, markup);
boolean order = ccm.trim().endsWith(ol[1]);
boolean currentlyItem = false;
if (order) {
int olIndex = ccm.lastIndexOf(ol[1]);
ccm = ccm.substring(0, olIndex);
currentlyItem = ccm.trim().endsWith(li[1]);
}
sb.append(li[0] + prefix + ccm);
StringBuilder propertyComments = new StringBuilder();
currentlyItem &= appendPropertyComments(propertyComments, property, markup);
if (currentlyItem) {
sb.append(li[0]).append(propertyComments).append(li[1]);
} else {
sb.append(propertyComments);
}
appendPropertyRules(sb, property, constraintMap, subConstraintMap, unprocessedConstraints, markup, !order);
if (order) {
sb.append(ol[1]);
}
sb.append(li[1]);
}
return result;
}
private static boolean appendPropertyComments(StringBuilder sb, Property property, boolean markup) {
// INLINE
Association association = property.getAssociation();
int startingStrLength = sb.length();
if (association != null && association.getOwnedComments().size() > 0) {
if (markup) {
sb.append("<p><lines><i>");
}
for (Comment comment : association.getOwnedComments()) {
sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
sb.append("</i></lines></p>");
}
}
if (property.getOwnedComments().size() > 0) {
if (markup) {
sb.append("<p><lines><i>");
}
for (Comment comment : property.getOwnedComments()) {
sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
sb.append("</i></lines></p>");
}
}
return sb.length() > startingStrLength;
}
private static void appendPropertyRules(StringBuilder sb, Property property,
Map<String, List<Constraint>> constraintMap, Map<Constraint, List<Constraint>> subConstraintMap,
List<Constraint> unprocessedConstraints, boolean markup, boolean newOrder) {
String[] ol = markup && newOrder
? OL
: NOOL;
String[] li = markup
? LI
: NOLI;
// association typeCode and property type
String assocConstraints = "";
if (property.getAssociation() != null) {
assocConstraints = CDAModelUtil.computeAssociationConstraints(property, markup);
}
StringBuffer ruleConstraints = new StringBuffer();
List<Constraint> rules = constraintMap.get(property.getName());
if (rules != null && !rules.isEmpty()) {
for (Constraint constraint : rules) {
unprocessedConstraints.remove(constraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(constraint, markup));
appendSubConstraintRules(ruleConstraints, constraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
}
if (assocConstraints.length() > 0 || ruleConstraints.length() > 0) {
sb.append(ol[0]);
sb.append(assocConstraints);
sb.append(ruleConstraints);
sb.append(ol[1]);
}
}
private static void appendSubConstraintRules(StringBuffer ruleConstraints, Constraint constraint,
Map<Constraint, List<Constraint>> subConstraintMap, List<Constraint> unprocessedConstraints,
boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
List<Constraint> subConstraints = subConstraintMap.get(constraint);
if (subConstraints != null && subConstraints.size() > 0) {
ruleConstraints.append(ol[0]);
for (Constraint subConstraint : subConstraints) {
unprocessedConstraints.remove(subConstraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(subConstraint, markup));
appendSubConstraintRules(
ruleConstraints, subConstraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
ruleConstraints.append(ol[1]);
}
}
private static boolean isHL7VocabAttribute(Property property) {
String name = property.getName();
return "classCode".equals(name) || "moodCode".equals(name) || "typeCode".equals(name);
}
private static String computeHL7VocabAttributeMessage(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Class rimClass = RIMModelUtil.getRIMClass(property.getClass_());
String code = property.getDefault();
String displayName = null;
String codeSystemId = null;
String codeSystemName = null;
if (rimClass != null) {
if ("Act".equals(rimClass.getName())) {
if ("classCode".equals(property.getName())) {
codeSystemName = "HL7ActClass";
codeSystemId = "2.16.840.1.113883.5.6";
if ("ACT".equals(code)) {
displayName = "Act";
} else if ("OBS".equals(code)) {
displayName = "Observation";
}
} else if ("moodCode".equals(property.getName())) {
codeSystemName = "HL7ActMood";
codeSystemId = "2.16.840.1.113883.5.1001";
if ("EVN".equals(code)) {
displayName = "Event";
}
}
}
}
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
if (codeSystemId != null || codeSystemName != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (codeSystemId != null) {
message.append(" ").append(codeSystemId);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeCodeSystemMessage(Property property, boolean markup) {
Stereotype codeSystemConstraintStereotype = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
CodeSystemConstraint codeSystemConstraint = TermProfileUtil.getCodeSystemConstraint(property);
String keyword = getValidationKeyword(property, codeSystemConstraintStereotype);
String id = null;
String name = null;
String code = null;
String displayName = null;
if (codeSystemConstraint != null) {
if (codeSystemConstraint.getReference() != null) {
CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();
id = codeSystemVersion.getIdentifier();
name = codeSystemVersion.getEnumerationName();
codeSystemVersion.getVersion();
} else {
id = codeSystemConstraint.getIdentifier();
name = codeSystemConstraint.getName();
codeSystemConstraint.getVersion();
}
codeSystemConstraint.getBinding();
code = codeSystemConstraint.getCode();
displayName = codeSystemConstraint.getDisplayName();
}
StringBuffer message = new StringBuffer();
if (code != null) {
message.append(markup
? "<tt><b>"
: "");
// single value binding
message.append("/@code");
message.append(markup
? "</b>"
: "");
message.append("=\"").append(code).append("\" ");
message.append(markup
? "</tt>"
: "");
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
} else {
// capture and return proper xml binding message based on mandatory or not
message.append(mandatoryOrNotMessage(property));
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from");
}
if (id != null || name != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ").append(name);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {
Stereotype valueSetConstraintStereotype = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property);
String keyword = getValidationKeyword(property, valueSetConstraintStereotype);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String xref = null;
String xrefFormat = "";
boolean showXref = false;
if (valueSetConstraint != null) {
if (valueSetConstraint.getReference() != null) {
ValueSetVersion valueSetVersion = valueSetConstraint.getReference();
id = valueSetVersion.getIdentifier();
name = valueSetVersion.getEnumerationName();
version = valueSetVersion.getVersion();
binding = valueSetVersion.getBinding();
if (valueSetVersion.getBase_Enumeration() != null) {
xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());
}
showXref = markup && (xref != null);
xrefFormat = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
} else {
id = valueSetConstraint.getIdentifier();
name = valueSetConstraint.getName();
version = valueSetConstraint.getVersion();
binding = valueSetConstraint.getBinding();
}
}
StringBuffer message = new StringBuffer();
// capture and return proper xml binding message based on mandatory or not
message.append(mandatoryOrNotMessage(property));
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from ValueSet");
message.append(markup
? "<tt>"
: "");
if (name != null) {
message.append(" ");
message.append(showXref
? "<xref " + xrefFormat + "href=\"" + xref + "\">"
: "");
message.append(name);
message.append(showXref
? "</xref>"
: "");
}
if (id != null) {
message.append(" ").append(id);
}
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<b>"
: "");
message.append(" ").append(binding.getName().toUpperCase());
message.append(markup
? "</b>"
: "");
if (BindingKind.STATIC == binding && version != null) {
message.append(" ").append(version);
}
return message.toString();
}
public static String computeConformanceMessage(Constraint constraint, boolean markup) {
LogicalConstraint logicConstraint = CDAProfileUtil.getLogicalConstraint(constraint);
if (logicConstraint != null) {
return computeLogicalConformanceMessage(constraint, logicConstraint, markup);
} else {
return computeCustomConformanceMessage(constraint, markup);
}
}
private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {
StringBuffer message = new StringBuffer();
String strucTextBody = null;
String analysisBody = null;
Map<String, String> langBodyMap = new HashMap<String, String>();
CDAProfileUtil.getLogicalConstraint(constraint);
ValueSpecification spec = constraint.getSpecification();
if (spec instanceof OpaqueExpression) {
for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
String lang = ((OpaqueExpression) spec).getLanguages().get(i);
String body = ((OpaqueExpression) spec).getBodies().get(i);
if ("StrucText".equals(lang)) {
strucTextBody = body;
} else if ("Analysis".equals(lang)) {
analysisBody = body;
} else {
langBodyMap.put(lang, body);
}
}
}
String displayBody = null;
if (strucTextBody != null && strucTextBody.trim().length() > 0) {
// TODO if markup, parse strucTextBody and insert DITA markup
displayBody = strucTextBody;
} else if (analysisBody != null && analysisBody.trim().length() > 0) {
Boolean ditaEnabled = false;
try {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION);
ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
} catch (IllegalArgumentException e) { /* Swallow this */
}
if (markup && !ditaEnabled) {
// escape non-dita markup in analysis text
displayBody = escapeMarkupCharacters(analysisBody);
// change severity words to bold text
displayBody = replaceSeverityWithBold(displayBody);
} else {
displayBody = analysisBody;
}
}
if (displayBody == null) {
List<Stereotype> stereotypes = constraint.getAppliedStereotypes();
if (stereotypes.isEmpty()) {
// This should never happen but in case it does we deal with it appropriately
// by bypassing custom constraint message additions
return "";
}
}
if (!markup) {
message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
}
if (displayBody == null || !containsSeverityWord(displayBody)) {
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" satisfy: ");
}
if (displayBody == null) {
message.append(constraint.getName());
} else {
message.append(displayBody);
}
appendConformanceRuleIds(constraint, message, markup);
if (!markup) {
// remove line feeds
int index;
while ((index = message.indexOf("\r")) >= 0) {
message.deleteCharAt(index);
}
while ((index = message.indexOf("\n")) >= 0) {
message.deleteCharAt(index);
if (message.charAt(index) != ' ') {
message.insert(index, " ");
}
}
}
return message.toString();
}
private static String computeLogicalConformanceMessage(Constraint constraint, LogicalConstraint logicConstraint,
boolean markup) {
StringBuffer message = new StringBuffer();
logicConstraint.getMessage();
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
// Wording for IFTHEN - IF xxx then SHALL yyy
if (!logicConstraint.getOperation().equals(LogicalOperator.IFTHEN)) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
}
switch (logicConstraint.getOperation()) {
case XOR:
message.append(" contain one and only one of the following ");
break;
case AND:
message.append(" contain all of the following ");
break;
case OR:
message.append(" contain one or more of the following ");
case IFTHEN:
message.append("if ");
break;
case NOTBOTH:
message.append(" contain zero or one of the following but not both ");
break;
default:
message.append(" satisfy the following ");
break;
}
if (logicConstraint.getOperation().equals(LogicalOperator.IFTHEN) &&
constraint.getConstrainedElements().size() == 2) {
String propertyKeyword = getValidationKeyword(constraint.getConstrainedElements().get(0));
if (propertyKeyword != null) {
message.append(
computeConformanceMessage(constraint.getConstrainedElements().get(0), markup).replace(
propertyKeyword, ""));
} else {
message.append(computeConformanceMessage(constraint.getConstrainedElements().get(0), markup));
}
message.append(" then it ").append(markup
? "<lines>"
: "").append(
markup
? "<b>"
: "").append(keyword).append(
markup
? "</b> "
: " ");
message.append(computeConformanceMessage(constraint.getConstrainedElements().get(1), markup));
message.append(markup
? "</lines>"
: "");
} else {
if (markup) {
message.append("<ul>");
}
for (Element element : constraint.getConstrainedElements()) {
message.append(LI[0]);
message.append(computeConformanceMessage(element, markup));
message.append(LI[1]);
}
if (markup) {
message.append("</ul>");
}
}
appendConformanceRuleIds(constraint, message, markup);
return message.toString();
}
private static boolean containsSeverityWord(String text) {
return text.indexOf("SHALL") >= 0 || text.indexOf("SHOULD") >= 0 || text.indexOf("MAY") >= 0;
}
private static String replaceSeverityWithBold(String input) {
String output;
output = input.replaceAll("SHALL", "<b>SHALL</b>");
output = output.replaceAll("SHOULD", "<b>SHOULD</b>");
output = output.replaceAll("MAY", "<b>MAY</b>");
output = output.replaceAll("\\<b>SHALL\\</b> NOT", "<b>SHALL NOT</b>");
output = output.replaceAll("\\<b>SHOULD\\</b> NOT", "<b>SHOULD NOT</b>");
return output;
}
/**
* FindResourcesByNameVisitor searches the resource for resources of a particular name
* You would think there was a method for this already but i could not find it
*
* @author seanmuir
*
*/
public static class FindResourcesByNameVisitor implements IResourceVisitor {
private String resourceName;
private ArrayList<IResource> resources = new ArrayList<IResource>();
/**
* @return the resources
*/
public ArrayList<IResource> getResources() {
return resources;
}
/**
* @param resourceName
*/
public FindResourcesByNameVisitor(String resourceName) {
super();
this.resourceName = resourceName;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core.resources.IResource)
*/
public boolean visit(IResource arg0) throws CoreException {
if (resourceName != null && resourceName.equals(arg0.getName())) {
resources.add(arg0);
}
return true;
}
}
public static IProject getElementModelProject(Element element) {
try {
Package elementPackage = UMLUtil.getTopPackage(element);
if (elementPackage != null && elementPackage.eResource() != null) {
FindResourcesByNameVisitor visitor = new FindResourcesByNameVisitor(
elementPackage.eResource().getURI().lastSegment());
IWorkspace iw = org.eclipse.core.resources.ResourcesPlugin.getWorkspace();
iw.getRoot().accept(visitor);
if (!visitor.getResources().isEmpty()) {
return visitor.getResources().get(0).getProject();
}
}
} catch (CoreException e) {
// If there is an issue with the workspace - return null
}
return null;
}
public static IProject getModelDocProject(IProject modelProject) {
if (modelProject != null && modelProject.exists()) {
return org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getProject(
modelProject.getName().replace(".model", ".doc"));
}
return null;
}
/**
* computeXref returns the XREF for DITA publication
*
* TODO Refactor and move out of model util
*
* @param source
* @param target
* @return
*/
public static String computeXref(Element source, Classifier target) {
if (target == null) {
return null;
}
if (target instanceof Enumeration) {
return computeTerminologyXref(source, (Enumeration) target);
}
if (UMLUtil.isSameProject(source, target)) {
return "../" + normalizeCodeName(target.getName()) + ".dita";
}
// If the model project is available (should be) and the dita content is part of the doc project
if (!isCDAModel(target)) {
IProject sourceProject = getElementModelProject(source);
sourceProject = getModelDocProject(sourceProject);
IProject targetProject = getElementModelProject(target);
targetProject = getModelDocProject(targetProject);
if (targetProject != null && sourceProject != null) {
IPath projectPath = new Path("/dita/classes/" + targetProject.getName());
IFolder referenceDitaFolder = sourceProject.getFolder(projectPath);
if (referenceDitaFolder.exists()) {
return "../" + targetProject.getName() + "/classes/" + normalizeCodeName(target.getName()) +
".dita";
}
}
String pathFolder = "classes";
String basePackage = "";
String prefix = "";
String packageName = target.getNearestPackage().getName();
if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.hl7.rim";
} else if (CDA_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.cda";
} else {
basePackage = getModelBasePackage(target);
prefix = getModelNamespacePrefix(target);
}
if (basePackage == null || basePackage.trim().length() == 0) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
if (prefix != null && prefix.trim().length() > 0) {
prefix += ".";
}
return INFOCENTER_URL + "/topic/" + basePackage + "." + prefix + "doc/" + pathFolder + "/" +
normalizeCodeName(target.getName()) + ".html";
}
return null;
}
protected static String computeTerminologyXref(Element source, Enumeration target) {
String href = null;
if (UMLUtil.isSameProject(source, target)) {
href = "../../terminology/" + normalizeCodeName(target.getName()) + ".dita";
}
return href;
}
public static Property getNavigableEnd(Association association) {
Property navigableEnd = null;
for (Property end : association.getMemberEnds()) {
if (end.isNavigable()) {
if (navigableEnd != null) {
return null; // multiple navigable ends
}
navigableEnd = end;
}
}
return navigableEnd;
}
/**
* getExtensionNamespace returns the name space from a extension package in the CDA model
*
* @param type
* @return
*/
private static String getExtensionNamespace(Type type) {
String nameSpace = null;
if (type != null && type.getNearestPackage() != null &&
!CDA_PACKAGE_NAME.equals(type.getNearestPackage().getName())) {
Stereotype ecoreStereotype = type.getNearestPackage().getAppliedStereotype(EPACKAGE);
if (ecoreStereotype != null) {
Object object = type.getNearestPackage().getValue(ecoreStereotype, NSPREFIX);
if (object instanceof String) {
nameSpace = (String) object;
}
}
}
return nameSpace;
}
public static String getNameSpacePrefix(Class cdaSourceClass) {
if (cdaSourceClass != null && cdaSourceClass.getPackage() != null &&
!CDA_PACKAGE_NAME.equals(cdaSourceClass.getPackage().getName())) {
Stereotype ecoreStereotype = cdaSourceClass.getPackage().getAppliedStereotype(EPACKAGE);
if (ecoreStereotype != null) {
Object object = cdaSourceClass.getPackage().getValue(ecoreStereotype, NSPREFIX);
if (object instanceof String) {
return (String) object;
}
}
}
return null;
}
/**
* getCDAElementName - Returns the CDA Element name as a string
*
* @TODO Refactor to use org.openhealthtools.mdht.uml.transform.ecore.TransformAbstract.getInitialProperty(Property)
*
* Currently walk the redefines to see if we can match the CDA property using the name and type
* If none found - for backwards compatibility we look for a property in the base class with a matching type which is potential error prone
* If none still - leverage the getassociation
*
* @param property
* @return
*/
public static String getCDAElementName(Property property) {
String elementName = null;
if (property.getType() instanceof Class) {
Class cdaSourceClass = getCDAClass(property.getClass_());
if (cdaSourceClass != null) {
// First check for definitions
for (Property redefinedProperty : property.getRedefinedProperties()) {
// This will never succeed for associations, does not include ActRelationship
if (redefinedProperty.getType() != null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
redefinedProperty.getName(), getCDAClass((Classifier) redefinedProperty.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
break;
}
}
}
// Next check using property type and name
if (elementName == null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
property.getName(), getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
}
}
// Ultimately use original logic for backwards compatibility
if (elementName == null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
null, getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
}
}
}
}
// look for CDA association class element name, e.g. "component"
if (elementName == null) {
elementName = getCDAAssociationElementName(property);
}
if (elementName == null) {
elementName = property.getName();
}
return elementName;
}
public static String getCDAAssociationElementName(Property property) {
Class cdaSourceClass = getCDAClass(property.getClass_());
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
Class cdaTargetClass = endType != null
? getCDAClass(endType)
: null;
// This is incomplete determination of XML element name, but same logic as used in model transform
String elementName = null;
if (cdaSourceClass == null) {
elementName = property.getName();
} else if ("ClinicalDocument".equals(cdaSourceClass.getName()) &&
(CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) {
elementName = "component";
} else if (CDAModelUtil.isSection(cdaSourceClass) && (CDAModelUtil.isSection(cdaTargetClass))) {
elementName = "component";
} else if (CDAModelUtil.isSection(cdaSourceClass) &&
(CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) {
elementName = "entry";
} else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "component";
} else
if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "entryRelationship";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&
"ParticipantRole".equals(cdaTargetClass.getName())) {
elementName = "participant";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&
"AssignedEntity".equals(cdaTargetClass.getName())) {
elementName = "performer";
}
return elementName;
}
private static String getMultiplicityRange(Property property) {
StringBuffer message = new StringBuffer();
String lower = Integer.toString(property.getLower());
String upper = property.getUpper() == -1
? "*"
: Integer.toString(property.getUpper());
message.append(" [").append(lower).append("..").append(upper).append("]");
return message.toString();
}
private static String getMultiplicityText(Property property) {
StringBuffer message = new StringBuffer();
if (property.getLower() == property.getUpper()) {
// Upper and lower equal and not zero
if (property.getLower() != 0) {
message.append("exactly ").append(convertNumberToWords(property.getUpper()));
}
} else if (property.getLower() == 0) {
// Lower is zero
if (property.getUpper() == 0) {
} else if (property.getUpper() == 1) {
message.append("zero or one");
} else if (property.getUpper() == -1) {
message.append("zero or more");
} else {
message.append("not more than " + convertNumberToWords(property.getUpper()));
}
} else if (property.getLower() == 1) {
// Lower is one
if (property.getUpper() == -1) {
message.append("at least one");
} else {
message.append(
"at least " + convertNumberToWords(property.getLower()) + " and not more than " +
convertNumberToWords(property.getUpper()));
}
} else {
// Lower is greater then 1
message.append("at least " + convertNumberToWords(property.getLower()));
if (property.getUpper() != -1) {
message.append(" and not more than " + convertNumberToWords(property.getUpper()));
}
}
return message.toString();
}
// This snippet may be used freely, as long as the authorship note remains in the source code.
private static final String[] lowNames = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
private static final String[] tensNames = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
private static final String[] bigNames = { "thousand", "million", "billion" };
private static String convertNumberToWords(int n) {
if (n < 0) {
return "minus " + convertNumberToWords(-n);
}
if (n <= 999) {
return convert999(n);
}
String s = null;
int t = 0;
while (n > 0) {
if (n % 1000 != 0) {
String s2 = convert999(n % 1000);
if (t > 0) {
s2 = s2 + " " + bigNames[t - 1];
}
if (s == null) {
s = s2;
} else {
s = s2 + ", " + s;
}
}
n /= 1000;
t++;
}
return s;
}
// Range 0 to 999.
private static String convert999(int n) {
String s1 = lowNames[n / 100] + " hundred";
String s2 = convert99(n % 100);
if (n <= 99) {
return s2;
} else if (n % 100 == 0) {
return s1;
} else {
return s1 + " " + s2;
}
}
// Range 0 to 99.
private static String convert99(int n) {
if (n < 20) {
return lowNames[n];
}
String s = tensNames[n / 10 - 2];
if (n % 10 == 0) {
return s;
}
return s + "-" + lowNames[n % 10];
}
public static boolean isXMLAttribute(Property property) {
Property cdaProperty = getCDAProperty(property);
if (cdaProperty != null) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
if (eAttribute != null) {
return true;
}
}
return false;
}
private static String getMultiplicityRange(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null && template.hasValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY)) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getMultiplicityRange((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getTemplateId(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getTemplateId((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getTemplateVersion(Class template) {
String templateVersion = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateVersion = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_VERSION);
} else {
for (Classifier parent : template.getGenerals()) {
templateVersion = getTemplateId((Class) parent);
if (templateVersion != null) {
break;
}
}
}
return templateVersion;
}
public static String getModelPrefix(Element element) {
String prefix = null;
Package thePackage = UMLUtil.getTopPackage(element);
if (thePackage != null) {
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(
thePackage, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) thePackage.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);
} else if (CDA_PACKAGE_NAME.equals(thePackage.getName())) {
prefix = "CDA";
} else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(thePackage.getName())) {
prefix = "RIM";
}
}
return prefix != null
? prefix
: "";
}
public static String getModelNamespacePrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);
}
return prefix;
}
public static String getModelBasePackage(Element element) {
String basePackage = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);
}
return basePackage;
}
public static String getEcorePackageURI(Element element) {
String nsURI = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);
}
if (nsURI == null) {
// for base models without codegenSupport
if (model.getName().equals("cda")) {
nsURI = "urn:hl7-org:v3";
} else if (model.getName().equals("datatypes")) {
nsURI = "http:
} else if (model.getName().equals("vocab")) {
nsURI = "http:
}
}
return nsURI;
}
public static String getPrefixedSplitName(NamedElement element) {
StringBuffer buffer = new StringBuffer();
String modelPrefix = getModelPrefix(element);
if (modelPrefix != null && modelPrefix.length() > 0) {
buffer.append(modelPrefix).append(" ");
}
buffer.append(UMLUtil.splitName(element));
return buffer.toString();
}
/**
* Returns a list conformance rule IDs.
*/
public static List<String> getConformanceRuleIdList(Element element) {
List<String> ruleIds = new ArrayList<String>();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
ruleIds.add(ruleId);
}
}
return ruleIds;
}
protected static void appendTerminologyConformanceRuleIds(Property property, StringBuffer message, boolean markup) {
String ruleIds = getTerminologyConformanceRuleIds(property);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Property property, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(property);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Association association, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(association);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(element);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Element element, Stereotype stereotype, StringBuffer message,
boolean markup) {
String ruleIds = getConformanceRuleIds(element, stereotype);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Property property) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.PROPERTY_VALIDATION);
return getConformanceRuleIds(property, validationSupport);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getTerminologyConformanceRuleIds(Property property) {
Stereotype terminologyConstraint = getTerminologyConstraint(property);
return getConformanceRuleIds(property, terminologyConstraint);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Association association) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ASSOCIATION_VALIDATION);
return getConformanceRuleIds(association, validationSupport);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return getConformanceRuleIds(element, validationSupport);
}
public static String getConformanceRuleIds(Element element, Stereotype validationSupport) {
StringBuffer ruleIdDisplay = new StringBuffer();
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
if (ruleIdDisplay.length() > 0) {
ruleIdDisplay.append(", ");
}
ruleIdDisplay.append(ruleId);
}
}
return ruleIdDisplay.toString();
}
public static Stereotype getTerminologyConstraint(Element element) {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
element, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);
if (stereotype == null) {
stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
}
if (stereotype == null) {
stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.VALUE_SET_CONSTRAINT);
}
return stereotype;
}
public static boolean hasValidationSupport(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return validationSupport != null;
}
/**
* @deprecated Use {@link #getValidationSeverity(Property, String)} to get the severity for a specific validation stereotype.
* If necessary, this can be the abstract {@link ICDAProfileConstants#VALIDATION Validation} stereotype to get any available
* validation severity.
*/
@Deprecated
public static String getValidationSeverity(Property property) {
return getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);
}
public static String getValidationSeverity(Property property, String validationStereotypeName) {
Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(property, validationStereotypeName);
return getValidationSeverity(property, validationStereotype);
}
public static String getValidationSeverity(Element element) {
// use first available validation stereotype
return getValidationSeverity(element, ICDAProfileConstants.VALIDATION);
}
public static String getValidationSeverity(Element element, String validationStereotypeName) {
Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);
return getValidationSeverity(element, validationStereotype);
}
public static String getValidationSeverity(Element element, Stereotype validationStereotype) {
String severity = null;
if ((validationStereotype != null) && CDAProfileUtil.isValidationStereotype(validationStereotype)) {
Object value = element.getValue(validationStereotype, ICDAProfileConstants.VALIDATION_SEVERITY);
if (value instanceof EnumerationLiteral) {
severity = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
severity = ((Enumerator) value).getName();
}
}
return severity;
}
public static String getValidationKeywordWithPropertyRange(Property property) {
String keyword = getValidationKeyword(property);
return addShallNot(keyword, property);
}
public static String getValidationKeyword(Property property) {
String severity = getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);
if (severity == null) {
// get other validation stereotype, usually for terminology
severity = getValidationSeverity((Element) property);
}
return getValidationKeyword(severity);
}
public static String getValidationKeywordWithPropertyRange(Element element, Property property) {
// use first available validation stereotype
String keyword = getValidationKeyword(element);
return addShallNot(keyword, property);
}
private static String addShallNot(String keyword, Property property) {
if (property.getLower() == 0 && property.getUpper() == 0 &&
("SHALL".equals(keyword) || "SHOULD".equals(keyword))) {
keyword += " NOT";
}
return keyword;
}
public static String getValidationKeyword(Element element) {
// use first available validation stereotype
String severity = getValidationSeverity(element);
return getValidationKeyword(severity);
}
public static String getValidationKeyword(Element element, Stereotype validationStereotype) {
String severity = getValidationSeverity(element, validationStereotype);
return getValidationKeyword(severity);
}
private static String getValidationKeyword(String severity) {
String keyword = null;
if (SEVERITY_INFO.equals(severity)) {
keyword = "MAY";
} else if (SEVERITY_WARNING.equals(severity)) {
keyword = "SHOULD";
} else if (SEVERITY_ERROR.equals(severity)) {
keyword = "SHALL";
}
return keyword;
}
public static void setValidationMessage(Element constrainedElement, String message) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);
}
}
protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
}
return name;
}
protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName,
Enumeration umlEnumeration) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getLabel();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
if (umlEnumeration != null) {
name = umlEnumeration.getOwnedLiteral(name).getLabel();
}
}
return name;
}
public static String fixNonXMLCharacters(String text) {
if (text == null) {
return null;
}
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
// test for unicode characters from copy/paste of MS Word text
if (text.charAt(i) == '\u201D') {
newText.append("\"");
} else if (text.charAt(i) == '\u201C') {
newText.append("\"");
} else if (text.charAt(i) == '\u2019') {
newText.append("'");
} else if (text.charAt(i) == '\u2018') {
newText.append("'");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String escapeMarkupCharacters(String text) {
if (text == null) {
return null;
}
text = fixNonXMLCharacters(text);
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '<') {
newText.append("<");
} else if (text.charAt(i) == '>') {
newText.append(">");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String normalizeCodeName(String name) {
String result = "";
String[] parts = name.split(" ");
for (String part : parts) {
result += part.substring(0, 1).toUpperCase() + part.substring(1);
}
result = UML2Util.getValidJavaIdentifier(result);
return result;
}
private static String mandatoryOrNotMessage(Property curProperty) {
// capture if allows nullFlavor or not
boolean mandatory = CDAProfileUtil.isMandatory(curProperty);
// mandatory implies nullFlavor is NOT allowed ", where the @code "
// non-mandatory implies nullFlavor is allowed ", which "
// return the proper message based on mandatory or not
return mandatory
? ", where the @code "
: ", which ";
}
public static boolean isInlineClass(Class _class) {
Inline inline = CDAProfileUtil.getInline(_class);
if (inline != null) {
return true;
}
if (_class.getOwner() instanceof Class) {
return true;
}
for (Comment comment : _class.getOwnedComments()) {
if (comment.getBody().startsWith("INLINE")) {
return true;
}
}
return false;
}
public static String getInlineFilter(Class inlineClass) {
Inline inline = CDAProfileUtil.getInline(inlineClass);
if (inline != null) {
return inline.getFilter() != null
? inline.getFilter()
: "";
}
String filter = "";
for (Comment comment : inlineClass.getOwnedComments()) {
if (comment.getBody().startsWith("INLINE&")) {
String[] temp = comment.getBody().split("&");
if (temp.length == 2) {
filter = String.format("->select(%s)", temp[1]);
}
break;
}
}
if ("".equals(filter)) {
// search hierarchy
for (Classifier next : inlineClass.getGenerals()) {
if (next instanceof Class) {
filter = getInlineFilter((Class) next);
if (!"".equals(filter)) {
break;
}
}
}
}
return filter;
}
public static boolean isPublishSeperately(Class _class) {
boolean publish = false;
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(_class, ICDAProfileConstants.INLINE);
if (stereotype != null) {
Boolean result = (Boolean) _class.getValue(stereotype, "publishSeperately");
publish = result.booleanValue();
}
return publish;
}
}
|
package com.opengamma.util.functional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sun.jersey.api.client.GenericType;
public final class Functional<S> implements Iterable<S> {
public static <T> T first(Collection<T> collection) {
Iterator<T> it = collection.iterator();
if (it.hasNext()) {
return it.next();
} else {
return null;
}
}
/**
* Creates an array of stings out of supplied objects
*
* @param objs objects out of which string array is created
* @return an array of stings out of supplied objects
*/
public static String[] newStringArray(final Object... objs) {
String[] strings = new String[objs.length];
for (int i = 0; i < objs.length; i++) {
strings[i] = objs[i] != null ? objs[i].toString() : null;
}
return strings;
}
/**
* Creates an array of type V out of provided objects (of type V as well)
*
* @param <V> the object type
* @param array objects out of which the array is created
* @return an array of type V out of provided objects
*/
public static <V> V[] newArray(final V... array) {
return array;
}
/**
* Returns part of the provided map which values are contained by provided set of values
* @param map the map
* @param values the set of values
* @param <K> type of map keys
* @param <V> type of map values
* @return submap of the original map, not null
*/
public static <K, V> Map<K, V> submapByValueSet(final Map<K, V> map, final Set<V> values) {
Map<K, V> submap = new HashMap<K, V>();
for (K key : map.keySet()) {
V value = map.get(key);
if (values.contains(value)) {
submap.put(key, value);
}
}
return submap;
}
/**
* Returns part of the provided map which keys are contained by provided set of keys.
*
* @param map the map, not null
* @param keys the set of keys, not null
* @param <K> type of map keys
* @param <V> type of map values
* @return submap of the original map, not null
*/
public static <K, V> Map<K, V> submapByKeySet(final Map<K, V> map, final Set<K> keys) {
Map<K, V> submap = new HashMap<K, V>();
for (K key : keys) {
if (map.containsKey(key)) {
submap.put(key, map.get(key));
}
}
return submap;
}
/**
* Creates reversed map of type Map<V, Collection<K>> from map of type Map<K, V>.
*
* @param map the underlying map, not null
* @param <K> type of map keys
* @param <V> type of map values
* @return the reversed map, not null
*/
public static <K, V> Map<V, Collection<K>> reverseMap(final Map<K, V> map) {
Map<V, Collection<K>> reversed = new HashMap<V, Collection<K>>();
for (K key : map.keySet()) {
V value = map.get(key);
Collection<K> keys = reversed.get(value);
if (keys == null) {
keys = new ArrayList<K>();
reversed.put(value, keys);
}
keys.add(key);
}
return reversed;
}
/**
* Merges source map into target one by mutating it (overwriting entries if
* the target map already contains the same keys).
*
* @param target the target map, not null
* @param source the source map, not null
* @param <K> type of map keys
* @param <V> type of map values
* @return the merged map, not null
*/
public static <K, V> Map<K, V> merge(final Map<K, V> target, final Map<K, V> source) {
for (K key : source.keySet()) {
target.put(key, source.get(key));
}
return target;
}
/**
* Returns sorted list of elements from unsorted collection.
*
* @param coll unsorted collection
* @param <T> type if elements in unsorted collection (must implement Comparable interface)
* @return list sorted using internal entries' {@link Comparable#compareTo(Object)} compareTo} method.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends Comparable> List<T> sort(final Collection<T> coll) {
List<T> list = new ArrayList<T>(coll);
Collections.sort(list);
return list;
}
@SuppressWarnings("rawtypes")
public static <T extends Comparable> List<T> sortBy(final Collection<T> coll, java.util.Comparator<? super T> comparator) {
List<T> list = new ArrayList<T>(coll);
Collections.sort(list, comparator);
return list;
}
public static <T, S> T reduce(final T acc, final Iterator<? extends S> iter, final Function2<T, S, T> reducer) {
T result = acc;
while (iter.hasNext()) {
result = reducer.execute(result, iter.next());
}
return result;
}
public static <T, S> T reduce(final T acc, final Iterable<? extends S> c, final Function2<T, S, T> reducer) {
final Iterator<? extends S> iter = c.iterator();
return reduce(acc, iter, reducer);
}
public static <T> T reduce(final Iterable<? extends T> c, final Function2<T, T, T> reducer) {
final Iterator<? extends T> iter = c.iterator();
if (iter.hasNext()) {
T acc = iter.next();
return reduce(acc, iter, reducer);
} else {
return null;
}
}
public static <T, S> Map<T, Collection<S>> groupBy(final Iterable<? extends S> c, final Function1<S, T> mapper) {
Map<T, Collection<S>> grouping = new HashMap<T, Collection<S>>();
final Iterator<? extends S> iter = c.iterator();
return reduce(grouping, iter, new Function2<Map<T, Collection<S>>, S, Map<T, Collection<S>>>() {
@Override
public Map<T, Collection<S>> execute(Map<T, Collection<S>> acc, S s) {
T key = mapper.execute(s);
if (!acc.containsKey(key)) {
acc.put(key, new ArrayList<S>());
}
Collection<S> values = acc.get(key);
values.add(s);
return acc;
}
});
}
public static <T> boolean any(final Iterable<? extends T> c, final Function1<T, Boolean> predicate) {
final Iterator<? extends T> iter = c.iterator();
boolean any = false;
while (!any && iter.hasNext()) {
any = predicate.execute(iter.next());
}
return any;
}
public static <T> boolean all(final Iterable<? extends T> c, final Function1<T, Boolean> predicate) {
final Iterator<? extends T> iter = c.iterator();
boolean all = true;
while (all && iter.hasNext()) {
all = predicate.execute(iter.next());
}
return all;
}
public static <T> Function1<T, Boolean> complement(final Function1<T, Boolean> predicate) {
return new Function1<T, Boolean>() {
@Override
public Boolean execute(T t) {
return !predicate.execute(t);
}
};
}
public static <T> List<T> filter(Iterable<? extends T> c, final Function1<T, Boolean> predicate) {
return reduce(new LinkedList<T>(), c, new Function2<LinkedList<T>, T, LinkedList<T>>() {
@Override
public LinkedList<T> execute(LinkedList<T> acc, T e) {
if (predicate.execute(e)) {
acc.add(e);
}
return acc;
}
});
}
public static <T, S> Collection<T> map(Iterable<? extends S> c, Function1<S, T> mapper) {
return map(new LinkedList<T>(), c, mapper);
}
public static <T, S, X extends Collection<T>> X map(X into, Iterable<? extends S> c, Function1<S, T> mapper) {
for (S arg : c) {
into.add(mapper.execute(arg));
}
return into;
}
public static <S> void dorun(Iterable<? extends S> c, Function1<S, Void> executor) {
for (S arg : c) {
executor.execute(arg);
}
}
public static <T, S> Collection<T> flatMap(Iterable<? extends S> c, Function1<S, Collection<T>> mapper) {
return flatMap(new LinkedList<T>(), c, mapper);
}
public static <T, S, X extends Collection<T>> X flatMap(X into, Iterable<? extends S> c, Function1<S, Collection<T>> mapper) {
for (S arg : c) {
into.addAll(mapper.execute(arg));
}
return into;
}
public boolean isEmpty() {
return iterable2collection(_collection).isEmpty();
}
public boolean isNotEmpty() {
return !isEmpty();
}
/**
* Class for implementing a reducer.
*
* @param <T> the first type
* @param <S> the second type
*/
public abstract static class Reduce<T, S> extends Function3<T, Iterable<? extends S>, Function2<T, S, T>, T> {
public abstract T reduce(T acc, S v);
@Override
public T execute(T acc, Iterable<? extends S> c, Function2<T, S, T> reducer) {
return Functional.reduce(acc, c, reducer);
}
public T execute(T acc, Iterable<? extends S> c) {
return execute(acc, c, new Function2<T, S, T>() {
@Override
public T execute(T t, S s) {
return reduce(t, s);
}
});
}
}
/**
* Class for implementing a reducer on a single type.
*
* @param <S> the second type
*/
public abstract static class ReduceSame<S> extends Function2<Iterable<? extends S>, Function2<S, S, S>, S> {
public abstract S reduce(S acc, S v);
@Override
public S execute(Iterable<? extends S> c, Function2<S, S, S> reducer) {
return Functional.reduce(c, reducer);
}
public S execute(Iterable<? extends S> c) {
return execute(c, new Function2<S, S, S>() {
@Override
public S execute(S a, S b) {
return reduce(a, b);
}
});
}
}
public static <S> Functional<S> functional(Iterable<S> c) {
return new Functional<S>(c);
}
private Iterable<S> _collection;
private Functional(final Iterable<S> c) {
_collection = c;
}
public <T, X extends Collection<T>> Functional<T> map(X into, Function1<S, T> mapper) {
for (S arg : _collection) {
into.add(mapper.execute(arg));
}
return new Functional<T>(into);
}
public <T> Functional<T> map(Function1<S, T> mapper) {
return new Functional<T>(map(new LinkedList<T>(), _collection, mapper));
}
public Functional<S> filter(final Function1<S, Boolean> predicate) {
return new Functional<S>(reduce(new LinkedList<S>(), new Function2<LinkedList<S>, S, LinkedList<S>>() {
@Override
public LinkedList<S> execute(LinkedList<S> acc, S e) {
if (predicate.execute(e)) {
acc.add(e);
}
return acc;
}
}));
}
public boolean all(final Function1<S, Boolean> predicate) {
final Iterator<? extends S> iter = _collection.iterator();
boolean all = true;
while (all && iter.hasNext()) {
all = predicate.execute(iter.next());
}
return all;
}
public <T> T reduce(final T acc, final Function2<T, S, T> reducer) {
T result = acc;
for (S s : _collection) {
result = reducer.execute(result, s);
}
return result;
}
static <T> ArrayList<T> iterable2collection(Iterable<T> iterable) {
ArrayList<T> collection;
if (iterable instanceof Collection) {
collection = new ArrayList<T>((Collection<T>) iterable);
} else {
collection = new ArrayList<T>();
for (T s : iterable) {
collection.add(s);
}
}
return collection;
}
public Functional<S> sortBy(java.util.Comparator<? super S> comparator) {
Collection<S> collection = iterable2collection(_collection);
Collections.sort((List<S>) collection, comparator);
return new Functional<S>(collection);
}
public Functional<S> sort() {
GenericType<S> gtS = new GenericType<S>() {
};
GenericType<Comparable<? extends S>> gtCS = new GenericType<Comparable<? extends S>>() {
};
if (gtCS.getRawClass().isAssignableFrom(gtS.getRawClass())) {
java.util.Comparator<? super S> comparator = new Comparator<S>() {
@SuppressWarnings("unchecked")
@Override
public int compare(S s, S s1) {
return ((Comparable<S>) s).compareTo(s1);
}
};
return sortBy(comparator);
} else {
return this;
}
}
public S first() {
ArrayList<? extends S> collection = iterable2collection(_collection);
if (collection.isEmpty()) {
return null;
} else {
return collection.get(collection.size() - 1);
}
}
public S last() {
ArrayList<? extends S> collection = iterable2collection(_collection);
if (collection.isEmpty()) {
return null;
} else {
return collection.get(collection.size() - 1);
}
}
public Functional<S> first(int count) {
ArrayList<? extends S> collection = iterable2collection(_collection);
if (collection.isEmpty()) {
return new Functional<S>(Collections.<S>emptyList());
} else {
Collection<S> c = new ArrayList<S>();
try {
for (int i = 0; i <= count; i++) {
c.add(collection.get(i));
}
} catch (IndexOutOfBoundsException e) {
// ok we have got them all
}
return new Functional<S>(c);
}
}
public Functional<S> last(int count) {
ArrayList<? extends S> collection = iterable2collection(_collection);
if (collection.isEmpty()) {
return new Functional<S>(Collections.<S>emptyList());
} else {
List<S> c = new ArrayList<S>();
try {
for (int i = (count - 1); i >= 0; i
c.add(collection.get(i));
}
} catch (IndexOutOfBoundsException e) {
// ok we have got them all
}
Collections.reverse(c);
return new Functional<S>(c);
}
}
public Functional<S> each(Function1<S, ?> sideEfectsExecutor) {
for (S s : this) {
sideEfectsExecutor.execute(s);
}
return this;
}
public Iterable<S> value() {
return _collection;
}
public Collection<S> asCollection() {
return iterable2collection(_collection);
}
public List<S> asList() {
return iterable2collection(_collection);
}
@Override
public Iterator<S> iterator() {
return _collection.iterator();
}
}
|
package se.sics.mspsim.util;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import se.sics.mspsim.chip.PacketListener;
/**
* @author joakim
*
*/
public class NetworkConnection implements Runnable {
private final static boolean DEBUG = true;
private final static int DEFAULT_PORT = 4711;
ServerSocket serverSocket = null;
ArrayList<ConnectionThread> connections = new ArrayList<ConnectionThread>();
private PacketListener listener;
public NetworkConnection() {
if (connect(DEFAULT_PORT)) {
System.out.println("NetworkConnection: Connected to network...");
} else {
setupServer(DEFAULT_PORT);
System.out.println("NetworkConnection: Setup network server...");
}
}
// TODO: this should handle several listeners!!!
public void addPacketListener(PacketListener pl) {
listener = pl;
}
private void setupServer(int port) {
try {
serverSocket = new ServerSocket(port);
if (DEBUG) System.out.println("NetworkConnection: setup of server socket finished... ");
new Thread(this).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
System.out.println("NetworkConnection: Accepting new connections...");
while (true) {
try {
Socket s = serverSocket.accept();
if (DEBUG) System.out.println("NetworkConnection: New connection accepted...");
connections.add(new ConnectionThread(s));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Data incoming from the network!!! - forward to radio and if server, to
// all other nodes
private void dataReceived(byte[] data, int len, ConnectionThread source) {
int[] buf = new int[len];
for (int i = 0; i < buf.length; i++) {
buf[i] = data[i];
}
if (listener != null) {
// Send this data to the transmitter in this node!
listener.transmissionStarted();
listener.transmissionEnded(buf);
}
// And if this is the server, propagate to the others
if (serverSocket != null) {
dataSent(buf, source);
}
}
private byte[] buf = new byte[256];
// Data was sent from the radio in the node (or other node) and should
// be sent out to other nodes!!!
public void dataSent(int[] data) {
dataSent(data, null);
}
// Data was sent either from radio, or came from another "radio" -
// and if so it should be propagated to all others.
public void dataSent(int[] data, ConnectionThread source) {
if (connections.size() > 0) {
for (int i = 0; i < data.length; i++) {
buf[i] = (byte) data[i];
}
ConnectionThread[] cthr = connections.toArray(new ConnectionThread[connections.size()]);
for (int i = 0; i < cthr.length; i++) {
if (cthr[i].isClosed()) {
connections.remove(cthr);
// Do not write back to the source
} else if (cthr[i] != source){
try {
cthr[i].output.write((byte) data.length);
cthr[i].output.write(buf, 0, data.length);
if (DEBUG) {
System.out.println("NetworkConnection: wrote " + data.length + " bytes");
printPacket(buf, data.length);
}
} catch (IOException e) {
e.printStackTrace();
cthr[i].close();
}
}
}
}
}
private void printPacket(byte[] data, int len) {
for (int i = 0; i < len; i++) {
System.out.print(Utils.hex8(data[i]) + " ");
}
System.out.println();
}
private boolean connect(int port) {
try {
Socket socket = new Socket("127.0.0.1", port);
connections.add(new ConnectionThread(socket));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
class ConnectionThread implements Runnable {
byte[] buffer = new byte[256];
Socket socket;
DataInputStream input;
OutputStream output;
public ConnectionThread(Socket socket) throws IOException {
this.socket = socket;
input = new DataInputStream(socket.getInputStream());
output = socket.getOutputStream();
new Thread(this).start();
}
public void close() {
try {
input.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
}
public boolean isClosed() {
return socket == null;
}
@Override
public void run() {
if (DEBUG) System.out.println("NetworkConnection: Started connection thread...");
try {
while (socket != null) {
int len;
len = input.read();
if (len > 0) {
input.readFully(buffer, 0, len);
if (DEBUG) {
System.out.println("NetworkConnection: Read packet with " + len + " bytes");
printPacket(buffer, len);
}
dataReceived(buffer, len, this);
}
}
} catch (IOException e) {
e.printStackTrace();
close();
}
}
}
}
|
package org.openhealthtools.mdht.uml.cda.core.util;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.common.util.UML2Util;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.util.UMLSwitch;
import org.openhealthtools.mdht.uml.cda.core.profile.ActRelationship;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationship;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationshipKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Validation;
import org.openhealthtools.mdht.uml.common.util.NamedElementComparator;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.BindingKind;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;
import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;
public class CDAModelUtil {
public static final String CDA_PACKAGE_NAME = "cda";
public static final String DATATYPES_NS_URI = "http:
/** This base URL may be set from preferences or Ant task options. */
public static String INFOCENTER_URL = "http:
public static final String SEVERITY_ERROR = "ERROR";
public static final String SEVERITY_WARNING = "WARNING";
public static final String SEVERITY_INFO = "INFO";
public static Class getCDAClass(Classifier templateClass) {
Class cdaClass = null;
// if the provided class is from CDA and not a template
if (isCDAModel(templateClass) && templateClass instanceof Class) {
return (Class) templateClass;
}
for (Classifier parent : templateClass.allParents()) {
// nearest package may be null if CDA model is not available
if (parent.getNearestPackage() != null) {
if (isCDAModel(parent) && parent instanceof Class) {
cdaClass = (Class) parent;
break;
}
}
}
return cdaClass;
}
public static Property getCDAProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
// if the provided property is from a CDA class and not a template
if (isCDAModel(templateProperty)) {
return templateProperty;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName().equals(templateProperty.getName()) && isCDAModel(inherited)) {
return inherited;
}
}
}
return null;
}
/**
* Returns the nearest inherited property with the same name, or null if not found.
*/
public static Property getInheritedProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName().equals(templateProperty.getName())) {
return inherited;
}
}
}
return null;
}
public static boolean isDatatypeModel(Element element) {
if (element != null && element.getNearestPackage() != null) {
Stereotype ePackage = element.getNearestPackage().getAppliedStereotype("Ecore::EPackage");
if (ePackage != null) {
return DATATYPES_NS_URI.equals(element.getNearestPackage().getValue(ePackage, "nsURI"));
}
}
return false;
}
public static boolean isCDAModel(Element element) {
return CDA_PACKAGE_NAME.equals((element.getNearestPackage() != null)
? element.getNearestPackage().getName()
: "");
}
public static boolean isCDAType(Type templateClass, String typeName) {
if (templateClass instanceof Class && typeName != null) {
Class cdaClass = getCDAClass((Class) templateClass);
if (cdaClass != null && typeName.equals(cdaClass.getName())) {
return true;
}
}
return false;
}
public static boolean isClinicalDocument(Type templateClass) {
return isCDAType(templateClass, "ClinicalDocument");
}
public static boolean isSection(Type templateClass) {
return isCDAType(templateClass, "Section");
}
public static boolean isOrganizer(Type templateClass) {
return isCDAType(templateClass, "Organizer");
}
public static boolean isEntry(Type templateClass) {
return isCDAType(templateClass, "Entry");
}
public static boolean isClinicalStatement(Type templateClass) {
if (templateClass instanceof Class) {
Class cdaClass = getCDAClass((Class) templateClass);
String cdaName = cdaClass == null
? null
: cdaClass.getName();
if (cdaClass != null &&
("Act".equals(cdaName) || "Encounter".equals(cdaName) || "Observation".equals(cdaName) ||
"ObservationMedia".equals(cdaName) || "Organizer".equals(cdaName) ||
"Procedure".equals(cdaName) || "RegionOfInterest".equals(cdaName) ||
"SubstanceAdministration".equals(cdaName) || "Supply".equals(cdaName))) {
return true;
}
}
return false;
}
public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {
final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(Collections.singletonList(element));
while (iterator != null && iterator.hasNext()) {
EObject child = iterator.next();
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
iterator.prune();
return association;
}
@Override
public Object caseClass(Class umlClass) {
String message = computeConformanceMessage(umlClass, markup);
stream.println(message);
return umlClass;
}
@Override
public Object caseGeneralization(Generalization generalization) {
String message = computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
stream.println(message);
}
return generalization;
}
@Override
public Object caseProperty(Property property) {
String message = computeConformanceMessage(property, markup);
if (message.length() > 0) {
stream.println(message);
}
return property;
}
@Override
public Object caseConstraint(Constraint constraint) {
String message = computeConformanceMessage(constraint, markup);
if (message.length() > 0) {
stream.println(message);
}
return constraint;
}
};
umlSwitch.doSwitch(child);
}
}
public static String computeConformanceMessage(Element element, final boolean markup) {
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
String message = null;
Property property = getNavigableEnd(association);
if (property != null) {
message = computeConformanceMessage(property, false);
}
return message;
}
@Override
public Object caseClass(Class umlClass) {
return computeConformanceMessage(umlClass, markup);
}
@Override
public Object caseGeneralization(Generalization generalization) {
return computeConformanceMessage(generalization, markup);
}
@Override
public Object caseProperty(Property property) {
return computeConformanceMessage(property, markup);
}
@Override
public Object caseConstraint(Constraint constraint) {
return computeConformanceMessage(constraint, markup);
}
};
return (String) umlSwitch.doSwitch(element);
}
public static String computeConformanceMessage(Class template, boolean markup) {
StringBuffer message = new StringBuffer();
String templateId = getTemplateId(template);
if (templateId != null) {
String ruleId = getConformanceRuleIds(template);
if (ruleId.length() > 0) {
message.append(markup
? "<b>"
: "");
message.append(ruleId + ": ");
message.append(markup
? "</b>"
: "");
}
if (!markup) {
message.append(getPrefixedSplitName(template)).append(" ");
}
message.append("SHALL contain the template identifier ").append(templateId);
}
return message.toString();
}
public static String computeConformanceMessage(Generalization generalization, boolean markup) {
return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));
}
public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {
Class general = (Class) generalization.getGeneral();
StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource));
appendConformanceRuleIds(generalization, message, markup);
return message.toString();
}
public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
String prefix = !UMLUtil.isSameModel(xrefSource, general)
? getModelPrefix(general) + " "
: "";
String xref = computeXref(xrefSource, general);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
Class cdaGeneral = getCDAClass(general);
if (cdaGeneral != null) {
message.append(markup
? "<b>"
: "");
message.append("SHALL");
message.append(markup
? "</b>"
: "");
message.append(" conform to ");
} else {
message.append("Extends ");
}
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(general));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(general);
if (templateId != null) {
message.append(" template (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource) {
if (getTemplateId(property.getClass_()) != null) {
return computeTemplateAssociationConformanceMessage(property, markup, xrefSource);
}
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
String elementName = getCDAElementName(property);
message.append(markup
? "<tt><b>"
: "");
message.append(elementName);
message.append(markup
? "</b></tt>"
: "");
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (endType != null) {
if (markup && endType.getOwner() instanceof Class) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringBuffer sb = sw.getBuffer();
appendConformanceRuleIds(association, message, markup);
appendPropertyComments(pw, property, markup);
appendConformanceRules(pw, endType, String.format(" %s%s%s ", (property.getUpper() == 1
? "This "
: "Such "), elementName, (property.getUpper() == 1
? ""
: "s")), markup);
message.append(" " + sw.getBuffer() + " ");
} else {
message.append(", where its type is ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
appendConformanceRuleIds(association, message, markup);
}
} else {
appendConformanceRuleIds(association, message, markup);
}
return message.toString();
}
private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup,
Package xrefSource) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
String elementName = getCDAElementName(property);
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
message.append(markup
? "<tt><b>"
: "");
message.append(elementName);
message.append(markup
? "</b></tt>"
: "");
appendConformanceRuleIds(association, message, markup);
if (property.getType() instanceof Class) {
Class inlinedClass = (Class) property.getType();
if (markup && inlinedClass.getOwner() instanceof Class) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringBuffer sb = sw.getBuffer();
appendPropertyComments(pw, property, markup);
appendConformanceRules(pw, inlinedClass, String.format(" %s%s%s ", (property.getUpper() == 1
? "This "
: "Such "), elementName, (property.getUpper() == 1
? ""
: "s")), markup);
message.append(" " + sw.getBuffer());
}
}
if (!markup) {
String assocConstraints = computeAssociationConstraints(property, markup);
if (assocConstraints.length() > 0) {
message.append(assocConstraints);
}
}
return message.toString();
}
public static String computeAssociationConstraints(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
Package xrefSource = UMLUtil.getTopPackage(property);
ActRelationship actRelationship = CDAProfileUtil.getActRelationship(association);
if (actRelationship != null) {
}
EntryRelationship entryRelationship = CDAProfileUtil.getEntryRelationship(association);
// Stereotype entryStereotype = CDAProfileUtil.getAppliedCDAStereotype(association, ICDAProfileConstants.ENTRY);
// Stereotype entryRelationshipStereotype = CDAProfileUtil.getAppliedCDAStereotype(
// association, ICDAProfileConstants.ENTRY_RELATIONSHIP);
EntryRelationshipKind typeCode = null;
// String typeCodeDisplay = null;
if (entryRelationship != null) {
typeCode = entryRelationship.getTypeCode(); // getLiteralValue(association, entryStereotype, ICDAProfileConstants.ENTRY_TYPE_CODE);
// Enumeration profileEnum = (Enumeration) entryStereotype.getProfile().getOwnedType(
// ICDAProfileConstants.ENTRY_KIND);
// typeCodeDisplay = getLiteralValueLabel(
// association, entryStereotype, ICDAProfileConstants.ENTRY_TYPE_CODE, profileEnum);
}
// else if (entryRelationshipStereotype != null) {
// typeCode = getLiteralValue(
// association, entryRelationshipStereotype, ICDAProfileConstants.ENTRY_RELATIONSHIP_TYPE_CODE);
// Enumeration profileEnum = (Enumeration) entryRelationshipStereotype.getProfile().getOwnedType(
// ICDAProfileConstants.ENTRY_RELATIONSHIP_KIND);
// typeCodeDisplay = getLiteralValueLabel(
// association, entryRelationshipStereotype, ICDAProfileConstants.ENTRY_RELATIONSHIP_TYPE_CODE,
// profileEnum);
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (typeCode != null) {
message.append(markup
? "\n<li>"
: " ");
// message.append(markup?"<b>":"").append("SHALL").append(markup?"</b>":"");
// message.append(" contain ");
message.append("Contains ");
message.append(markup
? "<tt><b>"
: "").append("@typeCode=\"").append(markup
? "</b>"
: "");
message.append(typeCode).append("\" ");
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<i>"
: "");
message.append(typeCode.getLiteral());
message.append(markup
? "</i>"
: "");
message.append(markup
? "</li>"
: ", and");
}
// TODO: what I should really do is test for an *implied* ActRelationship or Participation association
if (endType != null && getTemplateId(endType) != null) {
message.append(markup
? "\n<li>"
: " ");
// message.append(markup?"<b>":"").append("SHALL").append(markup?"</b>":"");
// message.append(" contain exactly one [1..1] ");
message.append("Contains exactly one [1..1] ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(endType);
if (templateId != null) {
message.append(" (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
message.append(markup
? "</tt>"
: "");
message.append(")");
}
message.append(markup
? "</li>"
: "");
}
return message.toString();
}
public static String computeConformanceMessage(Property property, boolean markup) {
return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {
if (property.getType() == null) {
System.out.println("Property has null type: " + property.getQualifiedName());
}
if (property.getAssociation() != null && property.isNavigable()) {
return computeAssociationConformanceMessage(property, markup, xrefSource);
}
StringBuffer message = new StringBuffer();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
message.append(markup
? "<tt><b>"
: "");
if (isXMLAttribute(property)) {
message.append("@");
}
message.append(property.getName());
message.append(markup
? "</b>"
: "");
if (isXMLAttribute(property) && property.getDefault() != null) {
message.append("=\"").append(property.getDefault()).append("\" ");
}
message.append(markup
? "</tt>"
: "");
Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.NULL_FLAVOR);
Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property, ICDAProfileConstants.TEXT_VALUE);
if (nullFlavorSpecification != null) {
String nullFlavor = getLiteralValue(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);
Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(
ICDAProfileConstants.NULL_FLAVOR_KIND);
String nullFlavorLabel = getLiteralValueLabel(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);
if (nullFlavor != null) {
message.append(markup
? "<tt>"
: "");
message.append("/@nullFlavor");
message.append(markup
? "</tt>"
: "");
message.append(" = \"").append(nullFlavor).append("\" ");
message.append(markup
? "<i>"
: "");
message.append(nullFlavorLabel);
message.append(markup
? "</i>"
: "");
}
}
if (textValue != null) {
String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);
if (value != null && value.length() > 0) {
message.append(" = \"").append(value).append("\"");
}
}
// Stereotype conceptDomainConstraint = CDAProfileUtil.getAppliedCDAStereotype(
// property, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);
Stereotype codeSystemConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
Stereotype valueSetConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
if (codeSystemConstraint != null) {
String vocab = computeCodeSystemMessage(property, markup);
message.append(vocab);
} else if (valueSetConstraint != null) {
String vocab = computeValueSetMessage(property, markup, xrefSource);
message.append(vocab);
} else if (isHL7VocabAttribute(property) && property.getDefault() != null) {
String vocab = computeHL7VocabAttributeMessage(property, markup);
message.append(vocab);
}
List<Property> redefinedProperties = UMLUtil.getRedefinedProperties(property);
Property redefinedProperty = redefinedProperties.isEmpty()
? null
: redefinedProperties.get(0);
if (property.getType() != null &&
(redefinedProperty == null || (!isXMLAttribute(property) && (property.getType() != redefinedProperty.getType())))) {
message.append(", where its data type is ");
String xref = (property.getType() instanceof Classifier && UMLUtil.isSameProject(
property, property.getType()))
? computeXref(xrefSource, (Classifier) property.getType())
: null;
boolean showXref = markup && (xref != null);
if (showXref) {
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(UMLUtil.splitName(property.getType()));
message.append(showXref
? "</xref>"
: "");
} else {
message.append(property.getType().getName());
}
}
appendConformanceRuleIds(property, message, markup);
return message.toString();
}
private static final String[] OL = { "<ol>", "</ol>" };
private static final String[] LI = { "<li>", "</li>" };
private static final String[] NOOL = { "", " " };
private static final String[] NOLI = { "", " " };
static private void appendConformanceRules(PrintWriter writer, Class umlClass, String prefix, boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
writer.print(ol[0]);
boolean hasRules = false;
for (Generalization generalization : umlClass.getGeneralizations()) {
Classifier general = generalization.getGeneral();
if (!RIMModelUtil.isRIMModel(general) && !CDAModelUtil.isCDAModel(general)) {
String message = CDAModelUtil.computeConformanceMessage(generalization, true);
if (message.length() > 0) {
hasRules = true;
writer.print(li[0] + prefix + message + li[1]);
}
}
}
// categorize constraints by constrainedElement name
List<Constraint> unprocessedConstraints = new ArrayList<Constraint>();
// propertyName -> constraints
Map<String, List<Constraint>> constraintMap = new HashMap<String, List<Constraint>>();
// constraint -> sub-constraints
Map<Constraint, List<Constraint>> subConstraintMap = new HashMap<Constraint, List<Constraint>>();
for (Constraint constraint : umlClass.getOwnedRules()) {
unprocessedConstraints.add(constraint);
for (Element element : constraint.getConstrainedElements()) {
if (element instanceof Property) {
String name = ((Property) element).getName();
List<Constraint> rules = constraintMap.get(name);
if (rules == null) {
rules = new ArrayList<Constraint>();
constraintMap.put(name, rules);
}
rules.add(constraint);
} else if (element instanceof Constraint) {
Constraint subConstraint = (Constraint) element;
List<Constraint> rules = subConstraintMap.get(subConstraint);
if (rules == null) {
rules = new ArrayList<Constraint>();
subConstraintMap.put(subConstraint, rules);
}
rules.add(constraint);
}
}
}
List<Property> allProperties = new ArrayList<Property>(umlClass.getOwnedAttributes());
List<Property> allAttributes = new ArrayList<Property>();
for (Property property : allProperties) {
if (CDAModelUtil.isXMLAttribute(property)) {
allAttributes.add(property);
}
}
allProperties.removeAll(allAttributes);
Collections.sort(allAttributes, new NamedElementComparator());
// XML attributes
for (Property property : allAttributes) {
hasRules = true;
writer.print(li[0] + prefix + CDAModelUtil.computeConformanceMessage(property, markup));
appendPropertyComments(writer, property, markup);
appendPropertyRules(writer, property, constraintMap, subConstraintMap, unprocessedConstraints, markup);
writer.print(li[1]);
}
// XML elements
for (Property property : allProperties) {
hasRules = true;
writer.print(li[0] + prefix + CDAModelUtil.computeConformanceMessage(property, markup));
appendPropertyComments(writer, property, markup);
appendPropertyRules(writer, property, constraintMap, subConstraintMap, unprocessedConstraints, markup);
writer.print(li[1]);
}
for (Constraint constraint : unprocessedConstraints) {
hasRules = true;
writer.print(li[0] + prefix + CDAModelUtil.computeConformanceMessage(constraint, markup) + li[1]);
}
if (!hasRules) {
writer.print(li[0] + li[1]);
}
writer.print(ol[1]);
}
private static void appendPropertyComments(PrintWriter writer, Property property, boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
// INLINE
Association association = property.getAssociation();
if (association != null && association.getOwnedComments().size() > 0) {
if (markup) {
writer.append("<p><i>");
}
for (Comment comment : association.getOwnedComments()) {
writer.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
writer.append("</i></p>");
}
}
if (property.getOwnedComments().size() > 0) {
if (markup) {
writer.append("<p><i>");
}
for (Comment comment : property.getOwnedComments()) {
writer.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
writer.append("</i></p>");
}
}
}
private static void appendPropertyRules(PrintWriter writer, Property property,
Map<String, List<Constraint>> constraintMap, Map<Constraint, List<Constraint>> subConstraintMap,
List<Constraint> unprocessedConstraints, boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
// association typeCode and property type
String assocConstraints = "";
if (property.getAssociation() != null) {
assocConstraints = CDAModelUtil.computeAssociationConstraints(property, true);
}
StringBuffer ruleConstraints = new StringBuffer();
List<Constraint> rules = constraintMap.get(property.getName());
if (rules != null && !rules.isEmpty()) {
for (Constraint constraint : rules) {
unprocessedConstraints.remove(constraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(constraint, true));
appendSubConstraintRules(ruleConstraints, constraint, subConstraintMap, unprocessedConstraints, markup);
// List<Constraint> subConstraints = subConstraintMap.get(constraint);
// if (subConstraints != null && subConstraints.size() > 0) {
// ruleConstraints.append(OL[0]);
// for (Constraint subConstraint : subConstraints) {
// unprocessedConstraints.remove(subConstraint);
// ruleConstraints.append("\n<li>" + CDAModelUtil.computeConformanceMessage(subConstraint, true) + "</li>");
// ruleConstraints.append("</ol>");
ruleConstraints.append(li[1]);
}
}
if (assocConstraints.length() > 0 || ruleConstraints.length() > 0) {
// writer.append(", such that ");
// writer.append(property.upperBound()==1 ? "it" : "each");
writer.append(ol[0]);
writer.append(assocConstraints);
writer.append(ruleConstraints);
writer.append(ol[1]);
}
}
private static void appendSubConstraintRules(StringBuffer ruleConstraints, Constraint constraint,
Map<Constraint, List<Constraint>> subConstraintMap, List<Constraint> unprocessedConstraints, boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
List<Constraint> subConstraints = subConstraintMap.get(constraint);
if (subConstraints != null && subConstraints.size() > 0) {
ruleConstraints.append(ol[0]);
for (Constraint subConstraint : subConstraints) {
unprocessedConstraints.remove(subConstraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(subConstraint, true));
appendSubConstraintRules(
ruleConstraints, subConstraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
ruleConstraints.append(ol[1]);
}
}
private static boolean isHL7VocabAttribute(Property property) {
String name = property.getName();
return "classCode".equals(name) || "moodCode".equals(name) || "typeCode".equals(name);
}
private static String computeHL7VocabAttributeMessage(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Class rimClass = RIMModelUtil.getRIMClass(property.getClass_());
String code = property.getDefault();
String displayName = null;
String codeSystemId = null;
String codeSystemName = null;
if (rimClass != null) {
if ("Act".equals(rimClass.getName())) {
if ("classCode".equals(property.getName())) {
codeSystemName = "HL7ActClass";
codeSystemId = "2.16.840.1.113883.5.6";
if ("ACT".equals(code)) {
displayName = "Act";
} else if ("OBS".equals(code)) {
displayName = "Observation";
}
} else if ("moodCode".equals(property.getName())) {
codeSystemName = "HL7ActMood";
codeSystemId = "2.16.840.1.113883.5.1001";
if ("EVN".equals(code)) {
displayName = "Event";
}
}
}
}
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
if (codeSystemId != null || codeSystemName != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (codeSystemId != null) {
message.append(" ").append(codeSystemId);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeCodeSystemMessage(Property property, boolean markup) {
CodeSystemConstraint codeSystemConstraint = TermProfileUtil.getCodeSystemConstraint(property);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String code = null;
String displayName = null;
if (codeSystemConstraint != null) {
if (codeSystemConstraint.getReference() != null) {
CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();
id = codeSystemVersion.getIdentifier();
name = codeSystemVersion.getEnumerationName();
version = codeSystemVersion.getVersion();
} else {
id = codeSystemConstraint.getIdentifier();
name = codeSystemConstraint.getName();
version = codeSystemConstraint.getVersion();
}
binding = codeSystemConstraint.getBinding();
code = codeSystemConstraint.getCode();
displayName = codeSystemConstraint.getDisplayName();
}
StringBuffer message = new StringBuffer();
if (code != null) {
message.append(markup
? "<tt><b>"
: "");
message.append("/@code");
message.append(markup
? "</b>"
: "");
message.append("=\"").append(code).append("\" ");
message.append(markup
? "</tt>"
: "");
}
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
if (id != null || name != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ").append(name);
}
message.append(markup
? "</tt>"
: "");
// message.append(" ").append(binding.getName().toUpperCase());
// if (version != null) {
// message.append(" ").append(version);
message.append(")");
}
return message.toString();
}
private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {
ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property);
String keyword = getValidationKeyword(property);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String xref = null;
String xrefFormat = "";
boolean showXref = false;
if (valueSetConstraint != null) {
if (valueSetConstraint.getReference() != null) {
ValueSetVersion valueSetVersion = valueSetConstraint.getReference();
id = valueSetVersion.getIdentifier();
name = valueSetVersion.getEnumerationName();
version = valueSetVersion.getVersion();
binding = valueSetVersion.getBinding();
if (valueSetVersion.getBase_Enumeration() != null) {
xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());
}
showXref = markup && (xref != null);
xrefFormat = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
} else {
id = valueSetConstraint.getIdentifier();
name = valueSetConstraint.getName();
version = valueSetConstraint.getVersion();
binding = valueSetConstraint.getBinding();
}
}
StringBuffer message = new StringBuffer();
message.append(", which ");
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from ValueSet");
message.append(markup
? "<tt>"
: "");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ");
message.append(showXref
? "<xref " + xrefFormat + "href=\"" + xref + "\">"
: "");
message.append(name);
message.append(showXref
? "</xref>"
: "");
}
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<b>"
: "");
message.append(" ").append(binding.getName().toUpperCase());
message.append(markup
? "</b>"
: "");
if (BindingKind.STATIC == binding && version != null) {
message.append(" ").append(version);
}
return message.toString();
}
public static String computeConformanceMessage(Constraint constraint, boolean markup) {
StringBuffer message = new StringBuffer();
String strucTextBody = null;
String analysisBody = null;
Map<String, String> langBodyMap = new HashMap<String, String>();
ValueSpecification spec = constraint.getSpecification();
if (spec instanceof OpaqueExpression) {
for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
String lang = ((OpaqueExpression) spec).getLanguages().get(i);
String body = ((OpaqueExpression) spec).getBodies().get(i);
if ("StrucText".equals(lang)) {
strucTextBody = body;
} else if ("Analysis".equals(lang)) {
analysisBody = body;
} else {
langBodyMap.put(lang, body);
}
}
}
String displayBody = null;
if (strucTextBody != null && strucTextBody.trim().length() > 0) {
// TODO if markup, parse strucTextBody and insert DITA markup
displayBody = strucTextBody;
} else if (analysisBody != null && analysisBody.trim().length() > 0) {
if (markup) {
// escape non-dita markup in analysis text
displayBody = escapeMarkupCharacters(analysisBody);
// change severity words to bold text
displayBody = replaceSeverityWithBold(displayBody);
} else {
displayBody = analysisBody;
}
}
if (!markup) {
message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
}
if (displayBody == null || !containsSeverityWord(displayBody)) {
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" satisfy: ");
}
if (displayBody == null) {
message.append(constraint.getName());
} else {
message.append(displayBody);
}
appendConformanceRuleIds(constraint, message, markup);
// include comment text only in markup output
if (false && markup && constraint.getOwnedComments().size() > 0) {
message.append("<ul>");
for (Comment comment : constraint.getOwnedComments()) {
message.append("<li>");
message.append(fixNonXMLCharacters(comment.getBody()));
message.append("</li>");
}
message.append("</ul>");
}
// Include other constraint languages, e.g. OCL or XPath
if (false && langBodyMap.size() > 0) {
message.append("<ul>");
for (String lang : langBodyMap.keySet()) {
message.append("<li>");
message.append("<codeblock>[" + lang + "]: ");
message.append(escapeMarkupCharacters(langBodyMap.get(lang)));
message.append("</codeblock>");
message.append("</li>");
}
message.append("</ul>");
}
if (!markup) {
// remove line feeds
int index;
while ((index = message.indexOf("\r")) >= 0) {
message.deleteCharAt(index);
}
while ((index = message.indexOf("\n")) >= 0) {
message.deleteCharAt(index);
if (message.charAt(index) != ' ') {
message.insert(index, " ");
}
}
}
return message.toString();
}
private static boolean containsSeverityWord(String text) {
return text.indexOf("SHALL") >= 0 || text.indexOf("SHOULD") >= 0 || text.indexOf("MAY") >= 0;
}
private static String replaceSeverityWithBold(String input) {
String output;
output = input.replaceAll("SHALL", "<b>SHALL</b>");
output = output.replaceAll("SHOULD", "<b>SHOULD</b>");
output = output.replaceAll("MAY", "<b>MAY</b>");
output = output.replaceAll("\\<b>SHALL\\</b> NOT", "<b>SHALL NOT</b>");
output = output.replaceAll("\\<b>SHOULD\\</b> NOT", "<b>SHOULD NOT</b>");
return output;
}
protected static String computeXref(Element source, Classifier target) {
if (target instanceof Enumeration) {
return computeTerminologyXref(source, (Enumeration) target);
}
String href = null;
if (UMLUtil.isSameProject(source, target)) {
href = "../" + normalizeCodeName(target.getName()) + ".dita";
} else if (isCDAModel(target)) {
// no xref to CDA available at this time
} else {
String pathFolder = "classes";
String basePackage = "";
String prefix = "";
String packageName = target.getNearestPackage().getName();
if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.hl7.rim";
} else if (CDA_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.cda";
} else {
basePackage = getModelBasePackage(target);
prefix = getModelNamespacePrefix(target);
}
if (basePackage == null || basePackage.trim().length() == 0) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
if (prefix != null && prefix.trim().length() > 0) {
prefix += ".";
}
href = INFOCENTER_URL + "/topic/" + basePackage + "." + prefix + "doc/" + pathFolder + "/" +
normalizeCodeName(target.getName()) + ".html";
// pathFolder = "dita/classes";
// href = "../../../../" + basePackage + "."
// + prefix + "doc/" + pathFolder + "/" + normalizeCodeName(target.getName()) + ".dita";
}
return href;
}
protected static String computeTerminologyXref(Element source, Enumeration target) {
String href = null;
if (UMLUtil.isSameProject(source, target)) {
href = "../../terminology/" + normalizeCodeName(target.getName()) + ".dita";
}
return href;
}
public static Property getNavigableEnd(Association association) {
Property navigableEnd = null;
for (Property end : association.getMemberEnds()) {
if (end.isNavigable()) {
if (navigableEnd != null) {
return null; // multiple navigable ends
}
navigableEnd = end;
}
}
return navigableEnd;
}
public static String getCDAElementName(Property property) {
String elementName = property.getName();
if (property.getType() instanceof Class) {
Class cdaSourceClass = getCDAClass(property.getClass_());
if (cdaSourceClass != null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
null, getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
elementName = cdaProperty.getName();
}
}
}
return elementName;
}
public static String getMultiplicityString(Property property) {
StringBuffer message = new StringBuffer();
if (property.getLower() == 1 && property.getUpper() == 1) {
message.append("exactly one");
} else if (property.getLower() == 0 && property.getUpper() == 1) {
message.append("zero or one");
} else if (property.getLower() == 0 && property.getUpper() == -1) {
message.append("zero or more");
} else if (property.getLower() == 1 && property.getUpper() == -1) {
message.append("at least one");
}
String lower = Integer.toString(property.getLower());
String upper = property.getUpper() == -1
? "*"
: Integer.toString(property.getUpper());
message.append(" [").append(lower).append("..").append(upper).append("]");
return message.toString();
}
public static boolean isXMLAttribute(Property property) {
Property cdaProperty = getCDAProperty(property);
if (cdaProperty != null) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
if (eAttribute != null) {
return true;
}
}
return false;
}
public static String getTemplateId(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getTemplateId((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getModelPrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);
} else if (CDA_PACKAGE_NAME.equals(model.getName())) {
prefix = "CDA";
} else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(model.getName())) {
prefix = "RIM";
}
return prefix != null
? prefix
: "";
}
public static String getModelNamespacePrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);
}
return prefix;
}
public static String getModelBasePackage(Element element) {
String basePackage = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);
}
return basePackage;
}
public static String getEcorePackageURI(Element element) {
String nsURI = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);
}
if (nsURI == null) {
// for base models without codegenSupport
if (model.getName().equals("cda")) {
nsURI = "urn:hl7-org:v3";
} else if (model.getName().equals("datatypes")) {
nsURI = "http:
} else if (model.getName().equals("vocab")) {
nsURI = "http:
}
}
return nsURI;
}
public static String getPrefixedSplitName(NamedElement element) {
StringBuffer buffer = new StringBuffer();
String modelPrefix = getModelPrefix(element);
if (modelPrefix != null && modelPrefix.length() > 0) {
buffer.append(modelPrefix).append(" ");
}
buffer.append(UMLUtil.splitName(element));
return buffer.toString();
}
public static boolean hasValidationSupport(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return validationSupport != null;
}
public static String getValidationSeverity(Element element) {
String severity = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Object value = element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_SEVERITY);
if (value instanceof EnumerationLiteral) {
severity = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
severity = ((Enumerator) value).getName();
}
// return (severity != null) ? severity : SEVERITY_ERROR;
}
return severity;
}
public static String getValidationMessage(Element element) {
String message = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);
}
if (message == null || message.length() == 0) {
message = computeConformanceMessage(element, false);
}
return message;
}
/**
* Returns a list conformance rule IDs.
*/
public static List<String> getConformanceRuleIdList(Element element) {
List<String> ruleIds = new ArrayList<String>();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
ruleIds.add(ruleId);
}
}
return ruleIds;
}
protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(element);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Element element) {
StringBuffer ruleIdDisplay = new StringBuffer();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
if (ruleIdDisplay.length() > 0) {
ruleIdDisplay.append(", ");
}
ruleIdDisplay.append(ruleId);
}
}
return ruleIdDisplay.toString();
}
public static String getValidationKeyword(Element element) {
String severity = getValidationSeverity(element);
if (severity != null) {
if (SEVERITY_INFO.equals(severity)) {
return "MAY";
} else if (SEVERITY_WARNING.equals(severity)) {
return "SHOULD";
} else if (SEVERITY_ERROR.equals(severity)) {
return "SHALL";
}
}
return null;
// if (element instanceof Association) {
// for (Property end : ((Association)element).getMemberEnds()) {
// if (end.isNavigable()) {
// element = end;
// break;
// if (element instanceof MultiplicityElement) {
// if (((MultiplicityElement)element).getLower() == 0)
// return "MAY";
// else
// return "SHALL";
// else {
// return "SHALL";
}
public static void setValidationMessage(Element constrainedElement, String message) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);
}
}
public static void setValidationRuleId(Element constrainedElement, String ruleId) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
List<String> ruleIds = new ArrayList<String>();
ruleIds.add(ruleId);
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_RULE_ID, ruleIds);
}
}
protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
}
return name;
}
protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName,
Enumeration umlEnumeration) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getLabel();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
if (umlEnumeration != null) {
name = umlEnumeration.getOwnedLiteral(name).getLabel();
}
}
return name;
}
public static String fixNonXMLCharacters(String text) {
if (text == null) {
return null;
}
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
// test for unicode characters from copy/paste of MS Word text
if (text.charAt(i) == '\u201D') {
newText.append("\"");
} else if (text.charAt(i) == '\u201C') {
newText.append("\"");
} else if (text.charAt(i) == '\u2019') {
newText.append("'");
} else if (text.charAt(i) == '\u2018') {
newText.append("'");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String escapeMarkupCharacters(String text) {
if (text == null) {
return null;
}
text = fixNonXMLCharacters(text);
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '<') {
newText.append("<");
} else if (text.charAt(i) == '>') {
newText.append(">");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String normalizeCodeName(String name) {
String result = "";
String[] parts = name.split(" ");
for (String part : parts) {
result += part.substring(0, 1).toUpperCase() + part.substring(1);
}
result = UML2Util.getValidJavaIdentifier(result);
return result;
}
}
|
package com.thinkaurelius.titan.graphdb.tinkerpop;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.StoreFeatures;
import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
/**
* Blueprint's features of a TitanGraph.
*
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class TitanFeatures implements Graph.Features {
private static final Logger log =
LoggerFactory.getLogger(TitanFeatures.class);
private final GraphFeatures graphFeatures;
private final VertexFeatures vertexFeatures;
private final EdgeFeatures edgeFeatures;
private TitanFeatures() {
graphFeatures = new TitanGraphFeatures();
vertexFeatures = new TitanVertexFeatures();
edgeFeatures = new TitanEdgeFeatures();
}
@Override
public GraphFeatures graph() {
return graphFeatures;
}
@Override
public VertexFeatures vertex() {
return vertexFeatures;
}
@Override
public EdgeFeatures edge() {
return edgeFeatures;
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
private static final TitanFeatures INSTANCE = new TitanFeatures();
public static TitanFeatures getFeatures(GraphDatabaseConfiguration config, StoreFeatures storageFeatures) {
return INSTANCE;
}
private static class TitanDataTypeFeatures implements DataTypeFeatures {
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
private static class TitanVariableFeatures extends TitanDataTypeFeatures implements VariableFeatures { }
private static class TitanGraphFeatures extends TitanDataTypeFeatures implements GraphFeatures {
@Override
public VariableFeatures variables() {
return new TitanVariableFeatures();
}
@Override
public boolean supportsComputer() {
return true;
}
@Override
public boolean supportsPersistence() {
return true;
}
@Override
public boolean supportsTransactions() {
return true;
}
@Override
public boolean supportsThreadedTransactions() {
return true;
}
}
private static class TitanVertexPropertyFeatures extends TitanDataTypeFeatures implements VertexPropertyFeatures {
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
}
private static class TitanEdgePropertyFeatures extends TitanDataTypeFeatures implements EdgePropertyFeatures {
}
private static class TitanVertexFeatures implements VertexFeatures {
@Override
public VertexPropertyFeatures properties() {
return new TitanVertexPropertyFeatures();
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
}
private static class TitanEdgeFeatures implements EdgeFeatures {
@Override
public EdgePropertyFeatures properties() {
return new TitanEdgePropertyFeatures();
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() { return false; }
}
}
|
// $Id: User.java,v 1.7 2002/09/18 01:18:51 shaper Exp $
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.servlet.user;
import java.sql.Date;
import com.samskivert.jdbc.jora.FieldMask;
import com.samskivert.util.StringUtil;
/**
* A user object contains information about a registered user in our web
* application environment. Users are stored in the user repository (a
* database table) and loaded during a request based on authentication
* information provided with the request headers.
*
* <p><b>Note:</b> Do not modify any of the fields of this object
* directly. Use the <code>set</code> methods to make updates. If no set
* methods exist, you shouldn't be modifying that field.
*/
public class User
{
/** The user's assigned integer userid. */
public int userId;
/** The user's chosen username. */
public String username;
/** The date this record was created. */
public Date created;
/** The user's real name (first, last and whatever else they opt to
* provide). */
public String realname;
/** The user's chosen password (encrypted). */
public String password;
/** The user's email address. */
public String email;
/** The site identifier of the site through which the user created
* their account. (Their affiliation, if you will.) */
public int siteId;
/**
* Updates the user's real name.
*/
public void setRealName (String realname)
{
this.realname = realname;
_dirty.setModified("realname");
}
/**
* Updates the user's password.
*
* @param password The user's new (unencrypted) password.
*/
public void setPassword (String password)
{
this.password = UserUtil.encryptPassword(username, password);
_dirty.setModified("password");
}
/**
* Updates the user's email address.
*/
public void setEmail (String email)
{
this.email = email;
_dirty.setModified("email");
}
/**
* Compares the supplied password with the password associated with
* this user record.
*
* @return true if the passwords match, false if they do not.
*/
public boolean passwordsMatch (String password)
{
String epasswd = UserUtil.encryptPassword(username, password);
return this.password.equals(epasswd);
}
/**
* Called by the repository to find out which fields have been
* modified since the object was loaded.
*/
protected FieldMask getDirtyMask ()
{
return _dirty;
}
/**
* Called by the repository to configure this user record with a field
* mask that it can use to track modified fields.
*/
protected void setDirtyMask (FieldMask dirty)
{
_dirty = dirty;
}
/** Returns a string representation of this instance. */
public String toString ()
{
return StringUtil.fieldsToString(this);
}
/** Our dirty field mask. */
protected transient FieldMask _dirty;
}
|
package org.openforis.collect.earth.app.service;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Observable;
import java.util.Properties;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.openforis.collect.earth.app.EarthConstants.CollectDBDriver;
import org.openforis.collect.earth.app.EarthConstants.OperationMode;
import org.openforis.collect.earth.app.EarthConstants.SAMPLE_SHAPE;
import org.openforis.collect.earth.app.EarthConstants.UI_LANGUAGE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Class to access Collect Earth configuration. This class is used all over the
* code in order to fetch the values of the properties that can be configured by
* the user, by directly editing the earth.properties file or by using the
* Tools--Properties menu option in the Collect Earth Window.
*
* @author Alfonso Sanchez-Paus Diaz
*
*/
@Component
public class LocalPropertiesService extends Observable {
/**
* Enumeration containing the names of all the possible values that can be
* configured in Collect Earth.
*
* @author Alfonso Sanchez-Paus Diaz
*
*/
public enum EarthProperty {
ACTIVE_PROJECT_DEFINITION("active_project_definition"), ALTERNATIVE_BALLOON_FOR_BROWSER(
"alternative_balloon_for_browser"), AUTOMATIC_BACKUP("automatic_backup"), BALLOON_TEMPLATE_KEY(
"balloon"), BALLOON_TEMPLATE_KEY_CHECKSUM("balloon_checksum"), BING_MAPS_KEY(
"bing_maps_key"), BROWSER_TO_USE("use_browser"), CHROME_BINARY_PATH(
"chrome_exe_path"), CRS_KEY("coordinates_reference_system"), CSV_KEY_CHECKSUM(
"csv_checksum"), DB_DRIVER("db_driver"), DB_HOST(
"db_host"), DB_NAME("db_name"), DB_PASSWORD(
"db_password"), DB_PORT("db_port"), DB_USERNAME(
"db_username"), DISTANCE_BETWEEN_PLOTS(
"distance_between_plots"), DISTANCE_BETWEEN_SAMPLE_POINTS(
"distance_between_sample_points"), DISTANCE_TO_PLOT_BOUNDARIES(
"distance_to_plot_boundaries"), ELEVATION_GEOTIF_DIRECTORY(
"elevation_geotif_directory"), EXCEPTION_SHOWN(
"exception_shown"), EXTRA_MAP_URL(
"extra_map_url"), FIREFOX_BINARY_PATH(
"firefox_exe_path"), GEE_EXPLORER_URL(
"gee_explorer_url"), GEE_FUNCTION_PICK(
"gee_js_pickFunction"), GEE_INITIAL_ZOOM(
"gee_initial_zoom"), GEE_JS_LIBRARY_URL(
"gee_js_library_url"), GEE_PLAYGROUND_URL(
"gee_playground_url"), GEE_ZOOM_METHOD(
"gee_js_zoom_method"), GEE_ZOOM_OBJECT(
"gee_js_zoom_object"), GENERATED_KEY(
"generated_on"), GOOGLE_MAPS_API_KEY(
"google_maps_api_key"), HERE_MAPS_APP_CODE(
"here_app_code"), HERE_MAPS_APP_ID(
"here_app_id"), HOST_KEY(
"host"), HOST_PORT_KEY(
"port"), INNER_SUBPLOT_SIDE(
"inner_point_side"), JUMP_TO_NEXT(
"jump_to_next_plot"), KML_TEMPLATE_KEY(
"template"), KML_TEMPLATE_KEY_CHECKSUM(
"template_checksum"), LAST_EXPORTED_DATE(
"last_exported_survey_date"), LAST_IGNORED_UPDATE(
"last_ignored_update_version"), LAST_USED_FOLDER(
"last_used_folder"), LOADED_PROJECTS(
"loaded_projects"), LOCAL_PORT_KEY(
"local_port"), METADATA_FILE(
"metadata_file"), MODEL_VERSION_NAME(
"model_version_name"), NUMBER_OF_SAMPLING_POINTS_IN_PLOT(
"number_of_sampling_points_in_plot"), OPEN_BALLOON_IN_BROWSER(
"open_separate_browser_form"), OPEN_BING_MAPS(
"open_bing_maps"), OPEN_GEE_EXPLORER(
"open_earth_engine"), OPEN_GEE_CODE_EDITOR(
"open_gee_playground"), OPEN_HERE_MAPS(
"open_here_maps"), OPEN_STREET_VIEW(
"open_street_view"), OPEN_TIMELAPSE(
"open_timelapse"), OPEN_YANDEX_MAPS(
"open_yandex_maps"), OPERATION_MODE(
"operation_mode"), OPERATOR_KEY(
"operator"), SAIKU_SERVER_FOLDER(
"saiku_server_folder"), SAMPLE_FILE(
"csv"), SAMPLE_SHAPE(
"sample_shape"), SURVEY_NAME(
"survey_name"), UI_LANGUAGE(
"ui_language"), LARGE_CENTRAL_PLOT_SIDE(
"large_central_plot_side"), OPEN_BAIDU_MAPS(
"open_baidu_maps"), DISTANCE_TO_BUFFERS(
"distance_to_buffers"), OPEN_PLANET_MAPS(
"open_planet_maps"), PLANET_MAPS_KEY(
"planet_maps_key"), PLANET_MAPS_MONHLY("planet_maps_monthly"), PLANET_MAPS_CE_KEY("planet_maps_ce_key"), OPEN_GEE_APP(
"open_gee_app"), GEE_MAP_URL(
"gee_app_url"), OPEN_MAXAR_SECUREWATCH(
"open_maxar_securewatch"),MAXAR_SECUREWATCH_URL("secure_watch_url"), EARTH_MAP_URL("earth_map_url"),
PLANET_NICFI_URL("planet_nicfi_url"),
OPEN_EARTH_MAP("open_earth_map"),
EARTH_MAP_LAYERS("earth_map_layers"),
EARTH_MAP_SCRIPTS("earth_map_scripts"),
EARTH_MAP_AOI("earth_map_aoi");
private String name;
private EarthProperty(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public static final String DEFAULT_LOCAL_PORT = "8028";
public static final String LOCAL_HOST = "127.0.0.1";
private static final String PROPERTIES_FILE_PATH = FolderFinder.getCollectEarthDataFolder() + File.separator
+ "earth.properties";
private static final String PROPERTIES_FILE_PATH_FORCED_UPDATE = "earth.properties_forced_update";
private static final String PROPERTIES_FILE_PATH_INITIAL = "earth.properties_initial";
private Logger logger = LoggerFactory.getLogger(LocalPropertiesService.class);;
private Properties properties;
public LocalPropertiesService() {
try {
init();
} catch (IOException e) {
logger.error("Error initilizeng Local Properties", e);
}
}
public String convertToOSPath(String path) {
String pathSeparator = File.separator;
path = path.replace("/", pathSeparator);
path = path.replace("\\", pathSeparator);
return path;
}
public String getBalloonFile() {
return convertToOSPath(getValue(EarthProperty.BALLOON_TEMPLATE_KEY));
}
public String getBalloonFileChecksum() {
return getValue(EarthProperty.BALLOON_TEMPLATE_KEY_CHECKSUM);
}
public CollectDBDriver getCollectDBDriver() {
final String collectDbDriver = getValue(EarthProperty.DB_DRIVER);
if (collectDbDriver.length() == 0) {
return CollectDBDriver.SQLITE;
}
return CollectDBDriver.valueOf(collectDbDriver);
}
public String getCrs() {
return getValue(EarthProperty.CRS_KEY);
}
public String getCsvFile() {
return convertToOSPath(getValue(EarthProperty.SAMPLE_FILE));
}
public String getCsvFileChecksum() {
return getValue(EarthProperty.CSV_KEY_CHECKSUM);
}
private String getExportedSurveyName(String surveyName) {
return EarthProperty.LAST_EXPORTED_DATE + "_" + surveyName;
}
public String getEarthMapAOI() {
return getValue(EarthProperty.EARTH_MAP_AOI);
}
public String getEarthMapLayers() {
return getValue(EarthProperty.EARTH_MAP_LAYERS);
}
public String getEarthMapScripts() {
return getValue(EarthProperty.EARTH_MAP_SCRIPTS);
}
public String getEarthMapURL() {
return getValue(EarthProperty.EARTH_MAP_URL);
}
public String getExtraMap() {
return getValue(EarthProperty.EXTRA_MAP_URL);
}
public String getGEEAppURL() {
return getValue(EarthProperty.GEE_MAP_URL);
}
public String getPlanetMapsKey() {
return getValue(EarthProperty.PLANET_MAPS_KEY);
}
public String getPlanetMapsCeKey() {
return getValue(EarthProperty.PLANET_MAPS_CE_KEY);
}
public String getGeePlaygoundUrl() {
if (isPropertyActivated(EarthProperty.GEE_PLAYGROUND_URL)) {
return getValue(EarthProperty.GEE_PLAYGROUND_URL);
} else {
return "https://code.earthengine.google.com/";
}
}
public String getGeneratedOn() {
return getValue(EarthProperty.GENERATED_KEY);
}
public String getHost() {
if (getOperationMode().equals(OperationMode.CLIENT_MODE)) {
return getValue(EarthProperty.HOST_KEY);
} else {
return LOCAL_HOST;
}
}
public String getImdFile() {
return convertToOSPath(getValue(EarthProperty.METADATA_FILE));
}
public Date getLastExportedDate(String surveyName) {
final String value = (String) properties.get(getExportedSurveyName(surveyName));
Date lastExported = null;
try {
if (!StringUtils.isBlank(value)) {
lastExported = new Date(Long.parseLong(value));
}
} catch (final NumberFormatException e) {
logger.error("Error parsing date", e);
}
return lastExported;
}
public String getLocalPort() {
if (getOperationMode().equals(OperationMode.SERVER_MODE)) {
return getPort();
} else {
return getValue(EarthProperty.LOCAL_PORT_KEY);
}
}
public String getModelVersionName() {
String modelVersion = (java.lang.String) properties.get(EarthProperty.MODEL_VERSION_NAME.toString());
if (modelVersion != null && modelVersion.trim().length() == 0) {
modelVersion = null;
}
return modelVersion;
}
public OperationMode getOperationMode() {
final String instanceType = getValue(EarthProperty.OPERATION_MODE);
if (instanceType.length() == 0) {
return OperationMode.SERVER_MODE;
}
return OperationMode.valueOf(instanceType);
}
public String getOperator() {
return getValue(EarthProperty.OPERATOR_KEY);
}
public String getPort() {
String port = getValue(EarthProperty.HOST_PORT_KEY);
if (StringUtils.isEmpty(port)) {
port = DEFAULT_LOCAL_PORT;
}
return port;
}
public String getProjectFolder() {
final File metadataFile = new File(getImdFile());
return metadataFile.getParent();
}
public String getSaikuFolder() {
final String configuredSaikuFolder = convertToOSPath(getValue(EarthProperty.SAIKU_SERVER_FOLDER));
if (StringUtils.isBlank(configuredSaikuFolder)) {
return ""; //$NON-NLS-1$
} else {
final File saikuFolder = new File(configuredSaikuFolder);
return saikuFolder.getAbsolutePath();
}
}
public SAMPLE_SHAPE getSampleShape() {
final String value = getValue(EarthProperty.SAMPLE_SHAPE);
if (StringUtils.isBlank(value)) {
return SAMPLE_SHAPE.SQUARE;
} else {
return SAMPLE_SHAPE.valueOf(value);
}
}
public String getSecureWatchURL() {
return getValue(EarthProperty.MAXAR_SECUREWATCH_URL);
}
public String getPlanetNicfiURL() {
return getValue(EarthProperty.PLANET_NICFI_URL);
}
public String getTemplateFile() {
return convertToOSPath(getValue(EarthProperty.KML_TEMPLATE_KEY));
}
public String getTemplateFileChecksum() {
return getValue(EarthProperty.KML_TEMPLATE_KEY_CHECKSUM);
}
public UI_LANGUAGE getUiLanguage() {
final String value = getValue(EarthProperty.UI_LANGUAGE);
if (StringUtils.isBlank(value)) {
return UI_LANGUAGE.EN;
} else {
UI_LANGUAGE selected = null;
try {
selected = UI_LANGUAGE.valueOf(value.toUpperCase());
} catch (Exception e) {
logger.warn("Unknown UI Language " + value);
}
if (selected != null) {
return selected;
} else {
return UI_LANGUAGE.EN;
}
}
}
public String getValue(EarthProperty key) {
String value = (String) properties.get(key.toString());
if (value == null) {
value = "";
}
return value;
}
private void init() throws IOException {
properties = new Properties() {
private static final long serialVersionUID = 4358906731731542445L;
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
boolean newInstallation = false;
File propertiesFileInitial = new File(PROPERTIES_FILE_PATH_INITIAL);
try {
File propertiesFile = new File(PROPERTIES_FILE_PATH);
if (!propertiesFile.exists() || propertiesFile.length() < 300) {
if (!propertiesFile.exists()) {
final boolean success = propertiesFile.createNewFile();
if (!success) {
throw new IOException("Could not create file " + propertiesFile.getAbsolutePath());
}
}
// The earth.properties file does not exists, this mean that the
// earth_properties.initial file is used, only the first time
propertiesFile = propertiesFileInitial;
newInstallation = true;
}
try( FileReader fr = new FileReader(propertiesFile); ){
properties.load(fr);
if (!newInstallation) {
// Add properties in initial_properties that are not present in earth.properites
// so that adding new properties in coming version does not generate issues with
// older versions
if (propertiesFileInitial.exists()) {
Properties initialProperties = new Properties();
try( FileReader frPropsFileInit = new FileReader(propertiesFileInitial) ){
initialProperties.load(frPropsFileInit);
Enumeration<String> initialPropertyNames = (Enumeration<String>) initialProperties.propertyNames();
while (initialPropertyNames.hasMoreElements()) {
String nextElement = initialPropertyNames.nextElement();
if (properties.get(nextElement) == null) {
properties.put(nextElement, initialProperties.getProperty(nextElement));
}
}
}
}
// UPDATERS!
// Emergency procedure for forcing the change of a value for updaters!
File propertiesForceChange = new File(PROPERTIES_FILE_PATH_FORCED_UPDATE);
if (propertiesForceChange.exists()) {
try( FileReader frProps = new FileReader(propertiesForceChange);){
properties.load(frProps);
// This procedure will only happen right after update
propertiesForceChange.deleteOnExit();
}
}
}
}
} catch (final FileNotFoundException e) {
logger.error("Could not find properties file", e);
} catch (final IOException e) {
logger.error("Could not open properties file", e);
}
}
public boolean isBaiduMapsSupported() {
return isPropertyActivated(EarthProperty.OPEN_BAIDU_MAPS);
}
public boolean isBingMapsSupported() {
return isPropertyActivated(EarthProperty.OPEN_BING_MAPS);
}
public boolean isGEEAppSupported() {
return isPropertyActivated(EarthProperty.OPEN_GEE_APP);
}
public boolean isCodeEditorSupported() {
return isPropertyActivated(EarthProperty.OPEN_GEE_CODE_EDITOR);
}
public boolean isEarthMapSupported() {
return isPropertyActivated(EarthProperty.OPEN_EARTH_MAP);
}
public boolean isExplorerSupported() {
return isPropertyActivated(EarthProperty.OPEN_GEE_EXPLORER);
}
public Boolean isExceptionShown() {
return isPropertyActivated(EarthProperty.EXCEPTION_SHOWN);
}
public boolean isHereMapsSupported() {
return isPropertyActivated(EarthProperty.OPEN_HERE_MAPS);
}
public boolean isPlanetMapsSupported() {
return isPropertyActivated(EarthProperty.OPEN_PLANET_MAPS);
}
public boolean isPlanetMapsMonthlyOpen() {
return isPropertyActivated(EarthProperty.PLANET_MAPS_MONHLY);
}
private boolean isPropertyActivated(EarthProperty earthProperty) {
boolean supported = false;
String value = getValue(earthProperty);
if (StringUtils.isNotBlank(value)) {
supported = Boolean.parseBoolean(value);
}
return supported;
}
public boolean isSecureWatchSupported() {
return isPropertyActivated(EarthProperty.OPEN_MAXAR_SECUREWATCH);
}
public boolean isStreetViewSupported() {
return isPropertyActivated(EarthProperty.OPEN_STREET_VIEW);
}
public boolean isTimelapseSupported() {
return isPropertyActivated(EarthProperty.OPEN_TIMELAPSE);
}
public boolean isUsingPostgreSqlDB() {
return getCollectDBDriver().equals(CollectDBDriver.POSTGRESQL);
}
public boolean isUsingSqliteDB() {
return getCollectDBDriver().equals(CollectDBDriver.SQLITE);
}
public boolean isYandexMapsSupported() {
return isPropertyActivated(EarthProperty.OPEN_YANDEX_MAPS);
}
public void nullifyChecksumValues() {
saveBalloonFileChecksum("");
saveCsvFileCehcksum("");
saveTemplateFileChecksum("");
storeProperties();
}
public void removeModelVersionName() {
setValue(EarthProperty.MODEL_VERSION_NAME, "");
}
public void saveBalloonFileChecksum(String checksum) {
setValue(EarthProperty.BALLOON_TEMPLATE_KEY_CHECKSUM, checksum);
}
public void saveCrs(String crsName) {
setValue(EarthProperty.CRS_KEY, crsName);
}
public void saveCsvFile(String csvFile) {
setValue(EarthProperty.SAMPLE_FILE, csvFile);
}
public void saveCsvFileCehcksum(String checksum) {
setValue(EarthProperty.CSV_KEY_CHECKSUM, checksum);
}
public void saveGeneratedOn(String dateGenerated) {
setValue(EarthProperty.GENERATED_KEY, dateGenerated);
}
public void saveHost(String hostName) {
setValue(EarthProperty.HOST_KEY, hostName);
}
public void saveOperator(String operatorName) {
setValue(EarthProperty.OPERATOR_KEY, operatorName);
}
public void savePort(String portName) {
setValue(EarthProperty.HOST_PORT_KEY, portName);
}
public void saveTemplateFileChecksum(String checksum) {
setValue(EarthProperty.KML_TEMPLATE_KEY_CHECKSUM, checksum);
}
public void setExceptionShown(Boolean showException) {
setValue(EarthProperty.EXCEPTION_SHOWN, showException.toString());
}
public void setJumpToNextPlot(String shouldSkip) {
String booleanSkip = "";
if (shouldSkip != null && shouldSkip.length() > 0) {
if (shouldSkip.equals("on")) {
booleanSkip = "true";
} else if (shouldSkip.equals("off")) {
booleanSkip = "false";
}
} else {
booleanSkip = "false";
}
setValue(EarthProperty.JUMP_TO_NEXT, booleanSkip);
}
public void setLastExportedDate(String surveyName) {
setValue(getExportedSurveyName(surveyName), Long.toString(System.currentTimeMillis()));
}
public void setModelVersionName(String modelVersionName) {
setValue(EarthProperty.MODEL_VERSION_NAME, modelVersionName);
}
public void setSampleShape(SAMPLE_SHAPE shape) {
setValue(EarthProperty.SAMPLE_SHAPE, shape.name());
}
public void setUiLanguage(UI_LANGUAGE language) {
setValue(EarthProperty.UI_LANGUAGE, language.name());
}
public void setValue(Object key, String value) {
properties.setProperty(key.toString(), value);
this.setChanged();
this.notifyObservers(key);
storeProperties();
}
public boolean shouldJumpToNextPlot() {
boolean jumpToNext = false;
if (getValue(EarthProperty.JUMP_TO_NEXT) != null && getValue(EarthProperty.JUMP_TO_NEXT).length() > 0) {
jumpToNext = Boolean.parseBoolean(getValue(EarthProperty.JUMP_TO_NEXT));
}
return jumpToNext;
}
private synchronized void storeProperties() {
File propertiesFile = new File(PROPERTIES_FILE_PATH);
try(FileWriter fw = new FileWriter(propertiesFile) ) {
properties.store(fw, null);
} catch (final IOException e) {
logger.error("The properties could not be saved", e);
}
}
}
|
package com.sap.core.odata.processor.core.jpa;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sap.core.odata.api.commons.HttpStatusCodes;
import com.sap.core.odata.api.commons.InlineCount;
import com.sap.core.odata.api.edm.EdmEntitySet;
import com.sap.core.odata.api.edm.EdmEntityType;
import com.sap.core.odata.api.edm.EdmException;
import com.sap.core.odata.api.edm.EdmFunctionImport;
import com.sap.core.odata.api.edm.EdmLiteralKind;
import com.sap.core.odata.api.edm.EdmMultiplicity;
import com.sap.core.odata.api.edm.EdmNavigationProperty;
import com.sap.core.odata.api.edm.EdmProperty;
import com.sap.core.odata.api.edm.EdmSimpleType;
import com.sap.core.odata.api.edm.EdmStructuralType;
import com.sap.core.odata.api.edm.EdmType;
import com.sap.core.odata.api.edm.EdmTypeKind;
import com.sap.core.odata.api.ep.EntityProvider;
import com.sap.core.odata.api.ep.EntityProviderException;
import com.sap.core.odata.api.ep.EntityProviderWriteProperties;
import com.sap.core.odata.api.ep.EntityProviderWriteProperties.ODataEntityProviderPropertiesBuilder;
import com.sap.core.odata.api.exception.ODataException;
import com.sap.core.odata.api.exception.ODataNotFoundException;
import com.sap.core.odata.api.processor.ODataContext;
import com.sap.core.odata.api.processor.ODataResponse;
import com.sap.core.odata.api.uri.ExpandSelectTreeNode;
import com.sap.core.odata.api.uri.NavigationPropertySegment;
import com.sap.core.odata.api.uri.SelectItem;
import com.sap.core.odata.api.uri.UriParser;
import com.sap.core.odata.api.uri.info.DeleteUriInfo;
import com.sap.core.odata.api.uri.info.GetEntityLinkUriInfo;
import com.sap.core.odata.api.uri.info.GetEntitySetLinksUriInfo;
import com.sap.core.odata.api.uri.info.GetEntitySetUriInfo;
import com.sap.core.odata.api.uri.info.GetEntityUriInfo;
import com.sap.core.odata.api.uri.info.GetFunctionImportUriInfo;
import com.sap.core.odata.api.uri.info.PostUriInfo;
import com.sap.core.odata.api.uri.info.PutMergePatchUriInfo;
import com.sap.core.odata.processor.api.jpa.ODataJPAContext;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
import com.sap.core.odata.processor.core.jpa.access.data.JPAEntityParser;
import com.sap.core.odata.processor.core.jpa.access.data.JPAExpandCallBack;
public final class ODataJPAResponseBuilder {
/* Response for Read Entity Set */
public static <T> ODataResponse build(List<T> jpaEntities,
GetEntitySetUriInfo resultsView, String contentType,
ODataJPAContext odataJPAContext) throws ODataJPARuntimeException {
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
List<ArrayList<NavigationPropertySegment>> expandList = null;
try {
edmEntityType = resultsView.getTargetEntitySet().getEntityType();
List<Map<String, Object>> edmEntityList = new ArrayList<Map<String, Object>>();
Map<String, Object> edmPropertyValueMap = null;
JPAEntityParser jpaResultParser = JPAEntityParser.create();
final List<SelectItem> selectedItems = resultsView.getSelect();
if (selectedItems != null && selectedItems.size() > 0) {
for (Object jpaEntity : jpaEntities) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(
jpaEntity,
buildSelectItemList(selectedItems,
edmEntityType));
edmEntityList.add(edmPropertyValueMap);
}
} else {
for (Object jpaEntity : jpaEntities) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(jpaEntity, edmEntityType);
edmEntityList.add(edmPropertyValueMap);
}
}
expandList = resultsView.getExpand();
if (expandList != null && expandList.size() != 0) {
int count = 0;
for (Object jpaEntity : jpaEntities) {
Map<String, Object> relationShipMap = edmEntityList.get(count);
HashMap<String, Object> navigationMap = jpaResultParser.parse2EdmNavigationValueMap(
jpaEntity, constructListofNavProperty(expandList));
relationShipMap.putAll(navigationMap);
count++;
}
}
EntityProviderWriteProperties feedProperties = null;
feedProperties = getEntityProviderProperties(odataJPAContext,
resultsView, edmEntityList);
odataResponse = EntityProvider.writeFeed(contentType,
resultsView.getTargetEntitySet(), edmEntityList,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.OK).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
/* Response for Read Entity */
public static ODataResponse build(Object jpaEntity,
GetEntityUriInfo resultsView, String contentType,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException,
ODataNotFoundException {
List<ArrayList<NavigationPropertySegment>> expandList = null;
if (jpaEntity == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
edmEntityType = resultsView.getTargetEntitySet().getEntityType();
Map<String, Object> edmPropertyValueMap = null;
JPAEntityParser jpaResultParser = JPAEntityParser.create();
final List<SelectItem> selectedItems = resultsView.getSelect();
if (selectedItems != null && selectedItems.size() > 0) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(
jpaEntity,
buildSelectItemList(selectedItems, resultsView
.getTargetEntitySet().getEntityType()));
} else
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(jpaEntity, edmEntityType);
expandList = resultsView.getExpand();
if (expandList != null && expandList.size() != 0)
{
HashMap<String, Object> navigationMap = jpaResultParser.parse2EdmNavigationValueMap(
jpaEntity, constructListofNavProperty(expandList));
edmPropertyValueMap.putAll(navigationMap);
}
EntityProviderWriteProperties feedProperties = null;
feedProperties = getEntityProviderProperties(oDataJPAContext,
resultsView);
odataResponse = EntityProvider.writeEntry(contentType,
resultsView.getTargetEntitySet(), edmPropertyValueMap,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.OK).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
/* Response for $count */
public static ODataResponse build(long jpaEntityCount,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException {
ODataResponse odataResponse = null;
try {
odataResponse = EntityProvider.writeText(String
.valueOf(jpaEntityCount));
odataResponse = ODataResponse.fromResponse(odataResponse).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
/* Response for Create Entity */
@SuppressWarnings("unchecked")
public static ODataResponse build(List<Object> createdObjectList,
PostUriInfo uriInfo, String contentType,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException,
ODataNotFoundException {
if (createdObjectList == null || createdObjectList.size() == 0 || createdObjectList.get(0) == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
edmEntityType = uriInfo.getTargetEntitySet().getEntityType();
Map<String, Object> edmPropertyValueMap = null;
JPAEntityParser jpaResultParser = JPAEntityParser.create();
edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(
createdObjectList.get(0), edmEntityType);
List<ArrayList<NavigationPropertySegment>> expandList = null;
if (createdObjectList.get(1) != null && ((Map<EdmNavigationProperty, EdmEntitySet>) createdObjectList.get(1)).size() > 0) {
expandList = getExpandList((Map<EdmNavigationProperty, EdmEntitySet>) createdObjectList.get(1));
HashMap<String, Object> navigationMap = jpaResultParser.parse2EdmNavigationValueMap(
createdObjectList.get(0), constructListofNavProperty(expandList));
edmPropertyValueMap.putAll(navigationMap);
}
EntityProviderWriteProperties feedProperties = null;
try {
feedProperties = getEntityProviderPropertiesforPost(oDataJPAContext, uriInfo, expandList);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
odataResponse = EntityProvider.writeEntry(contentType,
uriInfo.getTargetEntitySet(), edmPropertyValueMap,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.CREATED).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
/* Response for Update Entity */
public static ODataResponse build(Object updatedObject,
PutMergePatchUriInfo putUriInfo) throws ODataJPARuntimeException,
ODataNotFoundException {
if (updatedObject == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
return ODataResponse.status(HttpStatusCodes.NO_CONTENT).build();
}
/* Response for Delete Entity */
public static ODataResponse build(Object deletedObject,
DeleteUriInfo deleteUriInfo) throws ODataJPARuntimeException,
ODataNotFoundException {
if (deletedObject == null) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
}
return ODataResponse.status(HttpStatusCodes.OK).build();
}
/* Response for Function Import Single Result */
public static ODataResponse build(Object result,
GetFunctionImportUriInfo resultsView)
throws ODataJPARuntimeException {
try {
final EdmFunctionImport functionImport = resultsView
.getFunctionImport();
final EdmSimpleType type = (EdmSimpleType) functionImport
.getReturnType().getType();
if (result != null) {
ODataResponse response = null;
final String value = type.valueToString(result,
EdmLiteralKind.DEFAULT, null);
response = EntityProvider.writeText(value);
return ODataResponse.fromResponse(response).build();
} else
throw new ODataNotFoundException(ODataNotFoundException.COMMON);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
}
/* Response for Function Import Multiple Result */
public static ODataResponse build(List<Object> resultList,
GetFunctionImportUriInfo resultsView, String contentType,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException,
ODataNotFoundException {
ODataResponse odataResponse = null;
if (resultList != null && !resultList.isEmpty()) {
JPAEntityParser jpaResultParser = JPAEntityParser.create();
EdmType edmType = null;
EdmFunctionImport functionImport = null;
Map<String, Object> edmPropertyValueMap = null;
List<Map<String, Object>> edmEntityList = null;
Object result = null;
try {
EntityProviderWriteProperties feedProperties = null;
feedProperties = EntityProviderWriteProperties.serviceRoot(
oDataJPAContext.getODataContext().getPathInfo()
.getServiceRoot()).build();
functionImport = resultsView.getFunctionImport();
edmType = functionImport.getReturnType().getType();
if (edmType.getKind().equals(EdmTypeKind.ENTITY)
|| edmType.getKind().equals(EdmTypeKind.COMPLEX)) {
if (functionImport.getReturnType().getMultiplicity()
.equals(EdmMultiplicity.MANY)) {
edmEntityList = new ArrayList<Map<String, Object>>();
for (Object jpaEntity : resultList) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(jpaEntity,
(EdmStructuralType) edmType);
edmEntityList.add(edmPropertyValueMap);
}
result = edmEntityList;
} else {
Object resultObject = resultList.get(0);
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(resultObject,
(EdmStructuralType) edmType);
result = edmPropertyValueMap;
}
} else if (edmType.getKind().equals(EdmTypeKind.SIMPLE)) {
result = resultList.get(0);
}
odataResponse = EntityProvider
.writeFunctionImport(contentType,
resultsView.getFunctionImport(), result,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.OK).build();
} catch (EdmException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
} catch (EntityProviderException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
} else
throw new ODataNotFoundException(ODataNotFoundException.COMMON);
return odataResponse;
}
/* Response for Read Entity Link */
public static ODataResponse build(Object jpaEntity,
GetEntityLinkUriInfo resultsView, String contentType, ODataJPAContext oDataJPAContext)
throws ODataNotFoundException, ODataJPARuntimeException {
if (jpaEntity == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
EdmEntitySet entitySet = resultsView.getTargetEntitySet();
edmEntityType = entitySet.getEntityType();
Map<String, Object> edmPropertyValueMap = null;
JPAEntityParser jpaResultParser = JPAEntityParser.create();
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(
jpaEntity,
edmEntityType.getKeyProperties());
EntityProviderWriteProperties entryProperties = EntityProviderWriteProperties
.serviceRoot(oDataJPAContext.getODataContext().getPathInfo().getServiceRoot())
.build();
ODataResponse response = EntityProvider.writeLink(contentType, entitySet, edmPropertyValueMap, entryProperties);
odataResponse = ODataResponse.fromResponse(response).build();
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return odataResponse;
}
/* Response for Read Entity Links */
public static <T> ODataResponse build(List<T> jpaEntities,
GetEntitySetLinksUriInfo resultsView, String contentType,
ODataJPAContext oDataJPAContext)
throws ODataJPARuntimeException {
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
EdmEntitySet entitySet = resultsView.getTargetEntitySet();
edmEntityType = entitySet.getEntityType();
List<EdmProperty> keyProperties = edmEntityType.getKeyProperties();
List<Map<String, Object>> edmEntityList = new ArrayList<Map<String, Object>>();
Map<String, Object> edmPropertyValueMap = null;
JPAEntityParser jpaResultParser = JPAEntityParser.create();
for (Object jpaEntity : jpaEntities) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(
jpaEntity,
keyProperties);
edmEntityList.add(edmPropertyValueMap);
}
Integer count = resultsView.getInlineCount() == InlineCount.ALLPAGES ? edmEntityList
.size() : null;
ODataContext context = oDataJPAContext.getODataContext();
EntityProviderWriteProperties entryProperties = EntityProviderWriteProperties
.serviceRoot(context.getPathInfo().getServiceRoot())
.inlineCountType(resultsView.getInlineCount())
.inlineCount(count)
.build();
odataResponse = EntityProvider.writeLinks(contentType, entitySet, edmEntityList, entryProperties);
odataResponse = ODataResponse.fromResponse(odataResponse).build();
} catch (ODataException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
/*
* Method to build the entity provider Property.Callbacks for $expand would
* be registered here
*/
private static EntityProviderWriteProperties getEntityProviderProperties(
ODataJPAContext odataJPAContext, GetEntitySetUriInfo resultsView,
List<Map<String, Object>> edmEntityList)
throws ODataJPARuntimeException {
ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null;
Integer count = resultsView.getInlineCount() == InlineCount.ALLPAGES ? edmEntityList
.size() : null;
try {
entityFeedPropertiesBuilder = EntityProviderWriteProperties
.serviceRoot(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot());
entityFeedPropertiesBuilder.inlineCount(count);
entityFeedPropertiesBuilder.inlineCountType(resultsView
.getInlineCount());
ExpandSelectTreeNode expandSelectTree = UriParser
.createExpandSelectTree(resultsView.getSelect(),
resultsView.getExpand());
entityFeedPropertiesBuilder.callbacks(JPAExpandCallBack
.getCallbacks(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot(), expandSelectTree,
resultsView.getExpand()));
entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return entityFeedPropertiesBuilder.build();
}
private static EntityProviderWriteProperties getEntityProviderProperties(
ODataJPAContext odataJPAContext, GetEntityUriInfo resultsView)
throws ODataJPARuntimeException {
ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null;
ExpandSelectTreeNode expandSelectTree = null;
try {
entityFeedPropertiesBuilder = EntityProviderWriteProperties
.serviceRoot(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot());
expandSelectTree = UriParser.createExpandSelectTree(
resultsView.getSelect(), resultsView.getExpand());
entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree);
entityFeedPropertiesBuilder.callbacks(JPAExpandCallBack
.getCallbacks(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot(), expandSelectTree,
resultsView.getExpand()));
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return entityFeedPropertiesBuilder.build();
}
private static EntityProviderWriteProperties getEntityProviderPropertiesforPost(
ODataJPAContext odataJPAContext, PostUriInfo resultsView, List<ArrayList<NavigationPropertySegment>> expandList)
throws ODataJPARuntimeException {
ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null;
ExpandSelectTreeNode expandSelectTree = null;
try {
entityFeedPropertiesBuilder = EntityProviderWriteProperties
.serviceRoot(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot());
expandSelectTree = UriParser.createExpandSelectTree(
null, expandList);
entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree);
entityFeedPropertiesBuilder.callbacks(JPAExpandCallBack
.getCallbacks(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot(), expandSelectTree,
expandList));
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return entityFeedPropertiesBuilder.build();
}
private static List<ArrayList<NavigationPropertySegment>> getExpandList(Map<EdmNavigationProperty, EdmEntitySet> navPropEntitySetMap) {
List<ArrayList<NavigationPropertySegment>> expandList = new ArrayList<ArrayList<NavigationPropertySegment>>();
ArrayList<NavigationPropertySegment> navigationPropertySegmentList = new ArrayList<NavigationPropertySegment>();
for (Map.Entry<EdmNavigationProperty, EdmEntitySet> entry : navPropEntitySetMap.entrySet()) {
final EdmNavigationProperty edmNavigationProperty = entry.getKey();
final EdmEntitySet edmEntitySet = entry.getValue();
NavigationPropertySegment navigationPropertySegment = new NavigationPropertySegment() {
@Override
public EdmEntitySet getTargetEntitySet() {
return edmEntitySet;
}
@Override
public EdmNavigationProperty getNavigationProperty() {
return edmNavigationProperty;
}
};
navigationPropertySegmentList.add(navigationPropertySegment);
}
expandList.add(navigationPropertySegmentList);
return expandList;
}
private static List<EdmProperty> buildSelectItemList(
List<SelectItem> selectItems, EdmEntityType entity) throws ODataJPARuntimeException {
boolean flag = false;
List<EdmProperty> selectPropertyList = new ArrayList<EdmProperty>();
try {
for (SelectItem selectItem : selectItems)
selectPropertyList.add(selectItem.getProperty());
for (EdmProperty keyProperty : entity.getKeyProperties()) {
flag = true;
for (SelectItem selectedItem : selectItems) {
if (selectedItem.getProperty().equals(keyProperty)) {
flag = false;
break;
}
}
if (flag == true)
selectPropertyList.add(keyProperty);
}
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return selectPropertyList;
}
private static List<EdmNavigationProperty> constructListofNavProperty(
List<ArrayList<NavigationPropertySegment>> expandList) {
List<EdmNavigationProperty> navigationPropertyList = new ArrayList<EdmNavigationProperty>();
for (ArrayList<NavigationPropertySegment> navpropSegment : expandList)
navigationPropertyList.add(navpropSegment.get(0)
.getNavigationProperty());
return navigationPropertyList;
}
}
|
package ASSET.Util.XML.Vessels;
import ASSET.Models.MovementType;
import ASSET.Util.XML.Decisions.WaterfallHandler;
abstract public class ParticipantHandler extends MWC.Utilities.ReaderWriter.XML.MWCXMLReader
{
public static final String NAME = "Name";
public static final String MONTE_CARLO_TARGET = "MonteCarloTarget";
private String _myName;
private boolean _isMonteCarlo = false;
private int _myId = ASSET.ScenarioType.INVALID_ID;
private ASSET.Participants.Category _myCategory;
private ASSET.Participants.Status _myStatus;
private ASSET.Participants.DemandedStatus _myDemandedStatus;
private ASSET.Models.Sensor.SensorList _mySensorList;
private ASSET.Models.DecisionType _myDecisionModel;
private ASSET.Models.Vessels.Radiated.RadiatedCharacteristics _myRads;
private ASSET.Models.Vessels.Radiated.RadiatedCharacteristics _mySelfNoise;
// MOVEMENT CHARACTERISTICS - retrieved by child classes
protected ASSET.Models.Movement.MovementCharacteristics _myMoveChars;
protected MovementType _myMovement;
ParticipantHandler(final String type)
{
// inform our parent what type of class we are
super(type);
super.addAttributeHandler(new HandleAttribute("id")
{
public void setValue(String name, final String val)
{
_myId = Integer.parseInt(val);
}
});
super.addAttributeHandler(new HandleAttribute(NAME)
{
public void setValue(String name, final String val)
{
_myName = val;
}
});
super.addAttributeHandler(new HandleBooleanAttribute(MONTE_CARLO_TARGET)
{
public void setValue(String name, final boolean val)
{
_isMonteCarlo = val;
}
});
// add the readers for participant properties
addHandler(new ASSET.Util.XML.Vessels.Util.CategoryHandler()
{
public void setCategory(final ASSET.Participants.Category cat)
{
_myCategory = cat;
}
});
addHandler(new ASSET.Util.XML.Vessels.Util.StatusHandler()
{
public void setStatus(final ASSET.Participants.Status stat)
{
_myStatus = stat;
}
});
addHandler(new ASSET.Util.XML.Vessels.Util.DemandedStatusHandler()
{
public void setDemandedStatus(final ASSET.Participants.DemandedStatus stat)
{
_myDemandedStatus = stat;
}
});
addHandler(new ASSET.Util.XML.Sensors.SensorFitHandler()
{
public void setSensorFit(final ASSET.Models.Sensor.SensorList list)
{
_mySensorList = list;
}
});
addHandler(new ASSET.Util.XML.Decisions.WaterfallHandler(WaterfallHandler.MAX_CHAIN_DEPTH)
{
public void setModel(final ASSET.Models.DecisionType chain)
{
_myDecisionModel = chain;
}
});
addHandler(new ASSET.Util.XML.Decisions.SequenceHandler(WaterfallHandler.MAX_CHAIN_DEPTH)
{
public void setModel(final ASSET.Models.DecisionType chain)
{
_myDecisionModel = chain;
}
});
addHandler(new ASSET.Util.XML.Decisions.SwitchHandler(WaterfallHandler.MAX_CHAIN_DEPTH)
{
public void setModel(final ASSET.Models.DecisionType chain)
{
_myDecisionModel = chain;
}
});
// addHandler(new ASSET.Util.XML.Movement.MovementCharsHandler()
// public void setMovement(final ASSET.Models.Movement.MovementCharacteristics chars)
// _myMoves = chars;
addHandler(new ASSET.Util.XML.Vessels.Util.RadiatedCharsHandler()
{
public void setRadiation(final ASSET.Models.Vessels.Radiated.RadiatedCharacteristics chars)
{
_myRads = chars;
}
});
addHandler(new ASSET.Util.XML.Vessels.Util.SelfNoiseHandler()
{
public void setRadiation(final ASSET.Models.Vessels.Radiated.RadiatedCharacteristics chars)
{
_mySelfNoise = chars;
}
});
addHandler(new ASSET.Util.XML.Vessels.Util.MovementHandler()
{
public void setMovement(final ASSET.Models.MovementType movement)
{
_myMovement = movement;
}
});
}
private static int checkId(final int theID)
{
int res = theID;
// if the index is zero, we will create one
if (res == ASSET.Scenario.CoreScenario.INVALID_ID)
res = ASSET.Util.IdNumber.generateInt();
return res;
}
public void elementClosed()
{
_myId = checkId(_myId);
// get this instance
final ASSET.ParticipantType thisPart = getParticipant(_myId);
// add in the attributes we have observed
thisPart.setName(_myName);
thisPart.setCategory(_myCategory);
// update the id
_myStatus.setId(_myId);
thisPart.setStatus(_myStatus);
thisPart.setDemandedStatus(_myDemandedStatus);
if(_mySensorList != null)
thisPart.setSensorFit(_mySensorList);
thisPart.setDecisionModel(_myDecisionModel);
thisPart.setMovementChars(_myMoveChars);
thisPart.setRadiatedChars(_myRads);
thisPart.setSelfNoise(_mySelfNoise);
if(_myMovement != null)
thisPart.setMovementModel(_myMovement);
// allow the child classes to finish off the participant
finishParticipant(thisPart);
// store in the parent
addThis(thisPart, _isMonteCarlo);
// clear local vars
_myId = ASSET.ScenarioType.INVALID_ID;
_isMonteCarlo = false;
_myName = null;
_myCategory = null;
_myStatus = null;
_myDemandedStatus = null;
_mySensorList = null;
_myDecisionModel = null;
_myMoveChars = null;
_myRads = null;
_mySelfNoise = null;
}
/** extra method provided to allow child classes to interrupt the participant
* creation process
*/
void finishParticipant(ASSET.ParticipantType newPart)
{
}
abstract public void addThis(ASSET.ParticipantType part, boolean isMonteCarlo);
abstract protected ASSET.ParticipantType getParticipant(int index);
static void exportThis(final Object toExport, final org.w3c.dom.Element thisElement, final org.w3c.dom.Document doc)
{
final ASSET.ParticipantType part = (ASSET.ParticipantType) toExport;
thisElement.setAttribute("Name", part.getName());
// participant category
ASSET.Util.XML.Vessels.Util.CategoryHandler.exportThis(part.getCategory(), thisElement, doc);
// sensor list
ASSET.Util.XML.Sensors.SensorFitHandler.exportThis(part, thisElement, doc);
// current status
ASSET.Util.XML.Vessels.Util.StatusHandler.exportThis(part.getStatus(), thisElement, doc);
// current demanded status
ASSET.Util.XML.Vessels.Util.DemandedStatusHandler.exportThis(part.getDemandedStatus(), thisElement, doc);
// decision model
final ASSET.Models.DecisionType dec = part.getDecisionModel();
if (dec instanceof ASSET.Models.Decision.Switch)
ASSET.Util.XML.Decisions.SwitchHandler.exportThis(dec, thisElement, doc);
else if (dec instanceof ASSET.Models.Decision.Sequence)
ASSET.Util.XML.Decisions.SequenceHandler.exportSequence(dec, thisElement, doc);
else if (dec instanceof ASSET.Models.Decision.Waterfall)
ASSET.Util.XML.Decisions.WaterfallHandler.exportThis(dec, thisElement, doc);
// radiated noise characteristics
ASSET.Util.XML.Vessels.Util.RadiatedCharsHandler.exportThis(part.getRadiatedChars(), thisElement, doc);
// radiated noise characteristics
ASSET.Util.XML.Vessels.Util.SelfNoiseHandler.exportThis(part.getSelfNoise(), thisElement, doc);
// movement model
final ASSET.Models.MovementType mover = part.getMovementModel();
// start with the most specific instance first
if (mover instanceof ASSET.Models.Movement.SSKMovement)
ASSET.Util.XML.Movement.SSKMovementHandler.exportThis(mover, thisElement, doc);
else if (mover instanceof ASSET.Models.Movement.CoreMovement)
ASSET.Util.XML.Movement.MovementHandler.exportThis(mover, thisElement, doc);
}
}
|
package com.sap.core.odata.processor.core.jpa;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.sap.core.odata.api.commons.HttpStatusCodes;
import com.sap.core.odata.api.commons.InlineCount;
import com.sap.core.odata.api.edm.EdmEntityType;
import com.sap.core.odata.api.edm.EdmException;
import com.sap.core.odata.api.edm.EdmFunctionImport;
import com.sap.core.odata.api.edm.EdmLiteralKind;
import com.sap.core.odata.api.edm.EdmMultiplicity;
import com.sap.core.odata.api.edm.EdmNavigationProperty;
import com.sap.core.odata.api.edm.EdmProperty;
import com.sap.core.odata.api.edm.EdmSimpleType;
import com.sap.core.odata.api.edm.EdmStructuralType;
import com.sap.core.odata.api.edm.EdmType;
import com.sap.core.odata.api.edm.EdmTypeKind;
import com.sap.core.odata.api.ep.EntityProvider;
import com.sap.core.odata.api.ep.EntityProviderException;
import com.sap.core.odata.api.ep.EntityProviderWriteProperties;
import com.sap.core.odata.api.ep.EntityProviderWriteProperties.ODataEntityProviderPropertiesBuilder;
import com.sap.core.odata.api.exception.ODataException;
import com.sap.core.odata.api.exception.ODataNotFoundException;
import com.sap.core.odata.api.processor.ODataResponse;
import com.sap.core.odata.api.uri.ExpandSelectTreeNode;
import com.sap.core.odata.api.uri.NavigationPropertySegment;
import com.sap.core.odata.api.uri.SelectItem;
import com.sap.core.odata.api.uri.UriParser;
import com.sap.core.odata.api.uri.info.DeleteUriInfo;
import com.sap.core.odata.api.uri.info.GetEntitySetUriInfo;
import com.sap.core.odata.api.uri.info.GetEntityUriInfo;
import com.sap.core.odata.api.uri.info.GetFunctionImportUriInfo;
import com.sap.core.odata.api.uri.info.PostUriInfo;
import com.sap.core.odata.api.uri.info.PutMergePatchUriInfo;
import com.sap.core.odata.processor.api.jpa.ODataJPAContext;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
import com.sap.core.odata.processor.core.jpa.access.data.JPAExpandCallBack;
public final class ODataJPAResponseBuilder {
public static <T> ODataResponse build(List<T> jpaEntities,
GetEntitySetUriInfo resultsView, String contentType,
ODataJPAContext odataJPAContext) throws ODataJPARuntimeException {
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
List<ArrayList<NavigationPropertySegment>> expandList = null;
try {
edmEntityType = resultsView.getTargetEntitySet().getEntityType();
List<Map<String, Object>> edmEntityList = new ArrayList<Map<String, Object>>();
Map<String, Object> edmPropertyValueMap = null;
JPAResultParser jpaResultParser = JPAResultParser.create();
final List<SelectItem> selectedItems = resultsView.getSelect();
if (selectedItems != null && selectedItems.size() > 0) {
for (Object jpaEntity : jpaEntities) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMapFromList(
jpaEntity,
buildSelectItemList(selectedItems,
edmEntityType));
edmEntityList.add(edmPropertyValueMap);
}
} else {
for (Object jpaEntity : jpaEntities) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(jpaEntity, edmEntityType);
edmEntityList.add(edmPropertyValueMap);
}
}
expandList = resultsView.getExpand();
if (expandList != null && expandList.size() != 0) {
int count = 0;
for (Object jpaEntity : jpaEntities) {
jpaResultParser.parse2EdmPropertyListMap(
edmEntityList.get(count), jpaEntity,
constructListofNavProperty(expandList));
count++;
}
}
EntityProviderWriteProperties feedProperties = null;
// Getting the entity feed properties
feedProperties = getEntityProviderProperties(odataJPAContext,
resultsView, edmEntityList);
odataResponse = EntityProvider.writeFeed(contentType,
resultsView.getTargetEntitySet(), edmEntityList,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.OK).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
public static ODataResponse build(Object jpaEntity,
GetEntityUriInfo resultsView, String contentType,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException,
ODataNotFoundException {
List<ArrayList<NavigationPropertySegment>> expandList = null;
if (jpaEntity == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY); // Need
// throw
// 404
// with
// Message
// body
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
edmEntityType = resultsView.getTargetEntitySet().getEntityType();
Map<String, Object> edmPropertyValueMap = null;
JPAResultParser jpaResultParser = JPAResultParser.create();
final List<SelectItem> selectedItems = resultsView.getSelect();
if (selectedItems != null && selectedItems.size() > 0) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMapFromList(
jpaEntity,
buildSelectItemList(selectedItems, resultsView
.getTargetEntitySet().getEntityType()));
} else
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(jpaEntity, edmEntityType);
expandList = resultsView.getExpand();
if (expandList != null && expandList.size() != 0)
jpaResultParser.parse2EdmPropertyListMap(edmPropertyValueMap,
jpaEntity, constructListofNavProperty(expandList));
EntityProviderWriteProperties feedProperties = null;
feedProperties = getEntityProviderProperties(oDataJPAContext,
resultsView);
odataResponse = EntityProvider.writeEntry(contentType,
resultsView.getTargetEntitySet(), edmPropertyValueMap,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.OK).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
public static ODataResponse build(long jpaEntityCount,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException {
ODataResponse odataResponse = null;
try {
odataResponse = EntityProvider.writeText(String
.valueOf(jpaEntityCount));
odataResponse = ODataResponse.fromResponse(odataResponse).build();
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
public static ODataResponse build(List<Object> createdObjectList,
PostUriInfo uriInfo, String contentType,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException,
ODataNotFoundException {
if (createdObjectList == null || createdObjectList.size() == 0 || createdObjectList.get(0) == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY); // Need
// throw
// 404
// with
// Message
// body
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
edmEntityType = uriInfo.getTargetEntitySet().getEntityType();
Map<String, Object> edmPropertyValueMap = null;
JPAResultParser jpaResultParser = JPAResultParser.create();
edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(
createdObjectList.get(0), edmEntityType);
EntityProviderWriteProperties feedProperties = null;
try {
feedProperties = EntityProviderWriteProperties.serviceRoot(
oDataJPAContext.getODataContext().getPathInfo()
.getServiceRoot()).expandSelectTree((ExpandSelectTreeNode) createdObjectList.get(1)).build();
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
odataResponse = EntityProvider.writeEntry(contentType,
uriInfo.getTargetEntitySet(), edmPropertyValueMap,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.CREATED).build(); // Send status
// code along
// with body of
// created
// content
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return odataResponse;
}
public static ODataResponse build(Object updatedObject,
PutMergePatchUriInfo putUriInfo) throws ODataJPARuntimeException,
ODataNotFoundException {
if (updatedObject == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY); // Need
// throw
// 404
// with
// Message
// body
return ODataResponse.status(HttpStatusCodes.ACCEPTED).build(); // Body
// not
// needed
// for
// successful
// update;
}
public static ODataResponse build(Object deletedObject,
DeleteUriInfo deleteUriInfo) throws ODataJPARuntimeException,
ODataNotFoundException {
if (deletedObject == null) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY); // Need
// throw
// 404
// with
// Message
// body
}
return ODataResponse.status(HttpStatusCodes.NO_CONTENT).build(); // Body
// not
// needed
// for
// successful
// delete;
}
public static ODataResponse build(Object result,
GetFunctionImportUriInfo resultsView)
throws ODataJPARuntimeException {
try {
final EdmFunctionImport functionImport = resultsView
.getFunctionImport();
final EdmSimpleType type = (EdmSimpleType) functionImport
.getReturnType().getType();
if (result != null) {
ODataResponse response = null;
final String value = type.valueToString(result,
EdmLiteralKind.DEFAULT, null);
response = EntityProvider.writeText(value);
return ODataResponse.fromResponse(response).build();
} else
throw new ODataNotFoundException(ODataNotFoundException.COMMON);
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (EntityProviderException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
}
public static ODataResponse build(List<Object> resultList,
GetFunctionImportUriInfo resultsView, String contentType,
ODataJPAContext oDataJPAContext) throws ODataJPARuntimeException,
ODataNotFoundException {
ODataResponse odataResponse = null;
if (resultList != null && !resultList.isEmpty()) {
JPAResultParser jpaResultParser = JPAResultParser.create();
EdmType edmType = null;
EdmFunctionImport functionImport = null;
Map<String, Object> edmPropertyValueMap = null;
List<Map<String, Object>> edmEntityList = null;
Object result = null;
try {
EntityProviderWriteProperties feedProperties = null;
feedProperties = EntityProviderWriteProperties.serviceRoot(
oDataJPAContext.getODataContext().getPathInfo()
.getServiceRoot()).build();
functionImport = resultsView.getFunctionImport();
edmType = functionImport.getReturnType().getType();
if (edmType.getKind().equals(EdmTypeKind.ENTITY)
|| edmType.getKind().equals(EdmTypeKind.COMPLEX)) {
if (functionImport.getReturnType().getMultiplicity()
.equals(EdmMultiplicity.MANY)) {
edmEntityList = new ArrayList<Map<String, Object>>();
for (Object jpaEntity : resultList) {
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(jpaEntity,
(EdmStructuralType) edmType);
edmEntityList.add(edmPropertyValueMap);
}
result = edmEntityList;
} else {
Object resultObject = resultList.get(0);
edmPropertyValueMap = jpaResultParser
.parse2EdmPropertyValueMap(resultObject,
(EdmStructuralType) edmType);
result = edmPropertyValueMap;
}
} else if (edmType.getKind().equals(EdmTypeKind.SIMPLE)) {
result = resultList.get(0);
}
odataResponse = EntityProvider
.writeFunctionImport(contentType,
resultsView.getFunctionImport(), result,
feedProperties);
odataResponse = ODataResponse.fromResponse(odataResponse)
.status(HttpStatusCodes.OK).build();
} catch (EdmException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
} catch (EntityProviderException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
} else
throw new ODataNotFoundException(ODataNotFoundException.COMMON);
return odataResponse;
}
/*
* Method to build the entity provider Property.Callbacks for $expand would
* be registered here
*/
private static EntityProviderWriteProperties getEntityProviderProperties(
ODataJPAContext odataJPAContext, GetEntitySetUriInfo resultsView,
List<Map<String, Object>> edmEntityList)
throws ODataJPARuntimeException {
ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null;
Integer count = resultsView.getInlineCount() == InlineCount.ALLPAGES ? edmEntityList
.size() : null;
try {
entityFeedPropertiesBuilder = EntityProviderWriteProperties
.serviceRoot(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot());
entityFeedPropertiesBuilder.inlineCount(count);
entityFeedPropertiesBuilder.inlineCountType(resultsView
.getInlineCount());
ExpandSelectTreeNode expandSelectTree = UriParser
.createExpandSelectTree(resultsView.getSelect(),
resultsView.getExpand());
entityFeedPropertiesBuilder.callbacks(JPAExpandCallBack
.getCallbacks(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot(), expandSelectTree,
resultsView.getExpand()));
entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree);
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return entityFeedPropertiesBuilder.build();
}
private static EntityProviderWriteProperties getEntityProviderProperties(
ODataJPAContext odataJPAContext, GetEntityUriInfo resultsView)
throws ODataJPARuntimeException {
ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null;
ExpandSelectTreeNode expandSelectTree = null;
try {
entityFeedPropertiesBuilder = EntityProviderWriteProperties
.serviceRoot(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot());
expandSelectTree = UriParser.createExpandSelectTree(
resultsView.getSelect(), resultsView.getExpand());
entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree);
entityFeedPropertiesBuilder.callbacks(JPAExpandCallBack
.getCallbacks(odataJPAContext.getODataContext()
.getPathInfo().getServiceRoot(), expandSelectTree,
resultsView.getExpand()));
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return entityFeedPropertiesBuilder.build();
}
private static List<EdmProperty> buildSelectItemList(
List<SelectItem> selectItems, EdmEntityType entity) throws ODataJPARuntimeException {
boolean flag = false;
List<EdmProperty> selectPropertyList = new ArrayList<EdmProperty>();
try {
for (SelectItem selectItem : selectItems)
selectPropertyList.add(selectItem.getProperty());
for (EdmProperty keyProperty : entity.getKeyProperties()) {
flag = true;
for (SelectItem selectedItem : selectItems) {
if (selectedItem.getProperty().equals(keyProperty)) {
flag = false;
break;
}
}
if (flag == true)
selectPropertyList.add(keyProperty);
}
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
return selectPropertyList;
}
private static List<EdmNavigationProperty> constructListofNavProperty(
List<ArrayList<NavigationPropertySegment>> expandList) {
List<EdmNavigationProperty> navigationPropertyList = new ArrayList<EdmNavigationProperty>();
for (ArrayList<NavigationPropertySegment> navpropSegment : expandList)
navigationPropertyList.add(navpropSegment.get(0)
.getNavigationProperty());
return navigationPropertyList;
}
}
|
package com.futurice.vor.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import static com.futurice.vor.Constants.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class SharedPreferencesManager {
/**
* Saves the jsonObject to SharedPreferences as a string
*
* @param jsonObject the json object
* @param context the context
*/
public static void saveToSharedPreferences(JSONObject jsonObject, Context context) {
if(jsonObject.has(TYPE_KEY)) {
try {
String type = jsonObject.getString(TYPE_KEY);
if (isValidType(type) && jsonObject.has(ID_KEY)) {
String jsonObjectId = jsonObject.getString(ID_KEY);
SharedPreferences sp = context.getSharedPreferences(
jsonObjectId,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(jsonObjectId, jsonObject.toString());
editor.apply();
}
} catch (JSONException jsonException) {
Log.e("JSON Parser", "Error parsing data: " + jsonException.getMessage());
}
}
}
/**
* Checks if a string is of an accepted type
*
* @param type the type
* @return <code>true</code> if it's of a valid type; <code>false</code> otherwise.
*/
private static boolean isValidType(String type) {
String[] types = {LOCATION_KEY, PRINTER_3D_KEY, POOL_KEY, FOOD_KEY, TOILET_KEY, TEST_KEY};
return (Arrays.asList(types).contains(type));
}
}
|
package sophena.math.energetic;
import sophena.model.Fuel;
import sophena.model.FuelConsumption;
import sophena.model.FuelSpec;
import sophena.model.WoodAmountType;
public class CalorificValue {
public static double get(FuelSpec spec) {
if (spec == null || spec.fuel == null)
return 0d;
Fuel fuel = spec.fuel;
if (spec.woodAmountType == null)
return fuel.calorificValue;
// wood fuel
double waterContent = spec.waterContent / 100.0;
double woodMass = woodMass(fuel, spec.woodAmountType, waterContent);
return forWood(woodMass, waterContent, fuel.calorificValue);
}
public static double get(FuelConsumption c) {
if (c == null || c.fuel == null)
return 0;
if (c.woodAmountType == null) {
return c.fuel.calorificValue;
}
// wood fuel
double waterContent = c.waterContent / 100;
double woodMass = woodMass(c.fuel, c.woodAmountType, waterContent);
return forWood(woodMass, waterContent, c.fuel.calorificValue);
}
static double forWood(double woodMass, double waterContent,
double calorificValue) {
return woodMass
* ((1 - waterContent) * calorificValue - waterContent * 680);
}
/**
* Calculates the real (wet) wood mass that goes into the calculation of a
* calorific value for a wood fuel.
*/
static double woodMass(Fuel woodFuel, WoodAmountType type,
double waterContent) {
if (woodFuel == null || waterContent >= 1.0) {
return 0.0;
}
if (type == WoodAmountType.MASS)
return 1 / (1 - waterContent);
double f = 1.0; // mass
if (type == WoodAmountType.CHIPS) {
f = 0.4;
} else if (type == WoodAmountType.LOGS) {
f = 0.7;
}
return (f * woodFuel.density / 1000) / (1 - waterContent);
}
}
|
package com.google.account;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.SessionCookieOptions;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.concurrent.TimeUnit;
/** Util methods related to firebase auth session cookies. */
public final class FirebaseAuthSessionCookieUtil {
private static final String ID_TOKEN_PARAM = "idToken";
private static final String LOG_IN_PAGE_PATH = "/log-in/index.html";
private FirebaseAuthSessionCookieUtil() {};
/**
* Creates the session cookies. It is evoked when the user signs in.
*
* @param request Log in request.
* @return Response with session cookie.
*/
@POST
@Path("/business-log-in")
@Consumes("application/json")
public static Response createSessionCookie(HttpServletRequest request) {
try {
// Gets the ID token sent by the client
String idToken = getIDToken(request);
// Sets session expiration to 5 days
long expiresIn = TimeUnit.DAYS.toMillis(/* duration= */5);
SessionCookieOptions options = SessionCookieOptions.builder().setExpiresIn(expiresIn).build();
// Creates the session cookie. This will also verify the ID token in the process.
// The session cookie will have the same claims as the ID token.
String sessionCookie = FirebaseAuth.getInstance().createSessionCookieAsync(idToken, options).get();
// Sets cookie policy parameters as required
NewCookie cookie = new NewCookie(/* name= */ "session", sessionCookie);
return Response.ok().cookie(cookie).build();
} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).entity("Failed to create a session cookie").build();
}
}
/**
* Verifies session cookies.
*
* @param cookie Session cookie.
* @return Response with uid of the current user account.
*/
@POST
@Path("/profile")
public static Response verifySessionCookie(@CookieParam("session") Cookie cookie) {
String sessionCookie = cookie.getValue();
try {
// Verify the session cookie. In this case an additional check is added to detect
// if the user's Firebase session was revoked, user deleted/disabled, etc.
final boolean checkRevoked = true;
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(sessionCookie, checkRevoked);
return getUid(decodedToken);
} catch (FirebaseAuthException e) {
// Session cookie is unavailable, invalid or revoked. Force user to login.
return Response.temporaryRedirect(URI.create(LOG_IN_PAGE_PATH)).build();
}
}
/**
* Clears the session cookie when the user signs out at the client side.
*
* @param cookie Session cookie
* @return Response to direct to log in page.
*/
@POST
@Path("/business-log-out")
public static Response clearSessionCookie(@CookieParam("session") Cookie cookie) {
final int maxAge = 0;
NewCookie newCookie = new NewCookie(cookie, /* comment= */ null, maxAge, /* secure= */ true);
return Response.temporaryRedirect(URI.create(LOG_IN_PAGE_PATH)).cookie(newCookie).build();
}
private static String getIDToken(HttpServletRequest request) throws IllegalArgumentException {
String idToken = request.getParameter(ID_TOKEN_PARAM).trim();
if (idToken == null || idToken.isEmpty()) {
throw new IllegalArgumentException("ID Token should be an non-empty string");
}
return idToken;
}
private static Response getUid(FirebaseToken decodedToken) {
String uid = decodedToken.getUid();
return Response.ok(uid).build();
}
}
|
package com.google.account;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.SessionCookieOptions;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
/** Util methods related to firebase auth session cookies. */
public final class FirebaseAuthSessionCookieUtil {
private static final String ID_TOKEN_PARAM = "idToken";
private static final String LOG_IN_PAGE_PATH = "/log-in/index.html";
public FirebaseAuthSessionCookieUtil() throws IOException {
initAdminSDK();
}
/**
* Creates the session cookies. It is evoked when the user signs in.
*
* @param request Log in request.
* @return Response with session cookie.
*/
@POST
@Path("/business-log-in")
@Consumes("application/json")
public Response createSessionCookie(HttpServletRequest request) {
try {
// Gets the ID token sent by the client
String idToken = getIDToken(request);
// Sets session expiration to 5 days
long expiresIn = TimeUnit.DAYS.toMillis(/* duration= */5);
SessionCookieOptions options = SessionCookieOptions.builder().setExpiresIn(expiresIn).build();
// Creates the session cookie. This will also verify the ID token in the process.
// The session cookie will have the same claims as the ID token.
String sessionCookie = FirebaseAuth.getInstance().createSessionCookieAsync(idToken, options).get();
// Sets cookie policy parameters as required
NewCookie cookie = new NewCookie(/* name= */ "session", sessionCookie);
return Response.ok().cookie(cookie).build();
} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).entity("Failed to create a session cookie").build();
}
}
/**
* Verifies session cookies.
*
* @param cookie Session cookie.
* @return Response with uid of the current user account.
*/
@POST
@Path("/profile")
public Response verifySessionCookie(@CookieParam("session") Cookie cookie) {
String sessionCookie = cookie.getValue();
try {
// Verify the session cookie. In this case an additional check is added to detect
// if the user's Firebase session was revoked, user deleted/disabled, etc.
final boolean checkRevoked = true;
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(sessionCookie, checkRevoked);
return getUid(decodedToken);
} catch (FirebaseAuthException e) {
// Session cookie is unavailable, invalid or revoked. Force user to login.
return Response.temporaryRedirect(URI.create(LOG_IN_PAGE_PATH)).build();
}
}
/**
* Clears the session cookie when the user signs out at the client side.
*
* @param cookie Session cookie
* @return Response to direct to log in page.
*/
@POST
@Path("/business-log-out")
public static Response clearSessionCookie(@CookieParam("session") Cookie cookie) {
final int maxAge = 0;
NewCookie newCookie = new NewCookie(cookie, /* comment= */ null, maxAge, /* secure= */ true);
return Response.temporaryRedirect(URI.create(LOG_IN_PAGE_PATH)).cookie(newCookie).build();
}
/** Initializes the admin SDK. */
private void initAdminSDK() throws IOException {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.setDatabaseUrl("https://com-walk-in-interview.firebaseio.com/")
.setProjectId("com-walk-in-interview")
.build();
FirebaseApp.initializeApp(options);
}
/** Gets the id token from the log in request. */
private String getIDToken(HttpServletRequest request) throws IllegalArgumentException {
String idToken = request.getParameter(ID_TOKEN_PARAM).trim();
if (idToken == null || idToken.isEmpty()) {
throw new IllegalArgumentException("ID Token should be an non-empty string");
}
return idToken;
}
/** Gets the uid the of the current account. */
private Response getUid(FirebaseToken decodedToken) {
String uid = decodedToken.getUid();
return Response.ok(uid).build();
}
}
|
package org.phenotips.ontology.internal.solr;
import org.phenotips.ontology.OntologyService;
import org.phenotips.ontology.OntologyTerm;
import org.phenotips.ontology.SolrOntologyServiceInitializer;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.slf4j.Logger;
/**
* Provides access to the Solr server, with the main purpose of providing access to an indexed ontology. There are two
* ways of accessing items in the ontology: getting a single term by its identifier, or searching for terms matching a
* given query in the Lucene query language.
*
* @version $Id$
* @since 1.0M8
*/
public abstract class AbstractSolrOntologyService implements OntologyService, Initializable
{
/** The name of the ID field. */
protected static final String ID_FIELD_NAME = "id";
/**
* Object used to mark in the cache that a term doesn't exist, since null means that the cache doesn't contain the
* requested entry.
*/
private static final OntologyTerm EMPTY_MARKER = new SolrOntologyTerm(null, null);
/** Logging helper object. */
@Inject
protected Logger logger;
/** The object used for initializing server connection and cache. */
@Inject
protected SolrOntologyServiceInitializer externalServicesAccess;
@Override
public void initialize() throws InitializationException
{
this.externalServicesAccess.initialize(this.getName());
}
// Dilemma:
// In an ideal world there should be a getter methods for server and cache instances.
// However the point of splitting up the server was to lessen the number of imports
/**
* Get the name of the Solr "core" to be used by this service instance.
*
* @return the simple core name
*/
protected abstract String getName();
@Override
public OntologyTerm getTerm(String id)
{
OntologyTerm result = this.externalServicesAccess.getCache().get(id);
if (result == null) {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(CommonParams.Q, ID_FIELD_NAME + ':' + ClientUtils.escapeQueryChars(id));
SolrDocumentList allResults = this.search(params);
if (allResults != null && !allResults.isEmpty()) {
result = new SolrOntologyTerm(allResults.get(0), this);
this.externalServicesAccess.getCache().set(id, result);
} else {
this.externalServicesAccess.getCache().set(id, EMPTY_MARKER);
}
}
return (result == EMPTY_MARKER) ? null : result;
}
@Override
public Set<OntologyTerm> getTerms(Collection<String> ids)
{
Set<OntologyTerm> result = new LinkedHashSet<OntologyTerm>();
StringBuilder query = new StringBuilder("id:(");
for (String id : ids) {
OntologyTerm cachedTerm = this.externalServicesAccess.getCache().get(id);
if (cachedTerm != null) {
if (cachedTerm != EMPTY_MARKER) {
result.add(cachedTerm);
}
} else {
query.append(ClientUtils.escapeQueryChars(id));
query.append(' ');
}
}
query.append(')');
// There's at least one more term not found in the cache
if (query.length() > 5) {
for (SolrDocument doc : this.search(SolrQueryUtils.transformQueryToSolrParams(query.toString()))) {
result.add(new SolrOntologyTerm(doc, this));
}
}
return result;
}
@Override
public Set<OntologyTerm> search(Map<String, ?> fieldValues)
{
return search(fieldValues, null);
}
@Override
public Set<OntologyTerm> search(Map<String, ?> fieldValues, Map<String, String> queryOptions)
{
Set<OntologyTerm> result = new LinkedHashSet<OntologyTerm>();
for (SolrDocument doc : this
.search(SolrQueryUtils.transformQueryToSolrParams(generateLuceneQuery(fieldValues)), queryOptions)) {
result.add(new SolrOntologyTerm(doc, this));
}
return result;
}
@Override
public long count(Map<String, ?> fieldValues)
{
return count(this.generateLuceneQuery(fieldValues));
}
@Override
public long size()
{
return count("*:*");
}
@Override
public int reindex(String ontologyUrl)
{
// FIXME Not implemented yet
throw new UnsupportedOperationException();
}
@Override
public String getVersion()
{
return null;
}
@Override
public long getDistance(String fromTermId, String toTermId)
{
return getDistance(getTerm(fromTermId), getTerm(toTermId));
}
@Override
public long getDistance(OntologyTerm fromTerm, OntologyTerm toTerm)
{
if (fromTerm == null || toTerm == null) {
return -1;
}
return fromTerm.getDistanceTo(toTerm);
}
/**
* Perform a search, falling back on the suggested spellchecked query if the original query fails to return any
* results.
*
* @param params the Solr parameters to use, should contain at least a value for the "q" parameter
* @return the list of matching documents, empty if there are no matching terms
*/
protected SolrDocumentList search(SolrParams params)
{
return search(params, null);
}
/**
* Perform a search, falling back on the suggested spellchecked query if the original query fails to return any
* results.
*
* @param params the Solr parameters to use, should contain at least a value for the "q" parameter
* @param queryOptions extra options to include in the query; these override the default values, but don't override
* values already set in the query
* @return the list of matching documents, empty if there are no matching terms
*/
protected SolrDocumentList search(SolrParams params, Map<String, String> queryOptions)
{
try {
SolrParams enhancedParams = SolrQueryUtils.enhanceParams(params, queryOptions);
this.logger.debug("Searching [{}] with query [{}]", getName(), enhancedParams);
QueryResponse response = this.externalServicesAccess.getServer().query(enhancedParams);
SolrDocumentList results = response.getResults();
if (response.getSpellCheckResponse() != null && !response.getSpellCheckResponse().isCorrectlySpelled()
&& StringUtils.isNotEmpty(response.getSpellCheckResponse().getCollatedResult())) {
enhancedParams =
SolrQueryUtils.applySpellcheckSuggestion(enhancedParams, response.getSpellCheckResponse()
.getCollatedResult());
this.logger.debug("Searching [{}] with spellchecked query [{}]", getName(), enhancedParams);
SolrDocumentList spellcheckResults =
this.externalServicesAccess.getServer().query(enhancedParams).getResults();
if (results.getMaxScore() < spellcheckResults.getMaxScore()) {
results = spellcheckResults;
}
}
return results;
} catch (Exception ex) {
this.logger.error("Failed to search: {}", ex.getMessage(), ex);
}
return null;
}
/**
* Get the number of entries that match a specific Lucene query.
*
* @param query a valid the Lucene query as string
* @return the number of entries matching the query
*/
protected long count(String query)
{
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(CommonParams.Q, query);
params.set(CommonParams.START, "0");
params.set(CommonParams.ROWS, "0");
SolrDocumentList results;
try {
this.logger.debug("Counting terms matching [{}] in [{}]", query, getName());
results = this.externalServicesAccess.getServer().query(params).getResults();
return results.getNumFound();
} catch (Exception ex) {
this.logger.error("Failed to count ontology terms: {}", ex.getMessage(), ex);
return 0;
}
}
/**
* Generate a Lucene query from a map of parameters, to be used in the "q" parameter for Solr.
*
* @param fieldValues a map with term meta-property values that must be matched by the returned terms; the keys are
* property names, like {@code id}, {@code description}, {@code is_a}, and the values can be either a
* single value, or a collection of values that can (OR) be matched by the term;
* @return the String representation of the equivalent Lucene query
*/
protected String generateLuceneQuery(Map<String, ?> fieldValues)
{
StringBuilder query = new StringBuilder();
for (Map.Entry<String, ?> field : fieldValues.entrySet()) {
if (Collection.class.isInstance(field.getValue()) && ((Collection<?>) field.getValue()).isEmpty()) {
continue;
}
query.append("+");
query.append(ClientUtils.escapeQueryChars(field.getKey()));
query.append(":(");
if (Collection.class.isInstance(field.getValue())) {
for (Object value : (Collection<?>) field.getValue()) {
query.append(ClientUtils.escapeQueryChars(String.valueOf(value)));
query.append(' ');
}
} else {
String value = String.valueOf(field.getValue());
if ("*".equals(value)) {
query.append(value);
} else {
query.append(ClientUtils.escapeQueryChars(value));
}
}
query.append(')');
}
return query.toString();
}
@Override
public Set<OntologyTerm> termSuggest(String query, Integer rows, String sort, String customFq)
{
throw new UnsupportedOperationException();
}
}
|
/* SyntaxTreeBuilderTokenManager.java */
/* Generated By:JJTree&JavaCC: Do not edit this line. SyntaxTreeBuilderTokenManager.java */
package org.eclipse.rdf4j.query.parser.sparql.ast;
/** Token Manager. */
@SuppressWarnings("unused")
public class SyntaxTreeBuilderTokenManager implements SyntaxTreeBuilderConstants {
/** Debug output. */
public java.io.PrintStream debugStream = System.out;
/** Set debug output. */
public void setDebugStream(java.io.PrintStream ds) {
debugStream = ds;
}
private int jjStopAtPos(int pos, int kind) {
jjmatchedKind = kind;
jjmatchedPos = pos;
return pos + 1;
}
private int jjMoveStringLiteralDfa0_0() {
switch (curChar) {
case 33:
jjmatchedKind = 19;
return jjMoveStringLiteralDfa1_0(0x4000L, 0x0L, 0x0L);
case 38:
return jjMoveStringLiteralDfa1_0(0x200000L, 0x0L, 0x0L);
case 40:
jjmatchedKind = 4;
return jjMoveNfa_0(0);
case 41:
jjmatchedKind = 5;
return jjMoveNfa_0(0);
case 42:
jjmatchedKind = 24;
return jjMoveNfa_0(0);
case 43:
jjmatchedKind = 22;
return jjMoveNfa_0(0);
case 44:
jjmatchedKind = 11;
return jjMoveNfa_0(0);
case 45:
jjmatchedKind = 23;
return jjMoveNfa_0(0);
case 46:
jjmatchedKind = 12;
return jjMoveNfa_0(0);
case 47:
jjmatchedKind = 26;
return jjMoveNfa_0(0);
case 59:
jjmatchedKind = 10;
return jjMoveNfa_0(0);
case 60:
jjmatchedKind = 16;
return jjMoveStringLiteralDfa1_0(0x20000L, 0x0L, 0x400000000000000L);
case 61:
jjmatchedKind = 13;
return jjMoveNfa_0(0);
case 62:
jjmatchedKind = 15;
return jjMoveStringLiteralDfa1_0(0x40000L, 0x0L, 0x800000000000000L);
case 63:
jjmatchedKind = 25;
return jjMoveNfa_0(0);
case 65:
return jjMoveStringLiteralDfa1_0(0x1024000000000L, 0x100000080000L, 0x1004L);
case 66:
case 98:
return jjMoveStringLiteralDfa1_0(0x800200000000L, 0x14000081L, 0x0L);
case 67:
case 99:
return jjMoveStringLiteralDfa1_0(0x1000000000L, 0x230000008040L, 0x31L);
case 68:
case 100:
return jjMoveStringLiteralDfa1_0(0x800200a000000000L, 0x8000000000000L, 0x982L);
case 69:
return jjMoveStringLiteralDfa1_0(0x800000000000000L, 0x40000000000L, 0x0L);
case 70:
return jjMoveStringLiteralDfa1_0(0x100040000000000L, 0x400002000000L, 0x0L);
case 71:
return jjMoveStringLiteralDfa1_0(0x20400000000000L, 0x200000L, 0x0L);
case 72:
return jjMoveStringLiteralDfa1_0(0x200000000000000L, 0x10000000000000L, 0x0L);
case 73:
return jjMoveStringLiteralDfa1_0(0x0L, 0x6038L, 0x2040L);
case 76:
return jjMoveStringLiteralDfa1_0(0x6004000000000000L, 0x8000008000000000L, 0x0L);
case 77:
return jjMoveStringLiteralDfa1_0(0x80000000000000L, 0x224000000060000L, 0x8L);
case 78:
return jjMoveStringLiteralDfa1_0(0x400080000000000L, 0x1000000000000L, 0x0L);
case 79:
return jjMoveStringLiteralDfa1_0(0x18200000000000L, 0x0L, 0x0L);
case 80:
return jjMoveStringLiteralDfa1_0(0x400000000L, 0x0L, 0x0L);
case 82:
return jjMoveStringLiteralDfa1_0(0x10000000000L, 0x882000800000L, 0x0L);
case 83:
return jjMoveStringLiteralDfa1_0(0x1000000800000000L, 0x7c40001f88510b02L, 0x400L);
case 84:
return jjMoveStringLiteralDfa1_0(0x0L, 0x180000001000000L, 0x4000L);
case 85:
return jjMoveStringLiteralDfa1_0(0x40000000000000L, 0x4040000400L, 0x8000L);
case 86:
return jjMoveStringLiteralDfa1_0(0x0L, 0x20000000L, 0x0L);
case 87:
return jjMoveStringLiteralDfa1_0(0x100000000000L, 0x0L, 0x200L);
case 89:
return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000000000L, 0x0L);
case 91:
jjmatchedKind = 8;
return jjMoveNfa_0(0);
case 93:
jjmatchedKind = 9;
return jjMoveNfa_0(0);
case 94:
jjmatchedKind = 28;
return jjMoveStringLiteralDfa1_0(0x20000000L, 0x0L, 0x0L);
case 97:
jjmatchedKind = 32;
return jjMoveStringLiteralDfa1_0(0x1024000000000L, 0x100000080000L, 0x1004L);
case 101:
return jjMoveStringLiteralDfa1_0(0x800000000000000L, 0x40000000000L, 0x0L);
case 102:
return jjMoveStringLiteralDfa1_0(0x100040000000000L, 0x400002000000L, 0x0L);
case 103:
return jjMoveStringLiteralDfa1_0(0x20400000000000L, 0x200000L, 0x0L);
case 104:
return jjMoveStringLiteralDfa1_0(0x200000000000000L, 0x10000000000000L, 0x0L);
case 105:
return jjMoveStringLiteralDfa1_0(0x0L, 0x6038L, 0x2040L);
case 108:
return jjMoveStringLiteralDfa1_0(0x6004000000000000L, 0x8000008000000000L, 0x0L);
case 109:
return jjMoveStringLiteralDfa1_0(0x80000000000000L, 0x224000000060000L, 0x8L);
case 110:
return jjMoveStringLiteralDfa1_0(0x400080000000000L, 0x1000000000000L, 0x0L);
case 111:
return jjMoveStringLiteralDfa1_0(0x18200000000000L, 0x0L, 0x0L);
case 112:
return jjMoveStringLiteralDfa1_0(0x400000000L, 0x0L, 0x0L);
case 114:
return jjMoveStringLiteralDfa1_0(0x10000000000L, 0x882000800000L, 0x0L);
case 115:
return jjMoveStringLiteralDfa1_0(0x1000000800000000L, 0x7c40001f88510b02L, 0x400L);
case 116:
return jjMoveStringLiteralDfa1_0(0x0L, 0x180000001000000L, 0x4000L);
case 117:
return jjMoveStringLiteralDfa1_0(0x40000000000000L, 0x4040000400L, 0x8000L);
case 118:
return jjMoveStringLiteralDfa1_0(0x0L, 0x20000000L, 0x0L);
case 119:
return jjMoveStringLiteralDfa1_0(0x100000000000L, 0x0L, 0x200L);
case 121:
return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000000000L, 0x0L);
case 123:
jjmatchedKind = 6;
return jjMoveNfa_0(0);
case 124:
jjmatchedKind = 27;
return jjMoveStringLiteralDfa1_0(0x100000L, 0x0L, 0x0L);
case 125:
jjmatchedKind = 7;
return jjMoveNfa_0(0);
default:
return jjMoveNfa_0(0);
}
}
private int jjMoveStringLiteralDfa1_0(long active0, long active1, long active2) {
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(0);
}
switch (curChar) {
case 38:
if ((active0 & 0x200000L) != 0L) {
jjmatchedKind = 21;
jjmatchedPos = 1;
}
break;
case 60:
if ((active2 & 0x400000000000000L) != 0L) {
jjmatchedKind = 186;
jjmatchedPos = 1;
}
break;
case 61:
if ((active0 & 0x4000L) != 0L) {
jjmatchedKind = 14;
jjmatchedPos = 1;
} else if ((active0 & 0x20000L) != 0L) {
jjmatchedKind = 17;
jjmatchedPos = 1;
} else if ((active0 & 0x40000L) != 0L) {
jjmatchedKind = 18;
jjmatchedPos = 1;
}
break;
case 62:
if ((active2 & 0x800000000000000L) != 0L) {
jjmatchedKind = 187;
jjmatchedPos = 1;
}
break;
case 65:
case 97:
return jjMoveStringLiteralDfa2_0(active0, 0xe200080200000000L, active1, 0x8080022140002L, active2, 0x80L);
case 66:
case 98:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x100000000000L, active2, 0L);
case 67:
case 99:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0xc000000000L, active2, 0L);
case 68:
case 100:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x200000000000000L, active2, 0x4L);
case 69:
case 101:
return jjMoveStringLiteralDfa2_0(active0, 0x2012800000000L, active1, 0x42202008c00000L, active2, 0x900L);
case 70:
case 102:
if ((active1 & 0x2000L) != 0L) {
jjmatchedKind = 77;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0x8000000000000L, active1, 0L, active2, 0L);
case 72:
case 104:
return jjMoveStringLiteralDfa2_0(active0, 0x100000000000L, active1, 0x7c00000000000000L, active2, 0L);
case 73:
case 105:
return jjMoveStringLiteralDfa2_0(active0, 0x184008000000000L, active1, 0xa0000014020000L, active2, 0x600L);
case 76:
case 108:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x400000000000L, active2, 0x1001L);
case 78:
case 110:
if ((active1 & 0x4000L) != 0L) {
jjmatchedKind = 78;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0x40000000000000L, active1, 0x40040000080L, active2, 0x2040L);
case 79:
case 111:
if ((active2 & 0x4000L) != 0L) {
jjmatchedKind = 142;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0x400001000000000L, active1, 0x8015830000008041L, active2, 0x18L);
case 80:
case 112:
return jjMoveStringLiteralDfa2_0(active0, 0x10000000000000L, active1, 0L, active2, 0L);
case 82:
case 114:
return jjMoveStringLiteralDfa2_0(active0, 0x20640400000000L, active1, 0x1200000L, active2, 0x22L);
case 83:
case 115:
if ((active0 & 0x20000000000L) != 0L) {
jjmatchedKind = 41;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0x1004000000000L, active1, 0x38L, active2, 0x8000L);
case 84:
case 116:
return jjMoveStringLiteralDfa2_0(active0, 0x1000000000000000L, active1, 0x1e80000b00L, active2, 0L);
case 85:
case 117:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x100010400L, active2, 0L);
case 86:
case 118:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x80000L, active2, 0L);
case 88:
case 120:
return jjMoveStringLiteralDfa2_0(active0, 0x800000000000000L, active1, 0L, active2, 0L);
case 89:
case 121:
if ((active0 & 0x800000000000L) != 0L) {
jjmatchedKind = 47;
jjmatchedPos = 1;
}
break;
case 90:
case 122:
if ((active1 & 0x100000000000000L) != 0L) {
jjmatchedKind = 120;
jjmatchedPos = 1;
}
break;
case 94:
if ((active0 & 0x20000000L) != 0L) {
jjmatchedKind = 29;
jjmatchedPos = 1;
}
break;
case 124:
if ((active0 & 0x100000L) != 0L) {
jjmatchedKind = 20;
jjmatchedPos = 1;
}
break;
default:
break;
}
return jjMoveNfa_0(1);
}
private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L)
return jjMoveNfa_0(1);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(1);
}
switch (curChar) {
case 53:
if ((active1 & 0x200000000000000L) != 0L) {
jjmatchedKind = 121;
jjmatchedPos = 2;
}
break;
case 65:
case 97:
return jjMoveStringLiteralDfa3_0(active0, 0x20000000000000L, active1, 0xfc0200c000000040L, active2, 0L);
case 66:
case 98:
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x100000008L, active2, 0L);
case 67:
case 99:
if ((active0 & 0x1000000000000L) != 0L) {
jjmatchedKind = 48;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x40040000000000L, active2, 0L);
case 68:
case 100:
if ((active2 & 0x4L) != 0L) {
jjmatchedKind = 130;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x210000000000L, active1, 0x40000000L, active2, 0L);
case 69:
case 101:
return jjMoveStringLiteralDfa3_0(active0, 0x100400000000L, active1, 0L, active2, 0x21L);
case 70:
case 102:
return jjMoveStringLiteralDfa3_0(active0, 0x8000000000000L, active1, 0L, active2, 0x800L);
case 71:
case 103:
if ((active1 & 0x80000L) != 0L) {
jjmatchedKind = 83;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x800000L, active2, 0L);
case 73:
case 105:
return jjMoveStringLiteralDfa3_0(active0, 0x840000000000000L, active1, 0x200000000400L, active2, 0x8000L);
case 75:
case 107:
if ((active0 & 0x4000000000L) != 0L) {
jjmatchedKind = 38;
jjmatchedPos = 2;
}
break;
case 76:
case 108:
if ((active2 & 0x1000L) != 0L) {
jjmatchedKind = 140;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x100000800000000L, active1, 0x22000010L, active2, 0x500L);
case 77:
case 109:
if ((active1 & 0x10000L) != 0L) {
jjmatchedKind = 80;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x4080000000000L, active1, 0x80000000100002L, active2, 0L);
case 78:
case 110:
if ((active1 & 0x20000L) != 0L) {
jjmatchedKind = 81;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x6080001000000000L, active1, 0x240b0014000020L, active2, 0L);
case 79:
case 111:
return jjMoveStringLiteralDfa3_0(active0, 0x440000000000L, active1, 0x400000200080L, active2, 0x2L);
case 80:
case 112:
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x2000400000L, active2, 0x10L);
case 82:
case 114:
if ((active0 & 0x1000000000000000L) != 0L) {
jjmatchedKind = 60;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x1e88000b00L, active2, 0L);
case 83:
case 115:
if ((active1 & 0x100000000000L) != 0L) {
jjmatchedKind = 108;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x200a200000000L, active1, 0L, active2, 0x40L);
case 84:
case 116:
if ((active0 & 0x400000000000000L) != 0L) {
jjmatchedKind = 58;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x8010000000000000L, active1, 0L, active2, 0x2280L);
case 85:
case 117:
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x10800001008001L, active2, 0L);
case 86:
case 118:
return jjMoveStringLiteralDfa3_0(active0, 0x200000000000000L, active1, 0L, active2, 0x8L);
case 87:
case 119:
if ((active1 & 0x1000000000000L) != 0L) {
jjmatchedKind = 112;
jjmatchedPos = 2;
}
break;
case 88:
case 120:
if ((active1 & 0x40000L) != 0L) {
jjmatchedKind = 82;
jjmatchedPos = 2;
}
break;
case 89:
case 121:
if ((active1 & 0x8000000000000L) != 0L) {
jjmatchedKind = 115;
jjmatchedPos = 2;
}
break;
default:
break;
}
return jjMoveNfa_0(2);
}
private int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L)
return jjMoveNfa_0(2);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(2);
}
switch (curChar) {
case 49:
if ((active1 & 0x400000000000000L) != 0L) {
jjmatchedKind = 122;
jjmatchedPos = 3;
}
break;
case 50:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x1800000000000000L, active2, 0L);
case 51:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x2000000000000000L, active2, 0L);
case 53:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x4000000000000000L, active2, 0L);
case 65:
case 97:
if ((active2 & 0x80L) != 0L) {
jjmatchedKind = 135;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x8000000000000000L, active1, 0x1000400000L, active2, 0x821L);
case 66:
case 98:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x800000000L, active2, 0L);
case 67:
case 99:
if ((active0 & 0x2000000000000L) != 0L) {
jjmatchedKind = 49;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L, active1, 0x10000000000L, active2, 0L);
case 68:
case 100:
if ((active1 & 0x400L) != 0L) {
jjmatchedKind = 74;
jjmatchedPos = 3;
} else if ((active1 & 0x4000000L) != 0L) {
jjmatchedKind = 90;
jjmatchedPos = 3;
} else if ((active1 & 0x80000000000L) != 0L) {
jjmatchedKind = 107;
jjmatchedPos = 3;
} else if ((active1 & 0x8000000000000000L) != 0L) {
jjmatchedKind = 127;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x10000180L, active2, 0L);
case 69:
case 101:
if ((active0 & 0x200000000L) != 0L) {
jjmatchedKind = 33;
jjmatchedPos = 3;
} else if ((active1 & 0x1000000L) != 0L) {
jjmatchedKind = 88;
jjmatchedPos = 3;
} else if ((active2 & 0x8L) != 0L) {
jjmatchedKind = 131;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x280800000000L, active1, 0x80000440800002L, active2, 0x540L);
case 70:
case 102:
return jjMoveStringLiteralDfa4_0(active0, 0x400000000L, active1, 0L, active2, 0L);
case 71:
case 103:
if ((active0 & 0x2000000000000000L) != 0L) {
jjmatchedKind = 61;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x4000000000000000L, active1, 0L, active2, 0L);
case 72:
case 104:
if ((active2 & 0x200L) != 0L) {
jjmatchedKind = 137;
jjmatchedPos = 3;
}
break;
case 73:
case 105:
return jjMoveStringLiteralDfa4_0(active0, 0x214000000000000L, active1, 0x10L, active2, 0L);
case 76:
case 108:
if ((active1 & 0x200000000000L) != 0L) {
jjmatchedKind = 109;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x2080000248L, active2, 0L);
case 77:
case 109:
if ((active0 & 0x40000000000L) != 0L) {
jjmatchedKind = 42;
jjmatchedPos = 3;
}
break;
case 78:
case 110:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x800000008001L, active2, 0x8000L);
case 79:
case 111:
if ((active2 & 0x2000L) != 0L) {
jjmatchedKind = 141;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x40000000000000L, active1, 0x40440000000000L, active2, 0L);
case 80:
case 112:
if ((active2 & 0x2L) != 0L) {
jjmatchedKind = 129;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x20000000000000L, active1, 0x100000L, active2, 0L);
case 82:
case 114:
if ((active1 & 0x2000000000000L) != 0L) {
jjmatchedKind = 113;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0x100000000000L, active1, 0x10000000000000L, active2, 0L);
case 83:
case 115:
return jjMoveStringLiteralDfa4_0(active0, 0x808001000000000L, active1, 0xc302000000L, active2, 0L);
case 84:
case 116:
return jjMoveStringLiteralDfa4_0(active0, 0x100008000000000L, active1, 0x4020000000000L, active2, 0L);
case 85:
case 117:
return jjMoveStringLiteralDfa4_0(active0, 0x80410000000000L, active1, 0x20000020200820L, active2, 0L);
case 86:
case 118:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x8000000L, active2, 0L);
case 89:
case 121:
if ((active2 & 0x10L) != 0L) {
jjmatchedKind = 132;
jjmatchedPos = 3;
}
break;
default:
break;
}
return jjMoveNfa_0(3);
}
private int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L)
return jjMoveNfa_0(3);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(3);
}
switch (curChar) {
case 49:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x4000000000000000L, active2, 0L);
case 50:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x800000000000000L, active2, 0L);
case 53:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x1000000000000000L, active2, 0L);
case 56:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x2000000000000000L, active2, 0L);
case 65:
case 97:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x32000000208L, active2, 0L);
case 67:
case 99:
return jjMoveStringLiteralDfa5_0(active0, 0x10800000000L, active1, 0L, active2, 0L);
case 68:
case 100:
if ((active0 & 0x80000000000L) != 0L) {
jjmatchedKind = 43;
jjmatchedPos = 4;
} else if ((active1 & 0x1L) != 0L) {
jjmatchedKind = 64;
jjmatchedPos = 4;
} else if ((active1 & 0x800000000000L) != 0L) {
jjmatchedKind = 111;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x40000000000L, active2, 0L);
case 69:
case 101:
if ((active0 & 0x100000000000L) != 0L) {
jjmatchedKind = 44;
jjmatchedPos = 4;
} else if ((active1 & 0x80L) != 0L) {
jjmatchedKind = 71;
jjmatchedPos = 4;
} else if ((active1 & 0x2000000L) != 0L) {
jjmatchedKind = 89;
jjmatchedPos = 4;
} else if ((active1 & 0x4000000000L) != 0L) {
jjmatchedKind = 102;
jjmatchedPos = 4;
} else if ((active1 & 0x8000000000L) != 0L) {
jjmatchedKind = 103;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x108000000000000L, active1, 0x8a0000040L, active2, 0L);
case 70:
case 102:
if ((active1 & 0x40000000L) != 0L) {
jjmatchedKind = 94;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x1000000000L, active2, 0L);
case 71:
case 103:
if ((active2 & 0x8000L) != 0L) {
jjmatchedKind = 143;
jjmatchedPos = 4;
}
break;
case 72:
case 104:
if ((active0 & 0x20000000000000L) != 0L) {
jjmatchedKind = 53;
jjmatchedPos = 4;
} else if ((active1 & 0x4000000000000L) != 0L) {
jjmatchedKind = 114;
jjmatchedPos = 4;
}
break;
case 73:
case 105:
return jjMoveStringLiteralDfa5_0(active0, 0x8400000000L, active1, 0x18000000L, active2, 0L);
case 76:
case 108:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x100000L, active2, 0L);
case 77:
case 109:
return jjMoveStringLiteralDfa5_0(active0, 0x4000000000000000L, active1, 0x20L, active2, 0L);
case 78:
case 110:
if ((active0 & 0x40000000000000L) != 0L) {
jjmatchedKind = 54;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x200000000000000L, active1, 0x40000400000000L, active2, 0x400L);
case 79:
case 111:
return jjMoveStringLiteralDfa5_0(active0, 0x10000000000000L, active1, 0L, active2, 0L);
case 80:
case 112:
if ((active0 & 0x400000000000L) != 0L) {
jjmatchedKind = 46;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x200000L, active2, 0L);
case 82:
case 114:
if ((active0 & 0x200000000000L) != 0L) {
jjmatchedKind = 45;
jjmatchedPos = 4;
} else if ((active1 & 0x400000000000L) != 0L) {
jjmatchedKind = 110;
jjmatchedPos = 4;
} else if ((active2 & 0x1L) != 0L) {
jjmatchedKind = 128;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x2000000000L, active1, 0x400000L, active2, 0x40L);
case 83:
case 115:
if ((active0 & 0x80000000000000L) != 0L) {
jjmatchedKind = 55;
jjmatchedPos = 4;
} else if ((active1 & 0x10000000000000L) != 0L) {
jjmatchedKind = 116;
jjmatchedPos = 4;
}
break;
case 84:
case 116:
if ((active0 & 0x4000000000000L) != 0L) {
jjmatchedKind = 50;
jjmatchedPos = 4;
} else if ((active1 & 0x100L) != 0L) {
jjmatchedKind = 72;
jjmatchedPos = 4;
} else if ((active1 & 0x8000L) != 0L) {
jjmatchedKind = 79;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x8800001000000000L, active1, 0x20000300000012L, active2, 0x120L);
case 85:
case 117:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x800L, active2, 0x800L);
case 88:
case 120:
if ((active1 & 0x800000L) != 0L) {
jjmatchedKind = 87;
jjmatchedPos = 4;
}
break;
case 90:
case 122:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x80000000000000L, active2, 0L);
default:
break;
}
return jjMoveNfa_0(4);
}
private int jjMoveStringLiteralDfa5_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L)
return jjMoveNfa_0(4);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(4);
}
switch (curChar) {
case 50:
if ((active1 & 0x4000000000000000L) != 0L) {
jjmatchedKind = 126;
jjmatchedPos = 5;
}
break;
case 52:
if ((active1 & 0x800000000000000L) != 0L) {
jjmatchedKind = 123;
jjmatchedPos = 5;
} else if ((active1 & 0x2000000000000000L) != 0L) {
jjmatchedKind = 125;
jjmatchedPos = 5;
}
break;
case 54:
if ((active1 & 0x1000000000000000L) != 0L) {
jjmatchedKind = 124;
jjmatchedPos = 5;
}
break;
case 65:
case 97:
return jjMoveStringLiteralDfa6_0(active0, 0x4000000000000000L, active1, 0x200400000L, active2, 0L);
case 67:
case 99:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x2008000000L, active2, 0L);
case 68:
case 100:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x40000400000000L, active2, 0L);
case 69:
case 101:
if ((active1 & 0x100000L) != 0L) {
jjmatchedKind = 84;
jjmatchedPos = 5;
} else if ((active2 & 0x20L) != 0L) {
jjmatchedKind = 133;
jjmatchedPos = 5;
} else if ((active2 & 0x100L) != 0L) {
jjmatchedKind = 136;
jjmatchedPos = 5;
}
return jjMoveStringLiteralDfa6_0(active0, 0x10000000000L, active1, 0x20040000000032L, active2, 0L);
case 70:
case 102:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x800000000L, active2, 0L);
case 71:
case 103:
if ((active0 & 0x200000000000000L) != 0L) {
jjmatchedKind = 57;
jjmatchedPos = 5;
}
break;
case 73:
case 105:
return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L, active1, 0x20000000800L, active2, 0L);
case 76:
case 108:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0L, active2, 0x800L);
case 78:
case 110:
if ((active1 & 0x80000000L) != 0L) {
jjmatchedKind = 95;
jjmatchedPos = 5;
}
return jjMoveStringLiteralDfa6_0(active0, 0x10008000000000L, active1, 0x10000208L, active2, 0L);
case 79:
case 111:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x80000000000000L, active2, 0L);
case 82:
case 114:
if ((active0 & 0x100000000000000L) != 0L) {
jjmatchedKind = 56;
jjmatchedPos = 5;
} else if ((active1 & 0x100000000L) != 0L) {
jjmatchedKind = 96;
jjmatchedPos = 5;
}
return jjMoveStringLiteralDfa6_0(active0, 0x1000000000L, active1, 0L, active2, 0L);
case 83:
case 115:
if ((active0 & 0x800000000000000L) != 0L) {
jjmatchedKind = 59;
jjmatchedPos = 5;
} else if ((active1 & 0x20000000L) != 0L) {
jjmatchedKind = 93;
jjmatchedPos = 5;
}
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x40L, active2, 0L);
case 84:
case 116:
if ((active0 & 0x800000000L) != 0L) {
jjmatchedKind = 35;
jjmatchedPos = 5;
} else if ((active0 & 0x8000000000000L) != 0L) {
jjmatchedKind = 51;
jjmatchedPos = 5;
} else if ((active1 & 0x10000000000L) != 0L) {
jjmatchedKind = 104;
jjmatchedPos = 5;
} else if ((active2 & 0x40L) != 0L) {
jjmatchedKind = 134;
jjmatchedPos = 5;
} else if ((active2 & 0x400L) != 0L) {
jjmatchedKind = 138;
jjmatchedPos = 5;
}
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x1000000000L, active2, 0L);
case 88:
case 120:
if ((active0 & 0x400000000L) != 0L) {
jjmatchedKind = 34;
jjmatchedPos = 5;
}
break;
case 89:
case 121:
return jjMoveStringLiteralDfa6_0(active0, 0x8000000000000000L, active1, 0L, active2, 0L);
case 95:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x200000L, active2, 0L);
default:
break;
}
return jjMoveNfa_0(5);
}
private int jjMoveStringLiteralDfa6_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L)
return jjMoveNfa_0(5);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(5);
}
switch (curChar) {
case 65:
case 97:
return jjMoveStringLiteralDfa7_0(active0, 0x10000000000000L, active1, 0L, active2);
case 66:
case 98:
return jjMoveStringLiteralDfa7_0(active0, 0x2000000000L, active1, 0L, active2);
case 67:
case 99:
return jjMoveStringLiteralDfa7_0(active0, 0x8000000000L, active1, 0x200040L, active2);
case 68:
case 100:
if ((active0 & 0x10000000000L) != 0L) {
jjmatchedKind = 40;
jjmatchedPos = 6;
} else if ((active1 & 0x800L) != 0L) {
jjmatchedKind = 75;
jjmatchedPos = 6;
}
break;
case 69:
case 101:
if ((active1 & 0x8000000L) != 0L) {
jjmatchedKind = 91;
jjmatchedPos = 6;
} else if ((active1 & 0x2000000000L) != 0L) {
jjmatchedKind = 101;
jjmatchedPos = 6;
}
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x1000000000L, active2);
case 71:
case 103:
if ((active1 & 0x200L) != 0L) {
jjmatchedKind = 73;
jjmatchedPos = 6;
}
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x10000000L, active2);
case 75:
case 107:
if ((active1 & 0x8L) != 0L) {
jjmatchedKind = 67;
jjmatchedPos = 6;
}
break;
case 78:
case 110:
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x80020000000000L, active2);
case 79:
case 111:
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x800000000L, active2);
case 80:
case 112:
return jjMoveStringLiteralDfa7_0(active0, 0x8000000000000000L, active1, 0L, active2);
case 82:
case 114:
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x200000032L, active2);
case 83:
case 115:
if ((active1 & 0x400000000L) != 0L) {
jjmatchedKind = 98;
jjmatchedPos = 6;
} else if ((active1 & 0x20000000000000L) != 0L) {
jjmatchedKind = 117;
jjmatchedPos = 6;
} else if ((active1 & 0x40000000000000L) != 0L) {
jjmatchedKind = 118;
jjmatchedPos = 6;
}
break;
case 84:
case 116:
if ((active2 & 0x800L) != 0L) {
jjmatchedKind = 139;
jjmatchedPos = 6;
}
return jjMoveStringLiteralDfa7_0(active0, 0x4000000000000000L, active1, 0x400000L, active2);
case 85:
case 117:
return jjMoveStringLiteralDfa7_0(active0, 0x1000000000L, active1, 0L, active2);
case 95:
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x40000000000L, active2);
default:
break;
}
return jjMoveNfa_0(6);
}
private int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1, long old2) {
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjMoveNfa_0(6);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(6);
}
switch (curChar) {
case 65:
case 97:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x10L);
case 67:
case 99:
return jjMoveStringLiteralDfa8_0(active0, 0x4000001000000000L, active1, 0L);
case 69:
case 101:
if ((active0 & 0x2000000000L) != 0L) {
jjmatchedKind = 37;
jjmatchedPos = 7;
} else if ((active0 & 0x8000000000000000L) != 0L) {
jjmatchedKind = 63;
jjmatchedPos = 7;
} else if ((active1 & 0x40L) != 0L) {
jjmatchedKind = 70;
jjmatchedPos = 7;
} else if ((active1 & 0x80000000000000L) != 0L) {
jjmatchedKind = 119;
jjmatchedPos = 7;
}
break;
case 70:
case 102:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x40000000000L);
case 73:
case 105:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x20L);
case 76:
case 108:
if ((active0 & 0x10000000000000L) != 0L) {
jjmatchedKind = 52;
jjmatchedPos = 7;
}
break;
case 77:
case 109:
if ((active1 & 0x2L) != 0L) {
jjmatchedKind = 65;
jjmatchedPos = 7;
}
break;
case 79:
case 111:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x600000L);
case 82:
case 114:
if ((active1 & 0x1000000000L) != 0L) {
jjmatchedKind = 100;
jjmatchedPos = 7;
}
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x800000000L);
case 83:
case 115:
if ((active1 & 0x10000000L) != 0L) {
jjmatchedKind = 92;
jjmatchedPos = 7;
} else if ((active1 & 0x20000000000L) != 0L) {
jjmatchedKind = 105;
jjmatchedPos = 7;
}
break;
case 84:
case 116:
if ((active0 & 0x8000000000L) != 0L) {
jjmatchedKind = 39;
jjmatchedPos = 7;
}
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x200000000L);
default:
break;
}
return jjMoveNfa_0(7);
}
private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1) {
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjMoveNfa_0(7);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(7);
}
switch (curChar) {
case 67:
case 99:
if ((active1 & 0x20L) != 0L) {
jjmatchedKind = 69;
jjmatchedPos = 8;
}
break;
case 69:
case 101:
if ((active1 & 0x800000000L) != 0L) {
jjmatchedKind = 99;
jjmatchedPos = 8;
}
break;
case 72:
case 104:
return jjMoveStringLiteralDfa9_0(active0, 0x4000000000000000L, active1, 0L);
case 76:
case 108:
if ((active1 & 0x10L) != 0L) {
jjmatchedKind = 68;
jjmatchedPos = 8;
}
break;
case 78:
case 110:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x200000L);
case 79:
case 111:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x40000000000L);
case 82:
case 114:
if ((active1 & 0x400000L) != 0L) {
jjmatchedKind = 86;
jjmatchedPos = 8;
}
break;
case 83:
case 115:
if ((active1 & 0x200000000L) != 0L) {
jjmatchedKind = 97;
jjmatchedPos = 8;
}
break;
case 84:
case 116:
if ((active0 & 0x1000000000L) != 0L) {
jjmatchedKind = 36;
jjmatchedPos = 8;
}
break;
default:
break;
}
return jjMoveNfa_0(8);
}
private int jjMoveStringLiteralDfa9_0(long old0, long active0, long old1, long active1) {
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjMoveNfa_0(8);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(8);
}
switch (curChar) {
case 67:
case 99:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x200000L);
case 69:
case 101:
return jjMoveStringLiteralDfa10_0(active0, 0x4000000000000000L, active1, 0L);
case 82:
case 114:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x40000000000L);
default:
break;
}
return jjMoveNfa_0(9);
}
private int jjMoveStringLiteralDfa10_0(long old0, long active0, long old1, long active1) {
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjMoveNfa_0(9);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(9);
}
switch (curChar) {
case 65:
case 97:
return jjMoveStringLiteralDfa11_0(active0, active1, 0x200000L);
case 83:
case 115:
if ((active0 & 0x4000000000000000L) != 0L) {
jjmatchedKind = 62;
jjmatchedPos = 10;
}
break;
case 95:
return jjMoveStringLiteralDfa11_0(active0, active1, 0x40000000000L);
default:
break;
}
return jjMoveNfa_0(10);
}
private int jjMoveStringLiteralDfa11_0(long old0, long old1, long active1) {
if ((active1 &= old1) == 0L)
return jjMoveNfa_0(10);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(10);
}
switch (curChar) {
case 84:
case 116:
if ((active1 & 0x200000L) != 0L) {
jjmatchedKind = 85;
jjmatchedPos = 11;
}
break;
case 85:
case 117:
return jjMoveStringLiteralDfa12_0(active1);
default:
break;
}
return jjMoveNfa_0(11);
}
private int jjMoveStringLiteralDfa12_0(long old1) {
long active1 = 0x40000000000L;
if ((active1 &= old1) == 0L)
return jjMoveNfa_0(11);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(11);
}
switch (curChar) {
case 82:
case 114:
return jjMoveStringLiteralDfa13_0(active1);
default:
break;
}
return jjMoveNfa_0(12);
}
private int jjMoveStringLiteralDfa13_0(long old1) {
if ((0x40000000000L & old1) == 0L)
return jjMoveNfa_0(12);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return jjMoveNfa_0(12);
}
switch (curChar) {
case 73:
case 105:
jjmatchedKind = 106;
jjmatchedPos = 13;
break;
default:
break;
}
return jjMoveNfa_0(13);
}
static final long[] jjbitVec0 = {
0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec2 = {
0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec3 = {
0xfffe7000fffffff6L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0x5e00000000ffffffL
};
static final long[] jjbitVec4 = {
0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL
};
static final long[] jjbitVec5 = {
0x0L, 0xbfff000000000000L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec6 = {
0x3000L, 0xffff000000000000L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec7 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L
};
static final long[] jjbitVec8 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffL
};
static final long[] jjbitVec9 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffff00000000ffffL
};
static final long[] jjbitVec10 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0x3fffffffffffffffL
};
static final long[] jjbitVec11 = {
0x0L, 0x0L, 0x80000000000000L, 0xff7fffffff7fffffL
};
static final long[] jjbitVec12 = {
0xffffffffffffffffL, 0xbfffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec13 = {
0x8000000000003000L, 0xffff000000000001L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
private int jjMoveNfa_0(int curPos) {
int strKind = jjmatchedKind;
int strPos = jjmatchedPos;
int seenUpto;
input_stream.backup(seenUpto = curPos + 1);
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
throw new Error("Internal Error");
}
curPos = 0;
int startsAt = 0;
jjnewStateCnt = 157;
int i = 1;
jjstateSet[0] = 0;
int kind = 0x7fffffff;
for (;;) {
if (++jjround == 0x7fffffff)
ReInitRounds();
if (curChar < 64) {
kind = jjMoveNfa_0_curCharLessThan64(startsAt, i, kind);
} else if (curChar < 128) {
kind = jjMoveNfa_0_curCharLessThan128(startsAt, i, kind);
} else {
kind = jjMoveNfa_0_curChar128AndAbove(startsAt, i, kind);
}
if (kind != 0x7fffffff) {
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 157 - (jjnewStateCnt = startsAt)))
break;
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
break;
}
}
if (jjmatchedPos > strPos)
return curPos;
int toRet = Math.max(curPos, seenUpto);
if (curPos < toRet)
for (i = toRet - curPos; i
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
throw new Error("Internal Error : Please send a bug report.");
}
if (jjmatchedPos < strPos) {
jjmatchedKind = strKind;
jjmatchedPos = strPos;
} else if (jjmatchedPos == strPos && jjmatchedKind > strKind)
jjmatchedKind = strKind;
return toRet;
}
private int jjMoveNfa_0_curChar128AndAbove(int startsAt, int i, int kind) {
int hiByte = curChar >> 8;
int i1 = hiByte >> 6;
long l1 = 1L << (hiByte & 077);
int i2 = (curChar & 0xff) >> 6;
long l2 = 1L << (curChar & 077);
do {
switch (jjstateSet[--i]) {
case 0:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjCheckNAddStates(58, 63);
}
break;
case 2:
if (!jjCanMove_0(hiByte, i1, i2, l1, l2))
break;
if (kind > 3)
kind = 3;
jjstateSet[jjnewStateCnt++] = 2;
break;
case 13:
if (jjCanMove_0(hiByte, i1, i2, l1, l2)) {
jjAddStates(67, 68);
}
break;
case 16:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 147)
kind = 147; {
jjCheckNAddTwoStates(17, 18);
}
break;
case 17:
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(17, 18);
}
break;
case 18:
if (jjCanMove_2(hiByte, i1, i2, l1, l2) && kind > 147)
kind = 147;
break;
case 21:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 148)
kind = 148; {
jjCheckNAdd(22);
}
break;
case 22:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 148)
kind = 148; {
jjCheckNAdd(22);
}
break;
case 24:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 149)
kind = 149; {
jjCheckNAdd(25);
}
break;
case 25:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 149)
kind = 149; {
jjCheckNAdd(25);
}
break;
case 31:
if (jjCanMove_0(hiByte, i1, i2, l1, l2)) {
jjAddStates(23, 25);
}
break;
case 36:
if (jjCanMove_0(hiByte, i1, i2, l1, l2)) {
jjAddStates(20, 22);
}
break;
case 42:
if (jjCanMove_0(hiByte, i1, i2, l1, l2)) {
jjAddStates(28, 31);
}
break;
case 53:
if (jjCanMove_0(hiByte, i1, i2, l1, l2)) {
jjAddStates(34, 37);
}
break;
case 72:
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(72, 73);
}
break;
case 73:
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
jjCheckNAdd(74);
}
break;
case 75:
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(75, 76);
}
break;
case 76:
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
jjCheckNAdd(77);
}
break;
case 78:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 79:
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
jjCheckNAddStates(44, 47);
}
break;
case 80:
if (jjCanMove_2(hiByte, i1, i2, l1, l2) && kind > 146)
kind = 146;
break;
default:
if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0)
break;
else
break;
}
} while (i != startsAt);
return kind;
}
private int jjMoveNfa_0_curCharLessThan128(int startsAt, int i, int kind) {
long l = 1L << (curChar & 077);
do {
switch (jjstateSet[--i]) {
case 0:
if ((0x7fffffe07fffffeL & l) != 0L) {
jjCheckNAddStates(58, 63);
} else if (curChar == 64) {
jjCheckNAdd(27);
} else if (curChar == 95)
jjstateSet[jjnewStateCnt++] = 15;
else if (curChar == 91) {
jjAddStates(26, 27);
}
if ((0x20000000200L & l) != 0L) {
jjAddStates(64, 66);
} else if ((0x20000000200000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 10;
break;
case 2:
if (kind > 3)
kind = 3;
jjstateSet[jjnewStateCnt++] = 2;
break;
case 6:
if (curChar == 91) {
jjAddStates(26, 27);
}
break;
case 8:
if (curChar == 93 && kind > 31)
kind = 31;
break;
case 9:
if ((0x20000000200L & l) != 0L && kind > 76)
kind = 76;
break;
case 10:
case 70:
if ((0x4000000040000L & l) != 0L) {
jjCheckNAdd(9);
}
break;
case 11:
if ((0x20000000200000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 10;
break;
case 13:
if ((0xc7fffffeafffffffL & l) != 0L) {
jjAddStates(67, 68);
}
break;
case 16:
if ((0x7fffffe87fffffeL & l) == 0L)
break;
if (kind > 147)
kind = 147; {
jjCheckNAddTwoStates(17, 18);
}
break;
case 17:
if ((0x7fffffe87fffffeL & l) != 0L) {
jjCheckNAddTwoStates(17, 18);
}
break;
case 18:
if ((0x7fffffe87fffffeL & l) != 0L && kind > 147)
kind = 147;
break;
case 19:
if (curChar == 95)
jjstateSet[jjnewStateCnt++] = 15;
break;
case 21:
case 22:
if ((0x7fffffe87fffffeL & l) == 0L)
break;
if (kind > 148)
kind = 148; {
jjCheckNAdd(22);
}
break;
case 24:
case 25:
if ((0x7fffffe87fffffeL & l) == 0L)
break;
if (kind > 149)
kind = 149; {
jjCheckNAdd(25);
}
break;
case 26:
if (curChar == 64) {
jjCheckNAdd(27);
}
break;
case 27:
if ((0x7fffffe07fffffeL & l) == 0L)
break;
if (kind > 150)
kind = 150; {
jjCheckNAddTwoStates(27, 28);
}
break;
case 29:
if ((0x7fffffe07fffffeL & l) == 0L)
break;
if (kind > 150)
kind = 150; {
jjCheckNAddTwoStates(28, 29);
}
break;
case 31:
if ((0xffffffffefffffffL & l) != 0L) {
jjCheckNAddStates(23, 25);
}
break;
case 32:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 33;
break;
case 33:
if ((0x14404410000000L & l) != 0L) {
jjCheckNAddStates(23, 25);
}
break;
case 36:
if ((0xffffffffefffffffL & l) != 0L) {
jjCheckNAddStates(20, 22);
}
break;
case 37:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 38;
break;
case 38:
if ((0x14404410000000L & l) != 0L) {
jjCheckNAddStates(20, 22);
}
break;
case 42:
if ((0xffffffffefffffffL & l) != 0L) {
jjCheckNAddStates(28, 31);
}
break;
case 43:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 44;
break;
case 44:
if ((0x14404410000000L & l) != 0L) {
jjCheckNAddStates(28, 31);
}
break;
case 53:
if ((0xffffffffefffffffL & l) != 0L) {
jjCheckNAddStates(34, 37);
}
break;
case 54:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 55;
break;
case 55:
if ((0x14404410000000L & l) != 0L) {
jjCheckNAddStates(34, 37);
}
break;
case 62:
if ((0x20000000200L & l) != 0L) {
jjAddStates(64, 66);
}
break;
case 63:
if ((0x20000000200L & l) != 0L && kind > 66)
kind = 66;
break;
case 64:
case 67:
if ((0x4000000040000L & l) != 0L) {
jjCheckNAdd(63);
}
break;
case 65:
if ((0x20000000200L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 64;
break;
case 66:
if ((0x8000000080000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 65;
break;
case 68:
if ((0x20000000200000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 67;
break;
case 69:
if ((0x8000000080000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 68;
break;
case 71:
if ((0x7fffffe07fffffeL & l) != 0L) {
jjCheckNAddStates(58, 63);
}
break;
case 72:
if ((0x7fffffe87fffffeL & l) != 0L) {
jjCheckNAddTwoStates(72, 73);
}
break;
case 73:
if ((0x7fffffe87fffffeL & l) != 0L) {
jjCheckNAdd(74);
}
break;
case 75:
if ((0x7fffffe87fffffeL & l) != 0L) {
jjCheckNAddTwoStates(75, 76);
}
break;
case 76:
if ((0x7fffffe87fffffeL & l) != 0L) {
jjCheckNAdd(77);
}
break;
case 78:
if ((0x7fffffe87fffffeL & l) == 0L)
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 79:
if ((0x7fffffe87fffffeL & l) != 0L) {
jjCheckNAddStates(44, 47);
}
break;
case 80:
if ((0x7fffffe87fffffeL & l) != 0L && kind > 146)
kind = 146;
break;
case 81:
if (curChar == 92) {
jjAddStates(69, 70);
}
break;
case 82:
if ((0x4000000080000001L & l) != 0L) {
jjCheckNAddStates(44, 47);
}
break;
case 84:
if ((0x7e0000007eL & l) != 0L)
jjstateSet[jjnewStateCnt++] = 85;
break;
case 85:
if ((0x7e0000007eL & l) != 0L) {
jjCheckNAddStates(44, 47);
}
break;
case 86:
if ((0x7e0000007eL & l) != 0L)
jjstateSet[jjnewStateCnt++] = 87;
break;
case 87:
if ((0x7e0000007eL & l) != 0L && kind > 146)
kind = 146;
break;
case 88:
if ((0x4000000080000001L & l) != 0L && kind > 146)
kind = 146;
break;
case 89:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 90;
break;
case 90:
if ((0x4000000080000001L & l) == 0L)
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 92:
if ((0x7e0000007eL & l) != 0L)
jjstateSet[jjnewStateCnt++] = 93;
break;
case 93:
if ((0x7e0000007eL & l) == 0L)
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 103:
if ((0x2000000020L & l) != 0L) {
jjAddStates(71, 72);
}
break;
case 107:
if ((0x2000000020L & l) != 0L) {
jjAddStates(73, 74);
}
break;
case 117:
if ((0x2000000020L & l) != 0L) {
jjAddStates(75, 76);
}
break;
case 124:
if ((0x2000000020L & l) != 0L) {
jjAddStates(77, 78);
}
break;
case 128:
if ((0x2000000020L & l) != 0L) {
jjAddStates(79, 80);
}
break;
case 138:
if ((0x2000000020L & l) != 0L) {
jjAddStates(81, 82);
}
break;
case 145:
if ((0x2000000020L & l) != 0L) {
jjAddStates(83, 84);
}
break;
case 149:
if ((0x2000000020L & l) != 0L) {
jjAddStates(85, 86);
}
break;
case 154:
if ((0x2000000020L & l) != 0L) {
jjAddStates(87, 88);
}
break;
default:
break;
}
} while (i != startsAt);
return kind;
}
private int jjMoveNfa_0_curCharLessThan64(int startsAt, int i, int kind) {
long l = 1L << curChar;
do {
switch (jjstateSet[--i]) {
case 0:
if ((0x3ff000000000000L & l) != 0L) {
if (kind > 151)
kind = 151;
{
jjCheckNAddStates(0, 6);
}
} else if ((0x100003600L & l) != 0L) {
if (kind > 2)
kind = 2;
} else if (curChar == 46) {
jjCheckNAddTwoStates(99, 153);
} else if (curChar == 45) {
jjCheckNAddStates(7, 11);
} else if (curChar == 43) {
jjCheckNAddStates(12, 16);
} else if (curChar == 58) {
if (kind > 145)
kind = 145;
{
jjCheckNAddStates(17, 19);
}
} else if (curChar == 34)
jjstateSet[jjnewStateCnt++] = 60;
else if (curChar == 39)
jjstateSet[jjnewStateCnt++] = 49;
else if (curChar == 36)
jjstateSet[jjnewStateCnt++] = 24;
else if (curChar == 60) {
jjCheckNAddTwoStates(13, 14);
} else if (curChar == 40) {
jjCheckNAddTwoStates(4, 5);
} else if (curChar == 35) {
if (kind > 3)
kind = 3;
{
jjCheckNAdd(2);
}
} else if (curChar == 63)
jjstateSet[jjnewStateCnt++] = 21;
if (curChar == 34) {
jjCheckNAddStates(20, 22);
} else if (curChar == 39) {
jjCheckNAddStates(23, 25);
}
break;
case 1:
if (curChar != 35)
break;
if (kind > 3)
kind = 3; {
jjCheckNAdd(2);
}
break;
case 2:
if ((0xffffffffffffdbffL & l) == 0L)
break;
if (kind > 3)
kind = 3; {
jjCheckNAdd(2);
}
break;
case 3:
if (curChar == 40) {
jjCheckNAddTwoStates(4, 5);
}
break;
case 4:
if ((0x100003600L & l) != 0L) {
jjCheckNAddTwoStates(4, 5);
}
break;
case 5:
if (curChar == 41 && kind > 30)
kind = 30;
break;
case 7:
if ((0x100003600L & l) != 0L) {
jjAddStates(26, 27);
}
break;
case 12:
if (curChar == 60) {
jjCheckNAddTwoStates(13, 14);
}
break;
case 13:
if ((0xaffffffa00000000L & l) != 0L) {
jjCheckNAddTwoStates(13, 14);
}
break;
case 14:
if (curChar == 62 && kind > 144)
kind = 144;
break;
case 15:
if (curChar == 58)
jjstateSet[jjnewStateCnt++] = 16;
break;
case 16:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 147)
kind = 147; {
jjCheckNAddTwoStates(17, 18);
}
break;
case 17:
if ((0x3ff600000000000L & l) != 0L) {
jjCheckNAddTwoStates(17, 18);
}
break;
case 18:
if ((0x3ff200000000000L & l) != 0L && kind > 147)
kind = 147;
break;
case 20:
if (curChar == 63)
jjstateSet[jjnewStateCnt++] = 21;
break;
case 21:
case 22:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 148)
kind = 148; {
jjCheckNAdd(22);
}
break;
case 23:
if (curChar == 36)
jjstateSet[jjnewStateCnt++] = 24;
break;
case 24:
case 25:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 149)
kind = 149; {
jjCheckNAdd(25);
}
break;
case 28:
if (curChar == 45) {
jjCheckNAdd(29);
}
break;
case 29:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 150)
kind = 150; {
jjCheckNAddTwoStates(28, 29);
}
break;
case 30:
if (curChar == 39) {
jjCheckNAddStates(23, 25);
}
break;
case 31:
if ((0xffffff7fffffdbffL & l) != 0L) {
jjCheckNAddStates(23, 25);
}
break;
case 33:
if ((0x8400000000L & l) != 0L) {
jjCheckNAddStates(23, 25);
}
break;
case 34:
if (curChar == 39 && kind > 164)
kind = 164;
break;
case 35:
if (curChar == 34) {
jjCheckNAddStates(20, 22);
}
break;
case 36:
if ((0xfffffffbffffdbffL & l) != 0L) {
jjCheckNAddStates(20, 22);
}
break;
case 38:
if ((0x8400000000L & l) != 0L) {
jjCheckNAddStates(20, 22);
}
break;
case 39:
if (curChar == 34 && kind > 165)
kind = 165;
break;
case 40:
if (curChar == 39) {
jjCheckNAddStates(28, 31);
}
break;
case 41:
case 46:
if (curChar == 39) {
jjCheckNAddTwoStates(42, 43);
}
break;
case 42:
if ((0xffffff7fffffffffL & l) != 0L) {
jjCheckNAddStates(28, 31);
}
break;
case 44:
if ((0x8400000000L & l) != 0L) {
jjCheckNAddStates(28, 31);
}
break;
case 45:
if (curChar == 39) {
jjAddStates(32, 33);
}
break;
case 47:
if (curChar == 39 && kind > 166)
kind = 166;
break;
case 48:
if (curChar == 39)
jjstateSet[jjnewStateCnt++] = 47;
break;
case 49:
if (curChar == 39)
jjstateSet[jjnewStateCnt++] = 40;
break;
case 50:
if (curChar == 39)
jjstateSet[jjnewStateCnt++] = 49;
break;
case 51:
if (curChar == 34) {
jjCheckNAddStates(34, 37);
}
break;
case 52:
case 57:
if (curChar == 34) {
jjCheckNAddTwoStates(53, 54);
}
break;
case 53:
if ((0xfffffffbffffffffL & l) != 0L) {
jjCheckNAddStates(34, 37);
}
break;
case 55:
if ((0x8400000000L & l) != 0L) {
jjCheckNAddStates(34, 37);
}
break;
case 56:
if (curChar == 34) {
jjAddStates(38, 39);
}
break;
case 58:
if (curChar == 34 && kind > 167)
kind = 167;
break;
case 59:
if (curChar == 34)
jjstateSet[jjnewStateCnt++] = 58;
break;
case 60:
if (curChar == 34)
jjstateSet[jjnewStateCnt++] = 51;
break;
case 61:
if (curChar == 34)
jjstateSet[jjnewStateCnt++] = 60;
break;
case 72:
if ((0x3ff600000000000L & l) != 0L) {
jjAddStates(40, 41);
}
break;
case 73:
if ((0x3ff200000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 74;
break;
case 74:
if (curChar == 58 && kind > 145)
kind = 145;
break;
case 75:
if ((0x3ff600000000000L & l) != 0L) {
jjAddStates(42, 43);
}
break;
case 76:
if ((0x3ff200000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 77;
break;
case 77:
if (curChar == 58) {
jjCheckNAddStates(17, 19);
}
break;
case 78:
if ((0x7ff000000000000L & l) == 0L)
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 79:
if ((0x7ff600000000000L & l) != 0L) {
jjCheckNAddStates(44, 47);
}
break;
case 80:
if ((0x7ff200000000000L & l) != 0L && kind > 146)
kind = 146;
break;
case 82:
if ((0xa800ff7e00000000L & l) != 0L) {
jjCheckNAddStates(44, 47);
}
break;
case 83:
if (curChar == 37) {
jjAddStates(48, 49);
}
break;
case 84:
if ((0x3ff000000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 85;
break;
case 85:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddStates(44, 47);
}
break;
case 86:
if ((0x3ff000000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 87;
break;
case 87:
if ((0x3ff000000000000L & l) != 0L && kind > 146)
kind = 146;
break;
case 88:
if ((0xa800ff7e00000000L & l) != 0L && kind > 146)
kind = 146;
break;
case 90:
if ((0xa800ff7e00000000L & l) == 0L)
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 91:
if (curChar == 37)
jjstateSet[jjnewStateCnt++] = 92;
break;
case 92:
if ((0x3ff000000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 93;
break;
case 93:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 146)
kind = 146; {
jjCheckNAddStates(44, 47);
}
break;
case 94:
if (curChar != 58)
break;
if (kind > 145)
kind = 145; {
jjCheckNAddStates(17, 19);
}
break;
case 95:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 151)
kind = 151; {
jjCheckNAddStates(0, 6);
}
break;
case 96:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 151)
kind = 151; {
jjCheckNAdd(96);
}
break;
case 97:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(97, 98);
}
break;
case 98:
if (curChar == 46) {
jjCheckNAdd(99);
}
break;
case 99:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 154)
kind = 154; {
jjCheckNAdd(99);
}
break;
case 100:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(100, 101);
}
break;
case 101:
if (curChar == 46) {
jjCheckNAddTwoStates(102, 103);
}
break;
case 102:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(102, 103);
}
break;
case 104:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(105);
}
break;
case 105:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 157)
kind = 157; {
jjCheckNAdd(105);
}
break;
case 106:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(106, 107);
}
break;
case 108:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(109);
}
break;
case 109:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 157)
kind = 157; {
jjCheckNAdd(109);
}
break;
case 110:
if (curChar == 43) {
jjCheckNAddStates(12, 16);
}
break;
case 111:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 152)
kind = 152; {
jjCheckNAdd(111);
}
break;
case 112:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(112, 113);
}
break;
case 113:
if (curChar == 46) {
jjCheckNAdd(114);
}
break;
case 114:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 155)
kind = 155; {
jjCheckNAdd(114);
}
break;
case 115:
if (curChar == 46) {
jjCheckNAdd(116);
}
break;
case 116:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(116, 117);
}
break;
case 118:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(119);
}
break;
case 119:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 162)
kind = 162; {
jjCheckNAdd(119);
}
break;
case 120:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddStates(50, 53);
}
break;
case 121:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(121, 122);
}
break;
case 122:
if (curChar == 46) {
jjCheckNAddTwoStates(123, 124);
}
break;
case 123:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(123, 124);
}
break;
case 125:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(126);
}
break;
case 126:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 162)
kind = 162; {
jjCheckNAdd(126);
}
break;
case 127:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(127, 128);
}
break;
case 129:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(130);
}
break;
case 130:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 162)
kind = 162; {
jjCheckNAdd(130);
}
break;
case 131:
if (curChar == 45) {
jjCheckNAddStates(7, 11);
}
break;
case 132:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 153)
kind = 153; {
jjCheckNAdd(132);
}
break;
case 133:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(133, 134);
}
break;
case 134:
if (curChar == 46) {
jjCheckNAdd(135);
}
break;
case 135:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 156)
kind = 156; {
jjCheckNAdd(135);
}
break;
case 136:
if (curChar == 46) {
jjCheckNAdd(137);
}
break;
case 137:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(137, 138);
}
break;
case 139:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(140);
}
break;
case 140:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 163)
kind = 163; {
jjCheckNAdd(140);
}
break;
case 141:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddStates(54, 57);
}
break;
case 142:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(142, 143);
}
break;
case 143:
if (curChar == 46) {
jjCheckNAddTwoStates(144, 145);
}
break;
case 144:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(144, 145);
}
break;
case 146:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(147);
}
break;
case 147:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 163)
kind = 163; {
jjCheckNAdd(147);
}
break;
case 148:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(148, 149);
}
break;
case 150:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(151);
}
break;
case 151:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 163)
kind = 163; {
jjCheckNAdd(151);
}
break;
case 152:
if (curChar == 46) {
jjCheckNAddTwoStates(99, 153);
}
break;
case 153:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(153, 154);
}
break;
case 155:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(156);
}
break;
case 156:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 157)
kind = 157; {
jjCheckNAdd(156);
}
break;
default:
break;
}
} while (i != startsAt);
return kind;
}
/** Token literal values. */
public static final String[] jjstrLiteralImages = {
"", null, null, null, "\50", "\51", "\173", "\175", "\133", "\135", "\73",
"\54", "\56", "\75", "\41\75", "\76", "\74", "\74\75", "\76\75", "\41", "\174\174",
"\46\46", "\53", "\55", "\52", "\77", "\57", "\174", "\136", "\136\136", null, null,
"\141", null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
"\74\74", "\76\76", };
protected Token jjFillToken() {
final Token t;
final String curTokenImage;
final int beginLine;
final int endLine;
final int beginColumn;
final int endColumn;
String im = jjstrLiteralImages[jjmatchedKind];
curTokenImage = im == null ? input_stream.GetImage() : im;
beginLine = input_stream.getBeginLine();
beginColumn = input_stream.getBeginColumn();
endLine = input_stream.getEndLine();
endColumn = input_stream.getEndColumn();
t = Token.newToken(jjmatchedKind, curTokenImage);
t.beginLine = beginLine;
t.endLine = endLine;
t.beginColumn = beginColumn;
t.endColumn = endColumn;
return t;
}
static final int[] jjnextStates = {
96, 97, 98, 100, 101, 106, 107, 132, 133, 134, 136, 141, 111, 112, 113, 115,
120, 78, 89, 91, 36, 37, 39, 31, 32, 34, 7, 8, 41, 42, 43, 45,
46, 48, 52, 53, 54, 56, 57, 59, 72, 73, 75, 76, 79, 80, 81, 83,
84, 86, 121, 122, 127, 128, 142, 143, 148, 149, 72, 73, 74, 75, 76, 77,
66, 69, 70, 13, 14, 82, 88, 104, 105, 108, 109, 118, 119, 125, 126, 129,
130, 139, 140, 146, 147, 150, 151, 155, 156,
};
private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) {
if (hiByte == 0) {
return (jjbitVec2[i2] & l2) != 0L;
}
return (jjbitVec0[i1] & l1) != 0L;
}
private static boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2) {
switch (hiByte) {
case 0:
return (jjbitVec4[i2] & l2) != 0L;
case 3:
return (jjbitVec5[i2] & l2) != 0L;
case 32:
return (jjbitVec6[i2] & l2) != 0L;
case 33:
return (jjbitVec7[i2] & l2) != 0L;
case 47:
return (jjbitVec8[i2] & l2) != 0L;
case 48:
return (jjbitVec0[i2] & l2) != 0L;
case 253:
return (jjbitVec9[i2] & l2) != 0L;
case 255:
return (jjbitVec10[i2] & l2) != 0L;
default:
return (jjbitVec3[i1] & l1) != 0L;
}
}
private static boolean jjCanMove_2(int hiByte, int i1, int i2, long l1, long l2) {
switch (hiByte) {
case 0:
return (jjbitVec11[i2] & l2) != 0L;
case 3:
return (jjbitVec12[i2] & l2) != 0L;
case 32:
return (jjbitVec13[i2] & l2) != 0L;
case 33:
return (jjbitVec7[i2] & l2) != 0L;
case 47:
return (jjbitVec8[i2] & l2) != 0L;
case 48:
return (jjbitVec0[i2] & l2) != 0L;
case 253:
return (jjbitVec9[i2] & l2) != 0L;
case 255:
return (jjbitVec10[i2] & l2) != 0L;
default:
return (jjbitVec3[i1] & l1) != 0L;
}
}
private int curLexState = 0;
private int jjnewStateCnt;
private int jjround;
private int jjmatchedPos;
private int jjmatchedKind;
/** Get the next Token. */
public Token getNextToken() {
Token specialToken = null;
Token matchedToken;
int curPos;
for (;;) {
try {
curChar = input_stream.BeginToken();
} catch (Exception e) {
jjmatchedKind = 0;
jjmatchedPos = -1;
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
}
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_0();
if (jjmatchedKind != 0x7fffffff) {
if (jjmatchedPos + 1 < curPos) {
input_stream.backup(curPos - jjmatchedPos - 1);
}
if ((jjtoToken[jjmatchedKind >> 6] & 1L << (jjmatchedKind & 077)) != 0L) {
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
} else {
if ((jjtoSpecial[jjmatchedKind >> 6] & 1L << (jjmatchedKind & 077)) != 0L) {
matchedToken = jjFillToken();
if (specialToken == null) {
specialToken = matchedToken;
} else {
matchedToken.specialToken = specialToken;
specialToken = specialToken.next = matchedToken;
}
}
continue;
}
}
int error_line = input_stream.getEndLine();
int error_column = input_stream.getEndColumn();
String error_after = null;
boolean EOFSeen = false;
try {
input_stream.readChar();
input_stream.backup(1);
} catch (java.io.IOException e1) {
EOFSeen = true;
error_after = curPos <= 1 ? "" : input_stream.GetImage();
if (curChar == '\n' || curChar == '\r') {
error_line++;
error_column = 0;
} else {
error_column++;
}
}
if (!EOFSeen) {
input_stream.backup(1);
error_after = curPos <= 1 ? "" : input_stream.GetImage();
}
throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar,
TokenMgrError.LEXICAL_ERROR);
}
}
void SkipLexicalActions(Token matchedToken) {
}
void MoreLexicalActions() {
jjimageLen += jjmatchedPos + 1;
}
void TokenLexicalActions(Token matchedToken) {
}
private void jjCheckNAdd(int state) {
if (jjrounds[state] != jjround) {
jjstateSet[jjnewStateCnt++] = state;
jjrounds[state] = jjround;
}
}
private void jjAddStates(int start, int end) {
do {
jjstateSet[jjnewStateCnt++] = jjnextStates[start];
} while (start++ != end);
}
private void jjCheckNAddTwoStates(int state1, int state2) {
jjCheckNAdd(state1);
jjCheckNAdd(state2);
}
private void jjCheckNAddStates(int start, int end) {
do {
jjCheckNAdd(jjnextStates[start]);
} while (start++ != end);
}
/** Constructor. */
public SyntaxTreeBuilderTokenManager(CharStream stream) {
input_stream = stream;
}
/** Constructor. */
public SyntaxTreeBuilderTokenManager(CharStream stream, int lexState) {
ReInit(stream);
SwitchTo(lexState);
}
/** Reinitialise parser. */
public void ReInit(CharStream stream) {
jjmatchedPos = jjnewStateCnt = 0;
curLexState = 0;
input_stream = stream;
ReInitRounds();
}
private void ReInitRounds() {
int i;
jjround = 0x80000001;
for (i = 157; i
jjrounds[i] = 0x80000000;
}
/** Reinitialise parser. */
public void ReInit(CharStream stream, int lexState)
{
ReInit(stream);
SwitchTo(lexState);
}
/** Switch to specified lex state. */
public void SwitchTo(int lexState) {
if (lexState != 0)
throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.",
TokenMgrError.INVALID_LEXICAL_STATE);
else
curLexState = lexState;
}
/** Lexer state names. */
public static final String[] lexStateNames = {
"DEFAULT",
};
/** Lex State array. */
public static final int[] jjnewLexState = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
static final long[] jjtoToken = {
0xfffffffffffffff1L, 0xffffffffffffffffL, 0xc0000fc3fffffffL,
};
static final long[] jjtoSkip = {
0xcL, 0x0L, 0x0L,
};
static final long[] jjtoSpecial = {
0x8L, 0x0L, 0x0L,
};
static final long[] jjtoMore = {
0x0L, 0x0L, 0x0L,
};
protected CharStream input_stream;
private final int[] jjrounds = new int[157];
private final int[] jjstateSet = new int[2 * 157];
private final StringBuilder jjimage = new StringBuilder();
private final StringBuilder image = jjimage;
private int jjimageLen;
protected int curChar;
}
|
package org.hisp.dhis.appstore2;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.appmanager.AppManager;
import org.hisp.dhis.appmanager.AppStatus;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class DefaultAppStoreService implements AppStoreService
{
private static final Log log = LogFactory.getLog( DefaultAppStoreService.class );
@Autowired
private RestTemplate restTemplate;
@Autowired
private AppManager appManager;
@Autowired
private SystemSettingManager systemSettingManager;
@Override
public List<WebApp> getAppStore()
{
String appStoreApiUrl = (String) systemSettingManager.getSystemSetting( SettingKey.APP_STORE_API_URL );
WebApp[] apps = restTemplate.getForObject( appStoreApiUrl, WebApp[].class );
return Arrays.asList( apps );
}
@Override
public AppStatus installAppFromAppStore( String id )
{
if ( id == null )
{
return AppStatus.NOT_FOUND;
}
try
{
Optional<AppVersion> webAppVersion = getWebAppVersion( id );
if ( webAppVersion.isPresent() )
{
AppVersion version = webAppVersion.get();
URL url = new URL( version.getDownloadUrl() );
String filename = version.getFilename();
return appManager.installApp( getFile( url ), filename );
}
log.info( String.format( "No version found for id %s", id ) );
return AppStatus.NOT_FOUND;
}
catch ( IOException ex )
{
throw new RuntimeException( "Failed to install app", ex );
}
}
// Supportive methods
private Optional<AppVersion> getWebAppVersion( String id )
throws IOException
{
for ( WebApp app : getAppStore() )
{
for ( AppVersion version : app.getVersions() )
{
if ( id.equals( version.getId() ) )
{
return Optional.of( version );
}
}
}
return Optional.empty();
}
private static File getFile( URL url )
throws IOException
{
URLConnection connection = url.openConnection();
BufferedInputStream in = new BufferedInputStream( connection.getInputStream() );
File tempFile = File.createTempFile( "dhis", null );
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream( tempFile );
IOUtils.copy( in, out );
return tempFile;
}
}
|
package org.hisp.dhis.webapi.controller.organisationunit;
import static org.hisp.dhis.system.util.GeoUtils.getCoordinatesFromGeometry;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dxf2.common.TranslateParams;
import org.hisp.dhis.dxf2.webmessage.WebMessage;
import org.hisp.dhis.dxf2.webmessage.WebMessageUtils;
import org.hisp.dhis.fieldfilter.Defaults;
import org.hisp.dhis.merge.orgunit.OrgUnitMergeQuery;
import org.hisp.dhis.merge.orgunit.OrgUnitMergeService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitGroup;
import org.hisp.dhis.organisationunit.OrganisationUnitQueryParams;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.organisationunit.comparator.OrganisationUnitByLevelComparator;
import org.hisp.dhis.query.Order;
import org.hisp.dhis.query.Query;
import org.hisp.dhis.query.QueryParserException;
import org.hisp.dhis.schema.descriptors.OrganisationUnitSchemaDescriptor;
import org.hisp.dhis.split.orgunit.OrgUnitSplitQuery;
import org.hisp.dhis.split.orgunit.OrgUnitSplitService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.util.ObjectUtils;
import org.hisp.dhis.version.VersionService;
import org.hisp.dhis.webapi.controller.AbstractCrudController;
import org.hisp.dhis.webapi.webdomain.WebMetadata;
import org.hisp.dhis.webapi.webdomain.WebOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@Controller
@RequestMapping( value = OrganisationUnitSchemaDescriptor.API_ENDPOINT )
public class OrganisationUnitController
extends AbstractCrudController<OrganisationUnit>
{
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private VersionService versionService;
@Autowired
private OrgUnitSplitService orgUnitSplitService;
@Autowired
private OrgUnitMergeService orgUnitMergeService;
@ResponseStatus( HttpStatus.OK )
@PreAuthorize( "hasRole('ALL') or hasRole('F_ORGANISATION_UNIT_SPLIT')" )
@PostMapping( value = "/split", produces = { APPLICATION_JSON_VALUE } )
public @ResponseBody WebMessage splitOrgUnits( @RequestBody OrgUnitSplitQuery query )
{
orgUnitSplitService.split( orgUnitSplitService.getFromQuery( query ) );
return WebMessageUtils.ok( "Organisation unit split" );
}
@ResponseStatus( HttpStatus.OK )
@PreAuthorize( "hasRole('ALL') or hasRole('F_ORGANISATION_UNIT_MERGE')" )
@PostMapping( value = "/merge", produces = { APPLICATION_JSON_VALUE } )
public @ResponseBody WebMessage mergeOrgUnits( @RequestBody OrgUnitMergeQuery query )
{
orgUnitMergeService.merge( orgUnitMergeService.getFromQuery( query ) );
return WebMessageUtils.ok( "Organisation units merged" );
}
@Override
@SuppressWarnings( "unchecked" )
protected List<OrganisationUnit> getEntityList( WebMetadata metadata, WebOptions options, List<String> filters,
List<Order> orders )
throws QueryParserException
{
List<OrganisationUnit> objects = Lists.newArrayList();
User currentUser = currentUserService.getCurrentUser();
boolean anySpecialPropertySet = ObjectUtils.anyIsTrue( options.isTrue( "userOnly" ),
options.isTrue( "userDataViewOnly" ), options.isTrue( "userDataViewFallback" ),
options.isTrue( "levelSorted" ) );
boolean anyQueryPropertySet = ObjectUtils.firstNonNull( options.get( "query" ), options.getInt( "level" ),
options.getInt( "maxLevel" ) ) != null || options.isTrue( "withinUserHierarchy" )
|| options.isTrue( "withinUserSearchHierarchy" );
String memberObject = options.get( "memberObject" );
String memberCollection = options.get( "memberCollection" );
// Special parameter handling
if ( options.isTrue( "userOnly" ) )
{
objects = new ArrayList<>( currentUser.getOrganisationUnits() );
}
else if ( options.isTrue( "userDataViewOnly" ) )
{
objects = new ArrayList<>( currentUser.getDataViewOrganisationUnits() );
}
else if ( options.isTrue( "userDataViewFallback" ) )
{
if ( currentUser.hasDataViewOrganisationUnit() )
{
objects = new ArrayList<>( currentUser.getDataViewOrganisationUnits() );
}
else
{
objects = organisationUnitService.getOrganisationUnitsAtLevel( 1 );
}
}
else if ( options.isTrue( "levelSorted" ) )
{
objects = new ArrayList<>( manager.getAll( getEntityClass() ) );
objects.sort( OrganisationUnitByLevelComparator.INSTANCE );
}
// OrganisationUnitQueryParams query parameter handling
else if ( anyQueryPropertySet )
{
OrganisationUnitQueryParams params = new OrganisationUnitQueryParams();
params.setQuery( options.get( "query" ) );
params.setLevel( options.getInt( "level" ) );
params.setMaxLevels( options.getInt( "maxLevel" ) );
params.setParents( options.isTrue( "withinUserHierarchy" ) ? currentUser.getOrganisationUnits()
: options.isTrue( "withinUserSearchHierarchy" )
? currentUser.getTeiSearchOrganisationUnitsWithFallback()
: Sets.newHashSet() );
objects = organisationUnitService.getOrganisationUnitsByQuery( params );
}
// Standard Query handling
Query query = queryService.getQueryFromUrl( getEntityClass(), filters, orders, getPaginationData( options ),
options.getRootJunction() );
query.setUser( currentUser );
query.setDefaultOrder();
query.setDefaults( Defaults.valueOf( options.get( "defaults", DEFAULTS ) ) );
if ( anySpecialPropertySet || anyQueryPropertySet )
{
query.setObjects( objects );
}
List<OrganisationUnit> list = (List<OrganisationUnit>) queryService.query( query );
// Collection member count in hierarchy handling
IdentifiableObject member;
if ( memberObject != null && memberCollection != null && (member = manager.get( memberObject )) != null )
{
for ( OrganisationUnit unit : list )
{
Long count = organisationUnitService.getOrganisationUnitHierarchyMemberCount( unit, member,
memberCollection );
unit.setMemberCount( (count != null ? count.intValue() : 0) );
}
}
return list;
}
@Override
protected List<OrganisationUnit> getEntity( String uid, WebOptions options )
{
OrganisationUnit organisationUnit = manager.get( getEntityClass(), uid );
List<OrganisationUnit> organisationUnits = Lists.newArrayList();
if ( organisationUnit == null )
{
return organisationUnits;
}
if ( options.contains( "includeChildren" ) )
{
options.getOptions().put( "useWrapper", "true" );
organisationUnits.add( organisationUnit );
organisationUnits.addAll( organisationUnit.getChildren() );
}
else if ( options.contains( "includeDescendants" ) )
{
options.getOptions().put( "useWrapper", "true" );
organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( uid ) );
}
else if ( options.contains( "includeAncestors" ) )
{
options.getOptions().put( "useWrapper", "true" );
organisationUnits.add( organisationUnit );
List<OrganisationUnit> ancestors = organisationUnit.getAncestors();
Collections.reverse( ancestors );
organisationUnits.addAll( ancestors );
}
else if ( options.contains( "level" ) )
{
options.getOptions().put( "useWrapper", "true" );
int level = options.getInt( "level" );
int ouLevel = organisationUnit.getLevel();
int targetLevel = ouLevel + level;
organisationUnits
.addAll( organisationUnitService.getOrganisationUnitsAtLevel( targetLevel, organisationUnit ) );
}
else
{
organisationUnits.add( organisationUnit );
}
return organisationUnits;
}
@RequestMapping( value = "/{uid}/parents", method = RequestMethod.GET )
public @ResponseBody List<OrganisationUnit> getEntityList( @PathVariable( "uid" ) String uid,
@RequestParam Map<String, String> parameters, Model model, TranslateParams translateParams,
HttpServletRequest request, HttpServletResponse response )
throws Exception
{
setUserContext( translateParams );
OrganisationUnit organisationUnit = manager.get( getEntityClass(), uid );
List<OrganisationUnit> organisationUnits = Lists.newArrayList();
if ( organisationUnit != null )
{
OrganisationUnit organisationUnitParent = organisationUnit.getParent();
while ( organisationUnitParent != null )
{
organisationUnits.add( organisationUnitParent );
organisationUnitParent = organisationUnitParent.getParent();
}
}
WebMetadata metadata = new WebMetadata();
metadata.setOrganisationUnits( organisationUnits );
return organisationUnits;
}
@RequestMapping( value = "", method = RequestMethod.GET, produces = { "application/json+geo",
"application/json+geojson" } )
public void getGeoJson(
@RequestParam( value = "level", required = false ) List<Integer> rpLevels,
@RequestParam( value = "parent", required = false ) List<String> rpParents,
@RequestParam( value = "properties", required = false, defaultValue = "true" ) boolean rpProperties,
User currentUser, HttpServletResponse response )
throws IOException
{
rpLevels = rpLevels != null ? rpLevels : new ArrayList<>();
rpParents = rpParents != null ? rpParents : new ArrayList<>();
List<OrganisationUnit> parents = manager.getByUid( OrganisationUnit.class, rpParents );
if ( rpLevels.isEmpty() )
{
rpLevels.add( 1 );
}
if ( parents.isEmpty() )
{
parents.addAll( organisationUnitService.getRootOrganisationUnits() );
}
List<OrganisationUnit> organisationUnits = organisationUnitService.getOrganisationUnitsAtLevels( rpLevels,
parents );
response.setContentType( "application/json" );
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator( response.getOutputStream() );
generator.writeStartObject();
generator.writeStringField( "type", "FeatureCollection" );
generator.writeArrayFieldStart( "features" );
for ( OrganisationUnit organisationUnit : organisationUnits )
{
writeFeature( generator, organisationUnit, rpProperties, currentUser );
}
generator.writeEndArray();
generator.writeEndObject();
generator.close();
}
private void writeFeature( JsonGenerator generator, OrganisationUnit organisationUnit,
boolean includeProperties, User user )
throws IOException
{
if ( organisationUnit.getGeometry() == null )
{
return;
}
generator.writeStartObject();
generator.writeStringField( "type", "Feature" );
generator.writeStringField( "id", organisationUnit.getUid() );
generator.writeObjectFieldStart( "geometry" );
generator.writeObjectField( "type", organisationUnit.getGeometry().getGeometryType() );
generator.writeFieldName( "coordinates" );
generator.writeRawValue( getCoordinatesFromGeometry( organisationUnit.getGeometry() ) );
generator.writeEndObject();
generator.writeObjectFieldStart( "properties" );
if ( includeProperties )
{
Set<OrganisationUnit> roots = user.getDataViewOrganisationUnitsWithFallback();
generator.writeStringField( "code", organisationUnit.getCode() );
generator.writeStringField( "name", organisationUnit.getName() );
generator.writeStringField( "level", String.valueOf( organisationUnit.getLevel() ) );
if ( organisationUnit.getParent() != null )
{
generator.writeStringField( "parent", organisationUnit.getParent().getUid() );
}
generator.writeStringField( "parentGraph", organisationUnit.getParentGraph( roots ) );
generator.writeArrayFieldStart( "groups" );
for ( OrganisationUnitGroup group : organisationUnit.getGroups() )
{
generator.writeString( group.getUid() );
}
generator.writeEndArray();
}
generator.writeEndObject();
generator.writeEndObject();
}
@Override
protected void postCreateEntity( OrganisationUnit entity )
{
versionService.updateVersion( VersionService.ORGANISATIONUNIT_VERSION );
}
@Override
protected void postUpdateEntity( OrganisationUnit entity )
{
versionService.updateVersion( VersionService.ORGANISATIONUNIT_VERSION );
}
@Override
protected void postDeleteEntity( String entityUID )
{
versionService.updateVersion( VersionService.ORGANISATIONUNIT_VERSION );
}
}
|
package pl.edu.icm.coansys.disambiguation.clustering.strategies;
import pl.edu.icm.coansys.disambiguation.clustering.ClusterElement;
/**
*
* @author pdendek
* @version 1.0
* @since 2012-08-07
*/
public abstract class SingleLinkageHACStrategy implements ClusteringStrategy {
@Override
public int[] clusterize(float sim[][]) {
int[] I = new int[sim.length];
ClusterElement[] nearBestMatch = new ClusterElement[sim.length];
ClusterElement[][] C = new ClusterElement[sim.length][];
for (int n = 0; n < sim.length; n++) {
C[n] = new ClusterElement[n];
float maxSim = -1;
if (C[n].length != 0) {
maxSim = sim[n][0];
}
//if all sims are under 0, no of them will be chosen,
//so the first is as good as any other
int maxIndex = 0;
for (int i = 0; i < n; i++) {
C[n][i] = new ClusterElement(sim[n][i], i);
if (Math.max(maxSim, sim[n][i]) != maxSim) {
maxSim = sim[n][i];
maxIndex = i;
}
}
if (C[n].length != 0) {
nearBestMatch[n] = C[n][maxIndex];
} else {
nearBestMatch[n] = null;
}
I[n] = n;
}
int i1 = -1, i2 = -1;
for (int n = 1; n < sim.length; n++) {
i1 = argMaxSequenceIndexExcludeSame(nearBestMatch, I);
if (i1 == -1) {
continue;
}
i2 = I[nearBestMatch[i1].getIndex()];
if (i1 == i2) {
continue;
}
float simil = (i1 > i2) ? C[i1][i2].getSim() : C[i2][i1].getSim();
if (simil < 0) {
return I;
}
for (int i = 0; i < I.length; i++) {
if (I[i] == i && i != i1 && i != i2) {
if (i1 > i && i2 > i) {
C[i1][i].setSim( SIM(C[i1][i].getSim(), C[i2][i].getSim()) );
} else if (i1 > i && i2 < i) {
C[i1][i].setSim( SIM(C[i1][i].getSim(), C[i][i2].getSim()) );
} else if (i1 < i && i2 > i) {
C[i][i1].setSim( SIM(C[i][i1].getSim(), C[i2][i].getSim()) );
} else //if(i1<i && i2<i)
{
C[i][i1].setSim( SIM(C[i][i1].getSim(), C[i][i2].getSim()) );
}
}
if (I[i] == i2) {
I[i] = i1;
}
}
nearBestMatch[i1] = argMaxElementWithConstraints(C[n], I, n);
}
return I;
}
protected int argMaxSequenceIndexExcludeSame(ClusterElement[] nearBestMatch, int[] I) {
float maxval = Float.NEGATIVE_INFINITY;
int maxvalindex = -1;
for (int i = 0; i < nearBestMatch.length; i++) {
if (I[i] != i) {
continue;
}
if (nearBestMatch[i] == null) {
continue;
}
if (i == I[nearBestMatch[i].getIndex()]) {
continue;
}
if (maxval < nearBestMatch[i].getSim()) {
maxval = nearBestMatch[i].getSim();
maxvalindex = i;
}
}
return maxvalindex;
}
protected ClusterElement argMaxElementWithConstraints(ClusterElement[] Cn,
int[] I, int forbidden) {
float maxval = -1;
ClusterElement retEl = null;
for (int i = 0; i < Cn.length; i++) {
if (i == forbidden) {
continue;
}
if (I[i] != i) {
continue;
}
if (Cn[i].getSim() > maxval) {
maxval = Cn[i].getSim();
retEl = Cn[i];
}
}
return retEl;
}
protected abstract float SIM(float a, float b);
}
|
package ui;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.egit.github.core.IRepositoryIdProvider;
import org.eclipse.egit.github.core.RepositoryId;
import service.ServiceManager;
import storage.DataManager;
import ui.components.Dialog;
import ui.components.StatusBar;
import ui.issuecolumn.ColumnControl;
import util.DialogMessage;
public class LoginDialog extends Dialog<Boolean> {
private static final String DIALOG_TITLE = "GitHub Login";
private static final int DIALOG_HEIGHT = 200;
private static final int DIALOG_WIDTH = 570;
private static final String LABEL_REPO = "Repository:";
private static final String LABEL_GITHUB = "github.com /";
private static final String FIELD_DEFAULT_REPO_OWNER = "<owner/organization>";
private static final String FIELD_DEFAULT_REPO_NAME = "<repository>";
private static final String PASSWORD_LABEL = "Password:";
private static final String USERNAME_LABEL = "Username:";
private static final String BUTTON_SIGN_IN = "Sign in";
private static final Logger logger = LogManager.getLogger(LoginDialog.class.getName());
private TextField repoOwnerField;
private TextField repoNameField;
private TextField usernameField;
private PasswordField passwordField;
private ColumnControl columns;
private Button loginButton;
public LoginDialog(Stage parentStage, ColumnControl columns) {
super(parentStage);
this.columns = columns;
}
@Override
protected void onClose(WindowEvent e) {
completeResponse(false);
}
@Override
protected Parent content() {
setTitle(DIALOG_TITLE);
setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
setStageStyle(StageStyle.UTILITY);
GridPane grid = new GridPane();
setupGridPane(grid);
Label repoLabel = new Label(LABEL_REPO);
grid.add(repoLabel, 0, 0);
Label githubLabel = new Label(LABEL_GITHUB);
grid.add(githubLabel, 1, 0);
repoOwnerField = new TextField(FIELD_DEFAULT_REPO_OWNER);
repoOwnerField.setPrefWidth(140);
grid.add(repoOwnerField, 2, 0);
Label slash = new Label("/");
grid.add(slash, 3, 0);
repoNameField = new TextField(FIELD_DEFAULT_REPO_NAME);
repoNameField.setPrefWidth(250);
grid.add(repoNameField, 4, 0);
Label usernameLabel = new Label(USERNAME_LABEL);
grid.add(usernameLabel, 0, 1);
usernameField = new TextField();
grid.add(usernameField, 1, 1, 4, 1);
Label passwordLabel = new Label(PASSWORD_LABEL);
grid.add(passwordLabel, 0, 2);
passwordField = new PasswordField();
grid.add(passwordField, 1, 2, 4, 1);
populateSavedFields();
repoOwnerField.setOnAction(this::login);
repoNameField.setOnAction(this::login);
usernameField.setOnAction(this::login);
passwordField.setOnAction(this::login);
HBox buttons = new HBox(10);
buttons.setAlignment(Pos.BOTTOM_RIGHT);
loginButton = new Button(BUTTON_SIGN_IN);
loginButton.setOnAction(this::login);
buttons.getChildren().add(loginButton);
grid.add(buttons, 4, 3);
return grid;
}
/**
* Fills in fields which have values at this point.
*/
private void populateSavedFields() {
Optional<RepositoryId> lastViewed = DataManager.getInstance().getLastViewedRepository();
if (lastViewed.isPresent()) {
repoOwnerField.setText(lastViewed.get().getOwner());
repoNameField.setText(lastViewed.get().getName());
}
String lastLoginName = DataManager.getInstance().getLastLoginUsername();
if (!lastLoginName.isEmpty()) {
usernameField.setText(lastLoginName);
}
// Change focus depending on what fields are present
Platform.runLater(() -> {
if (!lastLoginName.isEmpty()) {
passwordField.requestFocus();
} else if (lastViewed.isPresent()) {
usernameField.requestFocus();
}
});
}
/**
* Configures the central grid pane before it's used.
* @param grid
*/
private static void setupGridPane(GridPane grid) {
grid.setAlignment(Pos.CENTER);
grid.setHgap(7);
grid.setVgap(10);
grid.setPadding(new Insets(25));
grid.setPrefSize(390, 100);
grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
applyColumnConstraints(grid, 20, 16, 33, 2, 29);
}
/**
* A variadic function that applies percentage-width column constraints to
* the given grid pane.
* @param grid the grid pane to apply column constraints to
* @param values an array of integer values which should add up to 100
*/
private static void applyColumnConstraints(GridPane grid, int... values) {
// The values should sum up to 100%
int sum = 0;
for (int i=0; i<values.length; i++) {
sum += values[i];
}
assert sum == 100 : "Column constraints should sum up to 100%!";
// Apply constraints to grid
ColumnConstraints column;
for (int i=0; i<values.length; i++) {
column = new ColumnConstraints();
column.setPercentWidth(values[i]);
grid.getColumnConstraints().add(column);
}
}
private void login(Event e) {
// Resolve username and password
String owner = repoOwnerField.getText();
String repo = repoNameField.getText();
String username = usernameField.getText();
String password = passwordField.getText();
// If either field is empty, try to load credentials.txt
if (username.isEmpty() || password.isEmpty()) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("credentials.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
if (username.isEmpty()) {
username = line;
} else {
password = line;
}
}
logger.info("Logged in using credentials.txt");
} catch (Exception ex) {
logger.info("Failed to find or open credentials.txt");
}
}
// Update UI
enableElements(false);
// Run blocking operations in the background
StatusBar.displayMessage("Signing in at GitHub...");
boolean couldLogIn = ServiceManager.getInstance().login(username, password);
Task<Boolean> task = new Task<Boolean>() {
@Override
protected Boolean call() throws Exception {
StatusBar.displayMessage("Signed in; loading data...");
boolean loadSuccess = loadRepository(owner, repo);
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(()->{
columns.resumeColumns();
latch.countDown();
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return loadSuccess;
}
};
task.setOnSucceeded(wse -> {
if (task.getValue()) {
StatusBar.displayMessage("Issues loaded successfully! " + ServiceManager.getInstance().getRemainingRequests() + " requests remaining out of " + ServiceManager.getInstance().getRequestLimit() + ".");
completeResponse(true);
close();
} else {
handleError("Issues failed to load. Please try again.");
}
});
task.setOnFailed(wse -> {
Throwable thrown = task.getException();
logger.error(thrown.getLocalizedMessage(), thrown);
handleError("An error occurred: " + task.getException());
});
if (couldLogIn) {
// Save login details only on successful login
DataManager.getInstance().setLastLoginUsername(username);
DialogMessage.showProgressDialog(task, "Loading issues from " + owner + "/" + repo + "...");
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
} else {
handleError("Failed to sign in. Please try again.");
}
}
private void handleError(String message) {
Platform.runLater(()->{
enableElements(true);
StatusBar.displayMessage(message);
DialogMessage.showWarningDialog("Warning", message);
});
}
private void enableElements(boolean enable) {
boolean disable = !enable;
loginButton.setDisable(disable);
repoOwnerField.setDisable(disable);
repoNameField.setDisable(disable);
usernameField.setDisable(disable);
passwordField.setDisable(disable);
}
private boolean loadRepository(String owner, String repoName) throws IOException {
boolean loaded = ServiceManager.getInstance().setupRepository(owner, repoName);
ServiceManager.getInstance().setupAndStartModelUpdate();
IRepositoryIdProvider currRepo = ServiceManager.getInstance().getRepoId();
if (currRepo != null) {
String repoId = currRepo.generateId();
DataManager.getInstance().addToLastViewedRepositories(repoId);
}
return loaded;
}
}
|
package edu.umd.cs.findbugs;
import java.util.*;
/**
* Singleton responsible for returning localized strings for information
* returned to the user.
*
* @author David Hovemeyer
*/
public class I18N {
private final ResourceBundle annotationDescriptionBundle;
private final HashMap<String, BugPattern> bugPatternMap;
private final HashMap<String, BugCode> bugCodeMap;
private I18N() {
annotationDescriptionBundle = ResourceBundle.getBundle("edu.umd.cs.findbugs.FindBugsAnnotationDescriptions");
bugPatternMap = new HashMap<String, BugPattern>();
bugCodeMap = new HashMap<String, BugCode>();
}
private static final I18N theInstance = new I18N();
/**
* Get the single object instance.
*/
public static I18N instance() {
return theInstance;
}
/**
* Register a BugPattern.
* @param bugPattern the BugPattern
*/
public void registerBugPattern(BugPattern bugPattern) {
bugPatternMap.put(bugPattern.getType(), bugPattern);
}
/**
* Look up bug pattern.
* @param bugType the bug type for the bug pattern
* @return the BugPattern, or null if it can't be found
*/
public BugPattern lookupBugPattern(String bugType) {
return bugPatternMap.get(bugType);
}
/**
* Register a BugCode.
* @param bugCode the BugCode
*/
public void registerBugCode(BugCode bugCode) {
bugCodeMap.put(bugCode.getAbbrev(), bugCode);
}
/**
* Get a message string.
* This is a format pattern for describing an entire bug instance in a single line.
* @param key which message to retrieve
*/
public String getMessage(String key) {
BugPattern bugPattern = bugPatternMap.get(key);
if (bugPattern == null)
return "Error: missing bug pattern for key " + key;
return bugPattern.getAbbrev() + ": " + bugPattern.getLongDescription();
}
/**
* Get a short message string.
* This is a concrete string (not a format pattern) which briefly describes
* the type of bug, without mentioning particular a particular class/method/field.
* @param key which short message to retrieve
*/
public String getShortMessage(String key) {
BugPattern bugPattern = bugPatternMap.get(key);
if (bugPattern == null)
return "Error: missing bug pattern for key " + key;
return bugPattern.getAbbrev() + ": " + bugPattern.getShortDescription();
}
/**
* Get an HTML document describing the bug pattern for given key in detail.
* @param key which HTML details for retrieve
*/
public String getDetailHTML(String key) {
BugPattern bugPattern = bugPatternMap.get(key);
if (bugPattern == null)
return "Error: missing bug pattern for key " + key;
return bugPattern.getDetailHTML();
}
/**
* Get an annotation description string.
* This is a format pattern which will describe a BugAnnotation in the
* context of a particular bug instance. Its single format argument
* is the BugAnnotation.
* @param key the annotation description to retrieve
*/
public String getAnnotationDescription(String key) {
return annotationDescriptionBundle.getString(key);
}
/**
* Get a description for given "bug type".
* FIXME: this is referred to elsewhere as the "bug code" or "bug abbrev".
* Should make the terminology consistent everywhere.
* In this case, the bug type refers to the short prefix code prepended to
* the long and short bug messages.
* @param shortBugType the short bug type code
* @return the description of that short bug type code means
*/
public String getBugTypeDescription(String shortBugType) {
BugCode bugCode = bugCodeMap.get(shortBugType);
if (bugCode == null)
return "Error: missing bug code for key " + shortBugType;
return bugCode.getDescription();
}
}
// vim:ts=4
|
package jolie.runtime;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class FaultException extends Exception
{
private static final long serialVersionUID = jolie.lang.Constants.serialVersionUID();
final private String faultName;
final private Value value;
public FaultException( String faultName, Throwable t )
{
super();
this.faultName = faultName;
this.value = Value.create( t.getMessage() );
ByteArrayOutputStream bs = new ByteArrayOutputStream();
t.printStackTrace( new PrintStream( bs ) );
this.value.getNewChild( "stackTrace" ).setValue( bs.toString() );
}
public FaultException( Throwable t )
{
super();
this.faultName = t.getClass().getSimpleName();
this.value = Value.create( t.getMessage() );
ByteArrayOutputStream bs = new ByteArrayOutputStream();
t.printStackTrace( new PrintStream( bs ) );
this.value.getNewChild( "stackTrace" ).setValue( bs.toString() );
}
public FaultException( String faultName, String message )
{
super();
this.faultName = faultName;
this.value = Value.create( message );
}
public FaultException( String faultName, Value value )
{
super();
this.faultName = faultName;
this.value = value;
}
public FaultException( String faultName )
{
super();
this.faultName = faultName;
this.value = Value.create();
}
@Override
public String getMessage()
{
StringBuilder builder = new StringBuilder();
builder.append( faultName );
builder.append( ": " );
builder.append( value.strValue() );
return builder.toString();
}
public Value value()
{
return value;
}
public String faultName()
{
return faultName;
}
}
|
package org.jpos.iso;
import org.jpos.iso.header.BaseHeader;
import org.jpos.iso.packager.XMLPackager;
import org.jpos.util.Loggeable;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
/**
* implements <b>Composite</b>
* whithin a <b>Composite pattern</b>
*
* @author apr@cs.com.uy
* @version $Id$
* @see ISOComponent
* @see ISOField
*/
@SuppressWarnings("unchecked")
public class ISOMsg extends ISOComponent
implements Cloneable, Loggeable, Externalizable
{
protected Map<Integer,Object> fields;
protected int maxField;
protected ISOPackager packager;
protected boolean dirty, maxFieldDirty;
protected int direction;
protected ISOHeader header;
protected byte[] trailer;
protected int fieldNumber = -1;
public static final int INCOMING = 1;
public static final int OUTGOING = 2;
private static final long serialVersionUID = 4306251831901413975L;
private WeakReference sourceRef;
/**
* Creates an ISOMsg
*/
public ISOMsg () {
fields = new TreeMap<>();
maxField = -1;
dirty = true;
maxFieldDirty=true;
direction = 0;
header = null;
trailer = null;
}
/**
* Creates a nested ISOMsg
* @param fieldNumber (in the outter ISOMsg) of this nested message
*/
public ISOMsg (int fieldNumber) {
this();
setFieldNumber (fieldNumber);
}
/**
* changes this Component field number<br>
* Use with care, this method does not change
* any reference held by a Composite.
* @param fieldNumber new field number
*/
@Override
public void setFieldNumber (int fieldNumber) {
this.fieldNumber = fieldNumber;
}
/**
* Creates an ISOMsg with given mti
* @param mti Msg's MTI
*/
@SuppressWarnings("PMD.EmptyCatchBlock")
public ISOMsg (String mti) {
this();
try {
setMTI (mti);
} catch (ISOException ignored) {
// Should never happen as this is not an inner message
}
}
/**
* Sets the direction information related to this message
* @param direction can be either ISOMsg.INCOMING or ISOMsg.OUTGOING
*/
public void setDirection(int direction) {
this.direction = direction;
}
/**
* Sets an optional message header image
* @param b header image
*/
public void setHeader(byte[] b) {
header = new BaseHeader (b);
}
public void setHeader (ISOHeader header) {
this.header = header;
}
/**
* get optional message header image
* @return message header image (may be null)
*/
public byte[] getHeader() {
return header != null ? header.pack() : null;
}
/**
* Sets optional trailer data.
* <p/>
* Note: The trailer data requires a customised channel that explicitily handles the trailer data from the ISOMsg.
*
* @param trailer The trailer data.
* @see BaseChannel#getMessageTrailer(ISOMsg).
* @see BaseChannel#sendMessageTrailer(ISOMsg, byte[]).
*/
public void setTrailer(byte[] trailer) {
this.trailer = trailer;
}
/**
* Get optional trailer image.
*
* @return message trailer imange (may be null)
*/
public byte[] getTrailer() {
return this.trailer;
}
/**
* Return this messages ISOHeader
* @return header associated with this ISOMsg, can be null
*/
public ISOHeader getISOHeader() {
return header;
}
/**
* @return the direction (ISOMsg.INCOMING or ISOMsg.OUTGOING)
* @see ISOChannel
*/
public int getDirection() {
return direction;
}
/**
* @return true if this message is an incoming message
* @see ISOChannel
*/
public boolean isIncoming() {
return direction == INCOMING;
}
/**
* @return true if this message is an outgoing message
* @see ISOChannel
*/
public boolean isOutgoing() {
return direction == OUTGOING;
}
/**
* @return the max field number associated with this message
*/
@Override
public int getMaxField() {
if (maxFieldDirty)
recalcMaxField();
return maxField;
}
private void recalcMaxField() {
maxField = 0;
for (Object obj : fields.keySet()) {
if (obj instanceof Integer)
maxField = Math.max(maxField, ((Integer) obj).intValue());
}
maxFieldDirty = false;
}
/**
* @param p - a peer packager
*/
public void setPackager (ISOPackager p) {
packager = p;
}
/**
* @return the peer packager
*/
public ISOPackager getPackager () {
return packager;
}
/**
* Set a field within this message
* @param c - a component
*/
public void set (ISOComponent c) throws ISOException {
if (c != null) {
Integer i = (Integer) c.getKey();
fields.put (i, c);
if (i > maxField)
maxField = i;
dirty = true;
}
}
/**
* Creates an ISOField associated with fldno within this ISOMsg.
*
* @param fldno field number
* @param value field value
*/
public void set(int fldno, String value) {
if (value == null) {
unset(fldno);
return;
}
try {
if (!(packager instanceof ISOBasePackager)) {
// No packager is available, we can't tell what the field
// might be, so treat as a String!
set(new ISOField(fldno, value));
}
else {
// This ISOMsg has a packager, so use it
Object obj = ((ISOBasePackager) packager).getFieldPackager(fldno);
if (obj instanceof ISOBinaryFieldPackager) {
set(new ISOBinaryField(fldno, ISOUtil.hex2byte(value)));
} else {
set(new ISOField(fldno, value));
}
}
} catch (ISOException ex) {}; //NOPMD: never happens for the given arguments of set methods
}
/**
* Creates an ISOField associated with fldno within this ISOMsg.
*
* @param fpath dot-separated field path (i.e. 63.2)
* @param value field value
*/
public void set(String fpath, String value) {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
for (;;) {
int fldno = parseInt(st.nextToken());
if (st.hasMoreTokens()) {
Object obj = m.getValue(fldno);
if (obj instanceof ISOMsg)
m = (ISOMsg) obj;
else
/**
* we need to go deeper, however, if the value == null then
* there is nothing to do (unset) at the lower levels, so break now and save some processing.
*/
if (value == null) {
break;
} else {
try {
// We have a value to set, so adding a level to hold it is sensible.
m.set(m = new ISOMsg (fldno));
} catch (ISOException ex) {} //NOPMD: never happens for the given arguments of set methods
}
} else {
m.set(fldno, value);
break;
}
}
}
/**
* Creates an ISOField associated with fldno within this ISOMsg
* @param fpath dot-separated field path (i.e. 63.2)
* @param c component
* @throws ISOException on error
*/
public void set (String fpath, ISOComponent c) throws ISOException {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
for (;;) {
int fldno = parseInt(st.nextToken());
if (st.hasMoreTokens()) {
Object obj = m.getValue(fldno);
if (obj instanceof ISOMsg)
m = (ISOMsg) obj;
else
/*
* we need to go deeper, however, if the value == null then
* there is nothing to do (unset) at the lower levels, so break now and save some processing.
*/
if (c == null) {
break;
} else {
// We have a value to set, so adding a level to hold it is sensible.
m.set (m = new ISOMsg (fldno));
}
} else {
m.set (c);
break;
}
}
}
/**
* Creates an ISOField associated with fldno within this ISOMsg.
*
* @param fpath dot-separated field path (i.e. 63.2)
* @param value binary field value
*/
public void set(String fpath, byte[] value) {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
for (;;) {
int fldno = parseInt(st.nextToken());
if (st.hasMoreTokens()) {
Object obj = m.getValue(fldno);
if (obj instanceof ISOMsg)
m = (ISOMsg) obj;
else
try {
m.set(m = new ISOMsg (fldno));
} catch (ISOException ex) {} //NOPMD: never happens for the given arguments of set methods
} else {
m.set(fldno, value);
break;
}
}
}
/**
* Creates an ISOBinaryField associated with fldno within this ISOMsg.
*
* @param fldno field number
* @param value field value
*/
public void set(int fldno, byte[] value) {
if (value == null) {
unset(fldno);
return;
}
try {
set(new ISOBinaryField(fldno, value));
} catch (ISOException ex) {}; //NOPMD: never happens for the given arguments of set methods
}
/**
* Unset a field if it exists, otherwise ignore.
* @param fldno - the field number
*/
@Override
public void unset (int fldno) {
if (fields.remove (fldno) != null)
dirty = maxFieldDirty = true;
}
/**
* Unsets several fields at once
* @param flds - array of fields to be unset from this ISOMsg
*/
public void unset (int ... flds) {
for (int fld : flds)
unset(fld);
}
/**
* Unset a field referenced by a fpath if it exists, otherwise ignore.
*
* @param fpath dot-separated field path (i.e. 63.2)
*/
public void unset(String fpath) {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
ISOMsg lastm = m;
int fldno = -1 ;
int lastfldno ;
for (;;) {
lastfldno = fldno;
fldno = parseInt(st.nextToken());
if (st.hasMoreTokens()) {
Object obj = m.getValue(fldno);
if (obj instanceof ISOMsg) {
lastm = m;
m = (ISOMsg) obj;
}
else {
// No real way of unset further subfield, exit.
break;
}
} else {
m.unset(fldno);
if (!m.hasFields() && lastfldno != -1) {
lastm.unset(lastfldno);
}
break;
}
}
}
/**
* Unset a a set of fields referenced by fpaths if any ot them exist, otherwise ignore.
*
* @param fpaths dot-separated field paths (i.e. 63.2)
*/
public void unset(String ... fpaths) {
for (String fpath : fpaths) {
unset(fpath);
}
}
/**
* In order to interchange <b>Composites</b> and <b>Leafs</b> we use
* getComposite(). A <b>Composite component</b> returns itself and
* a Leaf returns null.
*
* @return ISOComponent
*/
@Override
public ISOComponent getComposite() {
return this;
}
/**
* setup BitMap
* @exception ISOException on error
*/
public void recalcBitMap () throws ISOException {
if (!dirty)
return;
int mf = Math.min (getMaxField(), 192);
BitSet bmap = new BitSet (mf+62 >>6 <<6);
for (int i=1; i<=mf; i++)
if (fields.get (i) != null)
bmap.set (i);
set (new ISOBitMap (-1, bmap));
dirty = false;
}
/**
* clone fields
* @return copy of fields
*/
@Override
public Map getChildren() {
return (Map) ((TreeMap)fields).clone();
}
/**
* pack the message with the current packager
* @return the packed message
* @exception ISOException
*/
@Override
public byte[] pack() throws ISOException {
synchronized (this) {
recalcBitMap();
return packager.pack(this);
}
}
/**
* unpack a message
* @param b - raw message
* @return consumed bytes
* @exception ISOException
*/
@Override
public int unpack(byte[] b) throws ISOException {
synchronized (this) {
return packager.unpack(this, b);
}
}
@Override
public void unpack (InputStream in) throws IOException, ISOException {
synchronized (this) {
packager.unpack(this, in);
}
}
/**
* dump the message to a PrintStream. The output is sorta
* XML, intended to be easily parsed.
* <br>
* Each component is responsible for its own dump function,
* ISOMsg just calls dump on every valid field.
* @param p - print stream
* @param indent - optional indent string
*/
@Override
public void dump (PrintStream p, String indent) {
ISOComponent c;
p.print (indent + "<" + XMLPackager.ISOMSG_TAG);
switch (direction) {
case INCOMING:
p.print (" direction=\"incoming\"");
break;
case OUTGOING:
p.print (" direction=\"outgoing\"");
break;
}
if (fieldNumber != -1)
p.print (" "+XMLPackager.ID_ATTR +"=\""+fieldNumber +"\"");
p.println (">");
String newIndent = indent + " ";
if (getPackager() != null) {
p.println (
newIndent
+ "<!-- " + getPackager().getDescription() + " -->"
);
}
if (header instanceof Loggeable)
((Loggeable) header).dump (p, newIndent);
for (int i : fields.keySet()) {
if (i >= 0) {
if ((c = (ISOComponent) fields.get(i)) != null)
c.dump(p, newIndent);
}
}
p.println (indent + "</" + XMLPackager.ISOMSG_TAG+">");
}
/**
* get the component associated with the given field number
* @param fldno the Field Number
* @return the Component
*/
public ISOComponent getComponent(int fldno) {
return (ISOComponent) fields.get(fldno);
}
/**
* Return the object value associated with the given field number
* @param fldno the Field Number
* @return the field Object
*/
public Object getValue(int fldno) {
ISOComponent c = getComponent(fldno);
try {
return c != null ? c.getValue() : null;
} catch (ISOException ex) {
return null; //never happens for the given arguments of getValue method
}
}
/**
* Return the object value associated with the given field path
* @param fpath field path
* @return the field Object (may be null)
* @throws ISOException on error
*/
public Object getValue (String fpath) throws ISOException {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
Object obj;
for (;;) {
int fldno = parseInt(st.nextToken());
obj = m.getValue (fldno);
if (obj==null){
// The user will always get a null value for an incorrect path or path not present in the message
// no point having the ISOException thrown for fields that were not received.
break;
}
if (st.hasMoreTokens()) {
if (obj instanceof ISOMsg) {
m = (ISOMsg) obj;
}
else
throw new ISOException ("Invalid path '" + fpath + "'");
} else
break;
}
return obj;
}
/**
* get the component associated with the given field number
* @param fpath field path
* @return the Component
* @throws ISOException on error
*/
public ISOComponent getComponent (String fpath) throws ISOException {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
ISOComponent obj;
for (;;) {
int fldno = parseInt(st.nextToken());
obj = m.getComponent(fldno);
if (st.hasMoreTokens()) {
if (obj instanceof ISOMsg) {
m = (ISOMsg) obj;
}
else
break; // 'Quick' exit if hierachy is not present.
} else
break;
}
return obj;
}
/**
* Return the String value associated with the given ISOField number
* @param fldno the Field Number
* @return field's String value
*/
public String getString (int fldno) {
String s = null;
if (hasField (fldno)) {
Object obj = getValue(fldno);
if (obj instanceof String)
s = (String) obj;
else if (obj instanceof byte[])
s = ISOUtil.hexString((byte[]) obj);
}
return s;
}
/**
* Return the String value associated with the given field path
* @param fpath field path
* @return field's String value (may be null)
*/
public String getString (String fpath) {
String s = null;
try {
Object obj = getValue(fpath);
if (obj instanceof String)
s = (String) obj;
else if (obj instanceof byte[])
s = ISOUtil.hexString ((byte[]) obj);
} catch (ISOException e) {
return null;
}
return s;
}
/**
* Return the byte[] value associated with the given ISOField number
* @param fldno the Field Number
* @return field's byte[] value or null if ISOException or UnsupportedEncodingException happens
*/
public byte[] getBytes (int fldno) {
byte[] b = null;
if (hasField (fldno)) {
Object obj = getValue(fldno);
if (obj instanceof String)
b = ((String) obj).getBytes(ISOUtil.CHARSET);
else if (obj instanceof byte[])
b = (byte[]) obj;
}
return b;
}
/**
* Return the String value associated with the given field path
* @param fpath field path
* @return field's byte[] value (may be null)
*/
public byte[] getBytes (String fpath) {
byte[] b = null;
try {
Object obj = getValue(fpath);
if (obj instanceof String)
b = ((String) obj).getBytes(ISOUtil.CHARSET);
else if (obj instanceof byte[])
b = (byte[]) obj;
} catch (ISOException ignored) {
return null;
}
return b;
}
/**
* Check if a given field is present
* @param fldno the Field Number
* @return boolean indicating the existence of the field
*/
public boolean hasField(int fldno) {
return fields.get(fldno) != null;
}
/**
* Check if all fields are present
* @param fields an array of fields to check for presence
* @return true if all fields are present
*/
public boolean hasFields (int[] fields) {
for (int field : fields)
if (!hasField(field))
return false;
return true;
}
/**
* Check if the message has any of these fields
* @param fields an array of fields to check for presence
* @return true if at least one field is present
*/
public boolean hasAny (int[] fields) {
for (int field : fields)
if (hasField(field))
return true;
return false;
}
/**
* Check if the message has any of these fields
* @param fields to check for presence
* @return true if at least one field is present
*/
public boolean hasAny (String... fields) {
for (String field : fields)
if (hasField (field))
return true;
return false;
}
/**
* Check if a field indicated by a fpath is present
* @param fpath dot-separated field path (i.e. 63.2)
* @return true if field present
*/
public boolean hasField (String fpath) {
StringTokenizer st = new StringTokenizer (fpath, ".");
ISOMsg m = this;
for (;;) {
int fldno = parseInt(st.nextToken());
if (st.hasMoreTokens()) {
Object obj = m.getValue(fldno);
if (obj instanceof ISOMsg) {
m = (ISOMsg) obj;
}
else {
// No real way of checking for further subfields, return false, perhaps should be ISOException?
return false;
}
} else {
return m.hasField(fldno);
}
}
}
/**
* @return true if ISOMsg has at least one field
*/
public boolean hasFields () {
return !fields.isEmpty();
}
/**
* Don't call setValue on an ISOMsg. You'll sure get
* an ISOException. It's intended to be used on Leafs
* @param obj
* @throws org.jpos.iso.ISOException
* @see ISOField
* @see ISOException
*/
@Override
public void setValue(Object obj) throws ISOException {
throw new ISOException ("setValue N/A in ISOMsg");
}
@Override
public Object clone() {
try {
ISOMsg m = (ISOMsg) super.clone();
m.fields = (TreeMap) ((TreeMap) fields).clone();
if (header != null)
m.header = (ISOHeader) header.clone();
if (trailer != null)
m.trailer = trailer.clone();
for (Integer k : fields.keySet()) {
ISOComponent c = (ISOComponent) m.fields.get(k);
if (c instanceof ISOMsg)
m.fields.put(k, ((ISOMsg) c).clone());
}
return m;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/**
* Partially clone an ISOMsg
* @param fields int array of fields to go
* @return new ISOMsg instance
*/
@SuppressWarnings("PMD.EmptyCatchBlock")
public Object clone(int ... fields) {
try {
ISOMsg m = (ISOMsg) super.clone();
m.fields = new TreeMap();
for (int field : fields) {
if (hasField(field)) {
try {
m.set(getComponent(field));
} catch (ISOException ignored) {
// should never happen
}
}
}
return m;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/**
* Partially clone an ISOMsg by field paths
* @param fpaths string array of field paths to copy
* @return new ISOMsg instance
*/
public ISOMsg clone(String ... fpaths) {
try {
ISOMsg m = (ISOMsg) super.clone();
m.fields = new TreeMap();
for (String fpath : fpaths) {
try {
ISOComponent component = getComponent(fpath);
if (component instanceof ISOMsg) {
m.set(fpath, (ISOMsg)((ISOMsg)component).clone());
} else if (component != null) {
m.set(fpath, component);
}
} catch (ISOException ignored) {
//should never happen
}
}
return m;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/**
* add all fields present on received parameter to this ISOMsg<br>
* please note that received fields take precedence over
* existing ones (simplifying card agent message creation
* and template handling)
* @param m ISOMsg to merge
*/
@SuppressWarnings("PMD.EmptyCatchBlock")
public void merge (ISOMsg m) {
for (int i : m.fields.keySet()) {
try {
if (i >= 0 && m.hasField(i))
set(m.getComponent(i));
} catch (ISOException ignored) {
// should never happen
}
}
}
/**
* @return a string suitable for a log
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder();
if (isIncoming())
s.append(" In: ");
else if (isOutgoing())
s.append("Out: ");
else
s.append(" ");
s.append(getString(0));
if (hasField(11)) {
s.append(' ');
s.append(getString(11));
}
if (hasField(41)) {
s.append(' ');
s.append(getString(41));
}
return s.toString();
}
@Override
public Object getKey() throws ISOException {
if (fieldNumber != -1)
return fieldNumber;
throw new ISOException ("This is not a subField");
}
@Override
public Object getValue() {
return this;
}
/**
* @return true on inner messages
*/
public boolean isInner() {
return fieldNumber > -1;
}
/**
* @param mti new MTI
* @exception ISOException if message is inner message
*/
public void setMTI (String mti) throws ISOException {
if (isInner())
throw new ISOException ("can't setMTI on inner message");
set (new ISOField (0, mti));
}
/**
* moves a field (renumber)
* @param oldFieldNumber old field number
* @param newFieldNumber new field number
* @throws ISOException on error
*/
public void move (int oldFieldNumber, int newFieldNumber)
throws ISOException
{
ISOComponent c = getComponent (oldFieldNumber);
unset (oldFieldNumber);
if (c != null) {
c.setFieldNumber (newFieldNumber);
set (c);
} else
unset (newFieldNumber);
}
@Override
public int getFieldNumber () {
return fieldNumber;
}
/**
* @return true is message has MTI field
* @exception ISOException if this is an inner message
*/
public boolean hasMTI() throws ISOException {
if (isInner())
throw new ISOException ("can't hasMTI on inner message");
else
return hasField(0);
}
/**
* @return current MTI
* @exception ISOException on inner message or MTI not set
*/
public String getMTI() throws ISOException {
if (isInner())
throw new ISOException ("can't getMTI on inner message");
else if (!hasField(0))
throw new ISOException ("MTI not available");
return (String) getValue(0);
}
/**
* @return true if message "seems to be" a request
* @exception ISOException on MTI not set
*/
public boolean isRequest() throws ISOException {
return Character.getNumericValue(getMTI().charAt (2))%2 == 0;
}
/**
* @return true if message "seems not to be" a request
* @exception ISOException on MTI not set
*/
public boolean isResponse() throws ISOException {
return !isRequest();
}
/**
* @return true if message is Retransmission
* @exception ISOException on MTI not set
*/
public boolean isRetransmission() throws ISOException {
return getMTI().charAt(3) == '1';
}
/**
* sets an appropiate response MTI.
*
* i.e. 0100 becomes 0110<br>
* i.e. 0201 becomes 0210<br>
* i.e. 1201 becomes 1210<br>
* @exception ISOException on MTI not set or it is not a request
*/
public void setResponseMTI() throws ISOException {
if (!isRequest())
throw new ISOException ("not a request - can't set response MTI");
String mti = getMTI();
char c1 = mti.charAt(3);
char c2 = '0';
switch (c1)
{
case '0' :
case '1' : c2='0';break;
case '2' :
case '3' : c2='2';break;
case '4' :
case '5' : c2='4';break;
}
set (new ISOField (0,
mti.substring(0,2)
+(Character.getNumericValue(getMTI().charAt (2))+1) + c2
)
);
}
/**
* sets an appropiate retransmission MTI<br>
* @exception ISOException on MTI not set or it is not a request
*/
public void setRetransmissionMTI() throws ISOException {
if (!isRequest())
throw new ISOException ("not a request");
set (new ISOField (0, getMTI().substring(0,3) + "1"));
}
protected void writeHeader (ObjectOutput out) throws IOException {
int len = header.getLength();
if (len > 0) {
out.writeByte ('H');
out.writeShort (len);
out.write (header.pack());
}
}
protected void readHeader (ObjectInput in)
throws IOException, ClassNotFoundException
{
byte[] b = new byte[in.readShort()];
in.readFully (b);
setHeader (b);
}
protected void writePackager(ObjectOutput out) throws IOException {
out.writeByte('P');
String pclass = packager.getClass().getName();
byte[] b = pclass.getBytes();
out.writeShort(b.length);
out.write(b);
}
protected void readPackager(ObjectInput in) throws IOException,
ClassNotFoundException {
byte[] b = new byte[in.readShort()];
in.readFully(b);
try {
Class mypClass = Class.forName(new String(b));
ISOPackager myp = (ISOPackager) mypClass.newInstance();
setPackager(myp);
} catch (Exception e) {
setPackager(null);
}
}
protected void writeDirection (ObjectOutput out) throws IOException {
out.writeByte ('D');
out.writeByte (direction);
}
protected void readDirection (ObjectInput in)
throws IOException, ClassNotFoundException
{
direction = in.readByte();
}
@Override
public void writeExternal (ObjectOutput out) throws IOException {
out.writeByte (0); // reserved for future expansion (version id)
out.writeShort (fieldNumber);
if (header != null)
writeHeader (out);
if (packager != null)
writePackager(out);
if (direction > 0)
writeDirection (out);
// List keySet = new ArrayList (fields.keySet());
// Collections.sort (keySet);
for (Object o : fields.values()) {
ISOComponent c = (ISOComponent) o;
if (c instanceof ISOMsg) {
writeExternal(out, 'M', c);
} else if (c instanceof ISOBinaryField) {
writeExternal(out, 'B', c);
} else if (c instanceof ISOAmount) {
writeExternal(out, 'A', c);
} else if (c instanceof ISOField) {
writeExternal(out, 'F', c);
}
}
out.writeByte ('E');
}
@Override
public void readExternal (ObjectInput in)
throws IOException, ClassNotFoundException
{
in.readByte(); // ignore version for now
fieldNumber = in.readShort();
byte fieldType;
ISOComponent c;
try {
while ((fieldType = in.readByte()) != 'E') {
c = null;
switch (fieldType) {
case 'F':
c = new ISOField ();
break;
case 'A':
c = new ISOAmount ();
break;
case 'B':
c = new ISOBinaryField ();
break;
case 'M':
c = new ISOMsg ();
break;
case 'H':
readHeader (in);
break;
case 'P':
readPackager(in);
break;
case 'D':
readDirection (in);
break;
default:
throw new IOException ("malformed ISOMsg");
}
if (c != null) {
((Externalizable)c).readExternal (in);
set (c);
}
}
}
catch (ISOException e) {
throw new IOException (e.getMessage());
}
}
/**
* Let this ISOMsg object hold a weak reference to an ISOSource
* (usually used to carry a reference to the incoming ISOChannel)
* @param source an ISOSource
*/
public void setSource (ISOSource source) {
this.sourceRef = new WeakReference (source);
}
/**
* @return an ISOSource or null
*/
public ISOSource getSource () {
return sourceRef != null ? (ISOSource) sourceRef.get () : null;
}
private void writeExternal (ObjectOutput out, char b, ISOComponent c) throws IOException {
out.writeByte (b);
((Externalizable) c).writeExternal (out);
}
private int parseInt (String s) {
return s.startsWith("0x") ? Integer.parseInt(s.substring(2), 16) : Integer.parseInt(s);
}
}
|
package hudson.remoting;
import hudson.remoting.Channel.Mode;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLClassLoader;
import java.net.InetSocketAddress;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
/**
* Entry point for running a {@link Channel}. This is the main method of the slave JVM.
*
* <p>
* This class also defines several methods for
* starting a channel on a fresh JVM.
*
* @author Kohsuke Kawaguchi
*/
public class Launcher {
public static void main(String[] args) throws Exception {
Mode m = Mode.BINARY;
boolean ping = true;
URL slaveJnlpURL = null;
File tcpPortFile = null;
InetSocketAddress connectionTarget=null;
for(int i=0; i<args.length; i++) {
String arg = args[i];
if(arg.equals("-text")) {
System.out.println("Running in text mode");
m = Mode.TEXT;
continue;
}
if(arg.equals("-ping")) { // no-op, but left for backward compatibility
ping = true;
continue;
}
if(arg.equals("-jnlpUrl")) {
if(i+1==args.length) {
System.err.println("The -jnlpUrl option is missing a URL parameter");
System.exit(1);
}
slaveJnlpURL = new URL(args[++i]);
continue;
}
if(arg.equals("-cp") || arg.equals("-classpath")) {
if(i+1==args.length) {
System.err.println("The -cp option is missing a path parameter");
System.exit(1);
}
Method $addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
$addURL.setAccessible(true);
String pathList = args[++i];
for(String token : pathList.split(File.pathSeparator))
$addURL.invoke(ClassLoader.getSystemClassLoader(),new File(token).toURI().toURL());
// fix up the system.class.path to pretend that those jar files
// are given through CLASSPATH or something.
// some tools like JAX-WS RI and Hadoop relies on this.
System.setProperty("java.class.path",System.getProperty("java.class.path")+File.pathSeparatorChar+pathList);
continue;
}
if(arg.equals("-tcp")) {
if(i+1==args.length) {
System.err.println("The -tcp option is missing a file name parameter");
System.exit(1);
}
tcpPortFile = new File(args[++i]);
continue;
}
if(arg.equals("-connectTo")) {
if(i+1==args.length) {
System.err.println("The -connectTo option is missing ADDRESS:PORT parameter");
System.exit(1);
}
String[] tokens = args[++i].split(":");
if(tokens.length!=2) {
System.err.println("Illegal parameter: "+args[i-1]);
System.exit(1);
}
connectionTarget = new InetSocketAddress(tokens[0],Integer.valueOf(tokens[1]));
continue;
}
if(arg.equals("-noCertificateCheck")) {
// bypass HTTPS security check by using free-for-all trust manager
System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new NoCheckTrustManager()}, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// bypass host name check, too.
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
continue;
}
System.err.println("Invalid option: "+arg);
System.err.println(
"java -jar slave.jar [options...]\n" +
" -text : encode communication with the master with base64. Useful for\n" +
" running slave over 8-bit unsafe protocol like telnet.\n" +
" -jnlpUrl <url> : instead of talking to the master via stdin/stdout, emulate a JNLP client\n" +
" by making a TCP connection to the master. Connection parameters\n" +
" are obtained by parsing the JNLP file.\n" +
" -cp paths : add the given classpath elements to the system classloader\n" +
" -noCertificateCheck :\n" +
" bypass HTTPS certificate checks altogether.\n" +
" -connectTo <host>:<port> :\n" +
" make a TCP connection to the given host and port, then start communication.\n" +
" -tcp <file> : instead of talking to the master via stdin/stdout, listens to a random\n" +
" local port, write that port number to the given file, then wait for the\n" +
" master to connect to that port.\n");
System.exit(-1);
}
if(connectionTarget!=null) {
runAsTcpClient(connectionTarget,m,ping);
System.exit(0);
} else
if(slaveJnlpURL!=null) {
List<String> jnlpArgs = parseJnlpArguments(slaveJnlpURL);
hudson.remoting.jnlp.Main.main(jnlpArgs.toArray(new String[jnlpArgs.size()]));
} else
if(tcpPortFile!=null) {
runAsTcpServer(tcpPortFile,m,ping);
System.exit(0);
} else {
runWithStdinStdout(m, ping);
System.exit(0);
}
}
/**
* Parses the connection arguments from JNLP file given in the URL.
*/
private static List<String> parseJnlpArguments(URL slaveJnlpURL) throws ParserConfigurationException, SAXException, IOException, InterruptedException {
while (true) {
try {
URLConnection con = slaveJnlpURL.openConnection();
con.connect();
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
if(http.getResponseCode()>=400)
// got the error code. report that (such as 401)
throw new IOException("Failed to load "+slaveJnlpURL+": "+http.getResponseCode()+" "+http.getResponseMessage());
}
Document dom;
// check if this URL points to a .jnlp file
String contentType = con.getHeaderField("Content-Type");
if(contentType==null || !contentType.startsWith("application/x-java-jnlp-file")) {
// load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
try {
dom = loadDom(slaveJnlpURL, con);
} catch (SAXException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
} catch (IOException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
}
} else {
dom = loadDom(slaveJnlpURL, con);
}
// exec into the JNLP launcher, to fetch the connection parameter through JNLP.
NodeList argElements = dom.getElementsByTagName("argument");
List<String> jnlpArgs = new ArrayList<String>();
for( int i=0; i<argElements.getLength(); i++ )
jnlpArgs.add(argElements.item(i).getTextContent());
// force a headless mode
jnlpArgs.add("-headless");
return jnlpArgs;
} catch (SSLHandshakeException e) {
if(e.getMessage().contains("PKIX path building failed")) {
// invalid SSL certificate. One reason this happens is when the certificate is self-signed
IOException x = new IOException("Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
x.initCause(e);
throw x;
} else
throw e;
} catch (IOException e) {
System.err.println("Failing to obtain "+slaveJnlpURL);
e.printStackTrace(System.err);
System.err.println("Waiting 10 seconds before retry");
Thread.sleep(10*1000);
// retry
}
}
}
private static Document loadDom(URL slaveJnlpURL, URLConnection con) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return db.parse(con.getInputStream(),slaveJnlpURL.toExternalForm());
}
/**
* Listens on an ephemeral port, record that port number in a port file,
* then accepts one TCP connection.
*/
private static void runAsTcpServer(File portFile, Mode m, boolean ping) throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging foreever
ServerSocket ss = new ServerSocket(0,1);
ss.setSoTimeout(30*1000);
// write a port file to report the port number
FileWriter w = new FileWriter(portFile);
w.write(String.valueOf(ss.getLocalPort()));
w.close();
// accept just one connection and that's it.
// when we are done, remove the port file to avoid stale port file
Socket s;
try {
s = ss.accept();
ss.close();
} finally {
portFile.delete();
}
runOnSocket(m, ping, s);
}
private static void runOnSocket(Mode m, boolean ping, Socket s) throws IOException, InterruptedException {
main(new BufferedInputStream(new SocketInputStream(s)),
new BufferedOutputStream(new SocketOutputStream(s)),m,ping);
}
/**
* Connects to the given TCP port and then start running
*/
private static void runAsTcpClient(InetSocketAddress target, Mode m, boolean ping) throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging foreever
Socket s = new Socket(target.getAddress(),target.getPort());
runOnSocket(m, ping, s);
}
private static void runWithStdinStdout(Mode m, boolean ping) throws IOException, InterruptedException {
// use stdin/stdout for channel communication
ttyCheck();
// this will prevent programs from accidentally writing to System.out
// and messing up the stream.
OutputStream os = System.out;
System.setOut(System.err);
main(System.in,os,m,ping);
}
private static void ttyCheck() {
try {
Method m = System.class.getMethod("console");
Object console = m.invoke(null);
if(console!=null) {
// we seem to be running from interactive console. issue a warning.
// but since this diagnosis could be wrong, go on and do what we normally do anyway. Don't exit.
System.out.println(
"WARNING: Are you running slave agent from an interactive console?\n" +
"If so, you are probably using it incorrectly.\n" +
"See http://hudson.gotdns.com/wiki/display/HUDSON/Launching+slave.jar+from+from+console");
}
} catch (LinkageError e) {
// we are probably running on JDK5 that doesn't have System.console()
// we can't check
} catch (InvocationTargetException e) {
// this is impossible
throw new AssertionError(e);
} catch (NoSuchMethodException e) {
// must be running on JDK5
} catch (IllegalAccessException e) {
// this is impossible
throw new AssertionError(e);
}
}
public static void main(InputStream is, OutputStream os) throws IOException, InterruptedException {
main(is,os,Mode.BINARY);
}
public static void main(InputStream is, OutputStream os, Mode mode) throws IOException, InterruptedException {
main(is,os,mode,false);
}
public static void main(InputStream is, OutputStream os, Mode mode, boolean performPing) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Channel channel = new Channel("channel", executor, mode, is, os);
System.err.println("channel started");
if(performPing) {
System.err.println("Starting periodic ping thread");
new PingThread(channel) {
@Override
protected void onDead() {
System.err.println("Ping failed. Terminating");
System.exit(-1);
}
}.start();
}
channel.join();
System.err.println("channel stopped");
}
/**
* {@link X509TrustManager} that performs no check at all.
*/
private static class NoCheckTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
|
package org.eclipse.persistence.testing.tests.clientserver;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.testing.models.employee.relational.EmployeeSystem;
import org.eclipse.persistence.testing.models.insurance.InsuranceSystem;
import org.eclipse.persistence.testing.tests.identitymaps.ConcurrentIdentityMapKeyEnumerationTest;
import org.eclipse.persistence.testing.tests.unitofwork.*;
/**
* Test the TopLink ClientSession and ServerSession under concurrent,
* multi-thread use cases.
* Any concurrent tests should be put here.
*/
public class ClientServerTestModel extends TestModel {
public ClientServerTestModel() {
setDescription("This suite tests updating objects through various clients session.");
}
public void addRequiredSystems() {
try {
getSession().getLog().write("WARNING, some JDBC drivers may fail if they are not thread safe." +
Helper.cr() + "JDBC-ODBC will not be run for this test." + Helper.cr() +
"Oracle OCI may fail." + Helper.cr() + "DB2 IBM JDBC may fail." + Helper.cr());
getSession().getLog().flush();
} catch (java.io.IOException e) {
}
if (getSession().getLogin().isJDBCODBCBridge()) {
throw new TestWarningException("JDBC-ODBC cannot support concurrent connections.");
}
addRequiredSystem(new EmployeeSystem());
addRequiredSystem(new InsuranceSystem());
addRequiredSystem(new ClientServerEmployeeSystem());
addRequiredSystem(new org.eclipse.persistence.testing.tests.unitofwork.UOWSystem());
}
public void addTests() {
addTest(getClientServerTestSuite());
addTest(getClientServerReadingTestSuite());
}
public TestSuite getClientServerReadingTestSuite() {
TestSuite suite = new TestSuite();
suite.setName("Reading Tests");
suite.addTest(new ClientServerExclusiveReadingTest());
suite.addTest(new ClientServerConcurrentReadingTest_Case1());
suite.addTest(new ClientServerConcurrentReadingTest_Case2());
//useStreams
suite.addTest(new ClientServerConcurrentReadingTest_Case2(true));
suite.addTest(new ClientServerOptimisticLockingTest());
//test deadlock in the cache key level locking
suite.addTest(new ClientServerReadingDeadlockTest());
suite.addTest(new ClientServerReadingNonDeadlockTest());
//Run deadlock on readlock test for approx. 3 minutes
suite.addTest(new ConcurrentTestWithReadLocks(180000));
suite.addTest(new ConcurrentBatchReadingTest(70000));
//bug 3388383
suite.addTest(new ConcurrentTestRefreshWithOptimisticLocking(100000));
return suite;
}
public static TestSuite getClientServerTestSuite() {
TestSuite suite = new TestSuite();
suite.setName("ClientServerTestSuite");
suite.addTest(new ClientServerTest());
suite.addTest(new ConcurrencyManagerTest());
suite.addTest(new ClientServerConcurrentWriteTest());
suite.addTest(new ClientServerSequenceDeadlockTest());
suite.addTest(new ClientServerSequenceDeadlockTest2());
suite.addTest(new ClientLoginTest());
suite.addTest(new PreBeginTransactionFailureTest());
suite.addTest(new NPEIsThrownWhenWeTryToWriteNullToANullableField());
suite.addTest(new DonotAliaseTheTableWhenWeHaveSubSelectExpression());
//bug 3590333
suite.addTest(new ConcurrentIdentityMapKeyEnumerationTest());
// Moved concurrent client/server tests from UnitOfWork test suite here,
// as all concurrent tests should be here, and they can take a really long time to run.
//bug 3656068
suite.addTest(new ConcurrentReadOnUpdateWithEarlyTransTest());
//bug 4071929
suite.addTest(new UnitOfWorkConcurrentRevertTest());
//bug 3582102
suite.addTest(new LockOnCloneTest());
suite.addTest(new LockOnCloneDeadlockAvoidanceTest());
suite.addTest(new ConcurrentNewObjectTest());
suite.addTest(new ConcurrentReadOnInsertTest());
suite.addTest(new ConcurrentRefreshOnUpdateTest());
suite.addTest(new ConcurrentRefreshOnCloneTest());
//bug 4438127
suite.addTest(new NewObjectIdentityTest());
// Failover connection management EclipseLink bug 211100
suite.addTest(new CommunicationFailureTest());
return suite;
}
/**
* Because this changes the database it must put it back to a valid state.
*/
public void reset() {
//getExecutor().removeConfigureSystem(new EmployeeSystem());
getExecutor().removeConfigureSystem(new ClientEmployeeSystem());
getExecutor().getSession().getIdentityMapAccessor().initializeAllIdentityMaps();
}
}
|
package uk.ac.ebi.spot.goci.component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.ac.ebi.spot.goci.service.rest.GeneCheckingRestService;
import uk.ac.ebi.spot.goci.service.rest.SnpCheckingRestService;
import java.util.Set;
@Component
public class ValidationChecks {
private GeneCheckingRestService geneCheckingRestService;
private SnpCheckingRestService snpCheckingRestService;
@Autowired
public ValidationChecks(GeneCheckingRestService geneCheckingRestService,
SnpCheckingRestService snpCheckingRestService) {
this.geneCheckingRestService = geneCheckingRestService;
this.snpCheckingRestService = snpCheckingRestService;
}
/**
* Check value is populated
*
* @param value Value to be check presence
*/
public String checkValueIsPresent(String value) {
String error = null;
if (value == null) {
error = "Value is empty";
}
else {
if (value.isEmpty()) {
error = "Value is empty";
}
}
return error;
}
/**
* Check value is empty
*
* @param value Value to be checked
*/
public String checkValueIsEmpty(String value) {
String error = null;
if (value != null && !value.isEmpty()) {
error = "Value is not empty";
}
return error;
}
/**
* Check value is empty
*
* @param value Value to be checked
*/
public String checkValueIsEmpty(Float value) {
String error = null;
if (value != null) {
error = "Value is not empty";
}
return error;
}
/**
* Check snp type contains only values 'novel' or 'known'
*
* @param value Value to be checked
*/
public String checkSnpType(String value) {
String error = null;
if (value != null) {
switch (value) {
case "novel":
break;
case "known":
break;
default:
error = "Value does not contain novel or known";
}
}
else {
error = "Value is empty";
}
return error;
}
/**
* OR MUST be filled and a number
*
* @param value Value to be checked
*/
public String checkOrIsPresent(Float value) {
String error = null;
if (value == null) {
error = "Value is empty";
}
else {
if (Float.isNaN(value)) {
error = "Value is not number";
}
}
return error;
}
/**
* Reciprocal OR MUST be filled and less than 1
*
* @param value Value to be checked
*/
public String checkOrRecipIsPresentAndLessThanOne(Float value) {
String error = null;
if (value == null) {
error = "Value is empty";
}
else {
if (value > 1) {
error = "Value is more than 1";
}
}
return error;
}
/**
* If the 0R < 1 then you enter an OR reciprocal value. Otherwise OR reciprocal value can be left blank
*
* @param or OR value
* @param orRecip OR Reciprocal value
*/
public String checkOrAndOrRecip(Float or, Float orRecip) {
String error = null;
if (or == null) {
error = "OR value is empty";
}
else {
if (or < 1 && orRecip == null) {
error = "OR value is less than 1 and no OR reciprocal value entered";
}
}
return error;
}
/**
* Beta MUST be filled
*
* @param value Value to be checked
*/
public String checkBetaIsPresentAndIsNotNegative(Float value) {
String error = null;
if (value == null) {
error = "Value is empty";
}
else {
if (value < 0) {
error = "Value is less than 0";
}
}
return error;
}
/**
* "Beta direction" MUST be filled
*
* @param value Value to be checked
*/
public String checkBetaDirectionIsPresent(String value) {
String error = null;
if (value == null) {
error = "Value is empty";
}
else {
switch (value) {
case "increase":
break;
case "decrease":
break;
default:
error = "Value is not increase or decrease";
}
}
return error;
}
/**
* P-value mantissa check number of digits.
*
* @param value Value to be checked
*/
public String checkMantissaIsLessThan10(Integer value) {
String error = null;
if (value != null) {
if (value > 9) {
error = "Value not valid i.e. greater than 9";
}
}
else {
error = "Value is empty";
}
return error;
}
/**
* P-value exponent check
*
* @param value Value to be checked
*/
public String checkExponentIsPresentAndNegative(Integer value) {
String error = null;
if (value == null) {
error = "Value is empty";
}
else {
if (value >= 0) {
error = "Value is greater than or equal to zero";
}
}
return error;
}
/**
* Gene check
*
* @param geneName Gene name to be checked
*/
public String checkGene(String geneName) {
String error = null;
if (geneName == null) {
error = "Gene name is empty";
}
else {
if (geneName.isEmpty()) {
error = "Gene name is empty";
}
// Check gene name in Ensembl
else {
if (!geneName.equalsIgnoreCase("intergenic") && !geneName.equalsIgnoreCase("NR")) {
error = geneCheckingRestService.checkGeneSymbolIsValid(geneName);
}
}
}
return error;
}
/**
* Snp check
*
* @param snp Snp identifier to be checked
*/
public String checkSnp(String snp) {
String error = null;
if (snp == null) {
error = "SNP identifier is empty";
}
else {
if (snp.isEmpty()) {
error = "SNP identifier is empty";
}
// Check SNP in Ensembl
else {
error = snpCheckingRestService.checkSnpIdentifierIsValid(snp);
}
}
return error;
}
/**
* Gene and SNP not on same Chr
*
* @param snp Snp identifier to be checked
* @param gene Gene name to be checked
*/
public String checkSnpGeneLocation(String snp, String gene) {
String error = null;
// Ensure valid snp
String snpError = checkSnp(snp);
if (snpError != null) {
error = snpError;
}
else {
// Get all SNP locations and check gene location is one of them
Set<String> snpChromosomeNames = snpCheckingRestService.getSnpLocations(snp);
if (!snpChromosomeNames.isEmpty()) {
if (!gene.equalsIgnoreCase("intergenic") && !gene.equalsIgnoreCase("NR")) {
String geneChromosome = geneCheckingRestService.getGeneLocation(gene);
if (!snpChromosomeNames.contains(geneChromosome)) {
error = "Gene ".concat(gene)
.concat(" and SNP ")
.concat(snp)
.concat(" are not on same chromosome");
}
}
}
else {
error = "SNP ".concat(snp)
.concat(" has no location details, cannot check if gene is on same chromosome as SNP");
}
}
return error;
}
/**
* Risk allele check
*
* @param riskAlleleName to be checked
*/
public String checkRiskAllele(String riskAlleleName) {
String error = null;
/* TODO AT SOME STAGE WE SHOULD SWITCH TO CHECKING JUST THE 4 BASES
List<String> acceptableValues = new ArrayList<>();
acceptableValues.add("A");
acceptableValues.add("T");
acceptableValues.add("G");
acceptableValues.add("C");
acceptableValues.add("?");*/
if (riskAlleleName == null) {
error = "Value is empty";
}
else {
if (riskAlleleName.isEmpty()) {
error = "Value is empty";
}
// Check risk allele is one of the accepted types
else {
if (!riskAlleleName.startsWith("rs") && !riskAlleleName.contains("-")) {
error = "Value does not start with rs or contain -";
}
}
}
return error;
}
/**
* Risk frequency check
*
* @param riskFrequency Risk frequency value to be checked
*/
public String checkRiskFrequency(String riskFrequency) {
String error = null;
if (riskFrequency == null) {
error = "Value is empty";
}
else if (riskFrequency.isEmpty()) {
error = "Value is empty";
}
else {
// Skip check if value is NR
if (!riskFrequency.equals("NR")) {
try {
float f = Float.parseFloat(riskFrequency);
// if string contains only numbers then check its value is between valid range
if (f < 0 || f > 1) {
error = "Value is invalid, value is not between 0 and 1";
}
}
catch (NumberFormatException e) {
if (!riskFrequency.contentEquals("NR")) {
error = "Value is invalid i.e. not equal to NR or a number";
}
}
}
}
return error;
}
/**
* Check value contains the required delimiter
*
* @param value Value to check
* @param delimiter
*/
public String checkSynthax(String value, String delimiter) {
String error = null;
if (!value.contains(delimiter)) {
error = "Value does not contain correct separator";
}
return error;
}
/**
* Check that SNP status attributes are set to true for at least one
*
* @param genomeWide
* @param limitedList
*/
public String checkSnpStatus(Boolean genomeWide, Boolean limitedList) {
String error = null;
if (!genomeWide && !limitedList) {
error = "No status selected";
}
return error;
}
}
|
package org.knowm.xchange.binance.dto.meta;
import java.util.Map;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.dto.meta.CurrencyPairMetaData;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import org.knowm.xchange.dto.meta.RateLimit;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("serial")
public class BinanceMetaData extends ExchangeMetaData {
public BinanceMetaData(@JsonProperty("currency_pairs") Map<CurrencyPair, CurrencyPairMetaData> currencyPairs,
@JsonProperty("currencies") Map<Currency, CurrencyMetaData> currencies,
@JsonProperty("public_rate_limits") RateLimit[] publicRateLimits,
@JsonProperty("private_rate_limits") RateLimit[] privateRateLimits,
@JsonProperty("share_rate_limits") Boolean shareRateLimits) {
super(currencyPairs, currencies, publicRateLimits, privateRateLimits, shareRateLimits);
}
}
|
package documentconverter.reader;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.docx4j.jaxb.XPathBinderAssociationIsPartialException;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.P;
import org.docx4j.wml.PPr;
import org.docx4j.wml.PPrBase.PStyle;
import org.docx4j.wml.PPrBase.Spacing;
import org.docx4j.wml.DocDefaults;
import org.docx4j.wml.R;
import org.docx4j.wml.R.Tab;
import org.docx4j.wml.RPr;
import org.docx4j.wml.STVerticalAlignRun;
import org.docx4j.wml.SectPr;
import org.docx4j.wml.SectPr.PgMar;
import org.docx4j.wml.SectPr.PgSz;
import org.docx4j.wml.Style;
import org.docx4j.wml.Text;
import org.docx4j.wml.UnderlineEnumeration;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import documentconverter.renderer.FontConfig;
import documentconverter.renderer.FontStyle;
import documentconverter.renderer.Page;
import documentconverter.renderer.Renderer;
public class DocxReader implements Reader {
private static final Logger LOG = Logger.getLogger(DocxReader.class);
private static final int TAB_WIDTH = 950;
private Renderer renderer;
private File docx;
private MainDocumentPart main;
private Deque<PageLayout> layouts = new ArrayDeque<>();
private PageLayout layout;
private Page page;
private int xOffset;
private int yOffset;
private ParagraphStyle defaultParaStyle;
private ParagraphStyle paraStyle;
private ParagraphStyle runStyle;
/**
* The actions that represent the current line. These are stored until the
* line height can be calculated.
*/
private List<Object> actions = new ArrayList<>();
/**
* The current maximum height for the current line being processed.
* This is effectively the height of the objects stored in the actions list.
*/
private double lineHeight;
public DocxReader(Renderer renderer, File docx) {
this.renderer = renderer;
this.docx = docx;
}
@Override
public void process() throws ReaderException {
WordprocessingMLPackage word;
try {
word = WordprocessingMLPackage.load(docx);
} catch (Docx4JException e) {
throw new ReaderException("Error loading document", e);
}
main = word.getMainDocumentPart();
setDefaultStyles();
setPageLayouts(word);
createPageFromNextLayout();
iterateContentParts(main);
}
private void setDefaultStyles() throws ReaderException {
List<Object> docs;
try {
docs = (List<Object>) main.getStyleDefinitionsPart().getJAXBNodesViaXPath("/w:styles/w:docDefaults", false);
} catch (XPathBinderAssociationIsPartialException | JAXBException e) {
throw new ReaderException("Error retrieving default styles", e);
}
DocDefaults docDef = (DocDefaults) docs.get(0);
defaultParaStyle = getStyle(new ParagraphStyle(), docDef.getRPrDefault().getRPr());
}
private void setPageLayouts(WordprocessingMLPackage word) {
for (SectionWrapper section : word.getDocumentModel().getSections()) {
// TODO: support header and footers - section.getHeaderFooterPolicy()
layouts.add(createPageLayout(section.getSectPr()));
}
}
private PageLayout createPageLayout(SectPr sectPr) {
PgSz size = sectPr.getPgSz();
PgMar margin = sectPr.getPgMar();
return new PageLayout(
size.getW().intValue(),
size.getH().intValue(),
margin.getTop().intValue(),
margin.getRight().intValue(),
margin.getBottom().intValue(),
margin.getLeft().intValue()
);
}
private void createPageFromNextLayout() {
layout = layouts.removeFirst();
createPageFromLayout();
}
private void createPageFromLayout() {
page = renderer.addPage(layout.getWidth(), layout.getHeight());
xOffset = layout.getLeftMargin();
yOffset = layout.getTopMargin();
}
public void iterateContentParts(ContentAccessor ca) {
for (Object obj : ca.getContent()) {
if (obj instanceof P) {
processParagraph((P) obj);
} else if (obj instanceof R) {
processTextRun((R) obj);
} else if (obj instanceof JAXBElement) {
JAXBElement<?> element = (JAXBElement<?>) obj;
if (element.getDeclaredType().equals(Text.class)) {
processText(((Text) element.getValue()).getValue());
} else if (element.getDeclaredType().equals(Tab.class)) {
processTab((Tab) element.getValue());
} else {
LOG.trace("Unhandled JAXBElement class " + element.getDeclaredType());
}
} else {
LOG.trace("Unhandled document class " + obj.getClass());
}
}
}
private void processParagraph(P p) {
PPr properties = p.getPPr();
ParagraphStyle newParaStyle = new ParagraphStyle(defaultParaStyle);
if (properties != null) {
if (properties.getPStyle() != null) {
PStyle pstyle = properties.getPStyle();
newParaStyle = getStyleById(defaultParaStyle, pstyle.getVal());
}
if (properties.getJc() != null) {
switch(properties.getJc().getVal()) {
case RIGHT:
newParaStyle.setAlignment(Alignment.RIGHT);
break;
case CENTER:
newParaStyle.setAlignment(Alignment.CENTER);
break;
default:
// default to LEFT alignment
}
}
}
yOffset += newParaStyle.getSpaceBefore();
paraStyle = newParaStyle;
iterateContentParts(p);
renderActionsForLine();
yOffset += paraStyle.getSpaceAfter();
if (properties!= null && properties.getSectPr() != null) {
// The presence of SectPr indicates the next part should be started on a new page with a different layout
createPageFromNextLayout();
}
}
private void processTextRun(R r) {
ParagraphStyle newRunStyle = getStyle(paraStyle, r.getRPr());
if (runStyle == null || !newRunStyle.getFontConfig().equals(runStyle.getFontConfig())) {
actions.add(newRunStyle.getFontConfig());
}
if (runStyle == null || !newRunStyle.getColor().equals(runStyle.getColor())) {
actions.add(new Color(newRunStyle.getColor().getRGB()));
}
runStyle = newRunStyle;
iterateContentParts(r);
}
private void processText(String text) {
Rectangle2D bounds = runStyle.getStringBoxSize(text);
lineHeight = Math.max(lineHeight, bounds.getHeight());
// If the text needs wrapping, work out how to fit it into multiple lines
if (xOffset + bounds.getWidth() > layout.getWidth() - layout.getRightMargin()) {
String[] words = text.split(" ");
String newText = "";
for (int i=0; i<words.length; i++) {
if (newText.isEmpty()) {
bounds = runStyle.getStringBoxSize(words[i]);
} else {
bounds = runStyle.getStringBoxSize(newText + " " + words[i]);
}
// Check if adding the word will push it over the page content width
if (xOffset + bounds.getWidth() > layout.getWidth() - layout.getRightMargin()) {
// If this is the first word, break it up
if (i == 0) {
char[] chars = text.toCharArray();
for (int k=0; k<chars.length; k++) {
bounds = runStyle.getStringBoxSize(newText + chars[k]);
if (xOffset + bounds.getWidth() > layout.getWidth() - layout.getRightMargin()) {
break;
} else {
newText += chars[k];
}
}
} else {
break;
}
} else if (newText.isEmpty()) {
newText = words[i];
} else {
newText += " " + words[i];
}
}
actions.add(new DrawStringAction(newText, xOffset));
renderActionsForLine();
processText(text.substring(newText.length()).trim());
} else {
actions.add(new DrawStringAction(text, xOffset));
xOffset += bounds.getWidth();
}
}
private void processTab(Tab tab) {
xOffset += TAB_WIDTH - ((xOffset - layout.getLeftMargin()) % TAB_WIDTH);
}
private ParagraphStyle getStyleById(ParagraphStyle baseStyle, String styleId) {
return getStyle(baseStyle, main.getStyleDefinitionsPart().getStyleById(styleId));
}
private ParagraphStyle getStyle(ParagraphStyle baseStyle, Style style) {
ParagraphStyle newStyle;
if (style.getBasedOn() == null) {
newStyle = new ParagraphStyle(baseStyle);
} else {
newStyle = getStyleById(baseStyle, style.getBasedOn().getVal());
}
if (style.getPPr() != null) {
Spacing spacing = style.getPPr().getSpacing();
if (spacing != null && spacing.getLine() != null) {
newStyle.setLineSpacing(spacing.getLine().intValue());
newStyle.setSpaceBefore(spacing.getBefore().intValue());
newStyle.setSpaceAfter(spacing.getAfter().intValue());
}
}
return getStyle(newStyle, style.getRPr());
}
private ParagraphStyle getStyle(ParagraphStyle baseStyle, RPr runProperties) {
if (runProperties == null) {
return baseStyle;
}
ParagraphStyle newStyle = new ParagraphStyle(baseStyle);
// font
if (runProperties.getRFonts() != null) {
newStyle.setFontName(runProperties.getRFonts().getAscii());
}
// font size
if (runProperties.getSz() != null) {
float sizePt = runProperties.getSz().getVal().floatValue() / 2;
// scale by a factor of 20 for trips units
newStyle.setFontSize(sizePt * 20);
}
// style
// TODO: support other style types (subscript, outline, shadow, ...)
if (runProperties.getB() != null) {
newStyle.enableFontStyle(FontStyle.BOLD);
}
if (runProperties.getI() != null) {
newStyle.enableFontStyle(FontStyle.ITALIC);
}
if (runProperties.getStrike() != null) {
newStyle.enableFontStyle(FontStyle.STRIKETHROUGH);
}
if (runProperties.getU() != null && runProperties.getU().getVal().equals(UnderlineEnumeration.SINGLE)) {
// TODO: support the other underline types
newStyle.enableFontStyle(FontStyle.UNDERLINE);
}
if (runProperties.getVertAlign() != null && runProperties.getVertAlign().getVal().equals(STVerticalAlignRun.SUPERSCRIPT)) {
newStyle.enableFontStyle(FontStyle.SUPERSCRIPT);
}
// text color
Color newColor = Color.BLACK;
if (runProperties.getColor() != null) {
String strColor = runProperties.getColor().getVal();
if (strColor.equals("auto")) {
newColor = Color.BLACK;
} else {
String hex = StringUtils.leftPad(strColor, 6, '0');
newColor = new Color(
Integer.valueOf(hex.substring(0, 2), 16),
Integer.valueOf(hex.substring(2, 4), 16),
Integer.valueOf(hex.substring(4, 6), 16)
);
}
}
newStyle.setColor(newColor);
return newStyle;
}
private void renderActionsForLine() {
yOffset += lineHeight;
int alignmentOffset = 0;
switch(paraStyle.getAlignment()) {
case RIGHT:
alignmentOffset = layout.getWidth() - layout.getRightMargin() - xOffset;
break;
case CENTER:
alignmentOffset = (layout.getWidth() - layout.getRightMargin() - xOffset) / 2;
break;
default:
// default to left aligned
break;
}
for (Object obj : actions) {
if (obj instanceof DrawStringAction) {
DrawStringAction dsa = (DrawStringAction) obj;
page.drawString(dsa.getText(), dsa.getX() + alignmentOffset, yOffset);
} else if (obj instanceof Color) {
page.setColor(((Color) obj));
} else if (obj instanceof FontConfig) {
FontConfig fc = (FontConfig) obj;
page.setFontConfig(fc);
}
}
xOffset = layout.getLeftMargin();
lineHeight = 0;
actions.clear();
}
}
|
package org.javarosa.formmanager.view.chatterbox.widget;
import org.javarosa.core.model.QuestionDef;
import de.enough.polish.ui.ChoiceGroup;
import de.enough.polish.ui.ChoiceItem;
import de.enough.polish.ui.Container;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.MoreUIAccess;
import de.enough.polish.ui.Style;
/**
* The base widget for multi and single choice selections.
*
* NOTE: This class has a number of Hacks that I've made after rooting through
* the j2me polish source. If polish is behaving unpredictably, it is possibly because
* of conflicting changes in new Polish versions with this code. I have outlined
* the latest versions of polish in which the changes appear to work.
*
* Questions should be directed to csims@dimagi.com
*
* @author Clayton Sims
* @date Feb 16, 2009
*
*/
public abstract class SelectEntryWidget extends ExpandedWidget {
private int style;
protected QuestionDef question;
private ChoiceGroup choicegroup;
public SelectEntryWidget (int style) {
this.style = style;
}
protected Item getEntryWidget (QuestionDef question) {
this.question = question;
ChoiceGroup cg = new ChoiceGroup("", style) {
/** Hack #1 & Hack #3**/
// j2me polish refuses to produce events in the case where select items
// are already selected. This code intercepts key presses that toggle
// selection, and clear any existing selection to prevent the supression
// of the appropriate commands.
// Hack #3 is due to the fact that multiple choice items won't fire updates
// unless they haven't been selected by default. The return true here for them
// ensures that the system knows that fires on multi-select always signify
// a capture.
// NOTE: These changes are only necessary for Polish versions > 2.0.5 as far
// as I can tell. I have tested them on 2.0.4 and 2.0.7 and the changes
// were compatibly with both
protected boolean handleKeyReleased(int keyCode, int gameAction) {
boolean gameActionIsFire = getScreen().isGameActionFire(
keyCode, gameAction);
if (gameActionIsFire) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
if(this.choiceType != ChoiceGroup.MULTIPLE) {
//Hack
choiceItem.isSelected = false;
}
}
boolean superReturn = super.handleKeyReleased(keyCode, gameAction);
if(gameActionIsFire && this.choiceType == ChoiceGroup.MULTIPLE) {
//Hack
return true;
} else {
return superReturn;
}
}
public int getScrollHeight() {
return super.getScrollHeight();
}
/** Hack #2 **/
//This is a slight UI hack that is in place to make the choicegroup properly
//intercept 'up' and 'down' inputs. Essentially Polish is very broken when it comes
//to scrolling nested containers, and this function properly takes the parent (Widget) position
//into account as well as the choicegroup's
// I have tested this change with Polish 2.0.4 on Nokia Phones and the emulators and it works
// correctly. It also works correctly on Polish 2.0.7 on the emulator, but I have not attempted
// to use it on a real nokia phone.
public int getRelativeScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
// Clayton Sims - Feb 9, 2009 : Had to go through and modify this code again.
// The offsets are now accumulated through all of the parent containers, not just
// one.
Item walker = this.parent;
int offset = 0;
//Walk our parent containers and accumulate their offsets.
while(walker instanceof Container) {
// Clayton Sims - Apr 3, 2009 :
// If the container can scroll, it's relativeY is useless, it's in a frame and
// the relativeY isn't actually applicable.
// Actually, this should almost certainly _just_ break out of the loop if
// we hit something that scrolls, but if we have multiple scrolling containers
// nested, someone _screwed up_.
if(!MoreUIAccess.isScrollingContainer((Container)walker)) {
offset += walker.relativeY;
}
walker = walker.getParent();
}
//The value returned here (The + offest part) is the fix.
int absOffset = ((Container)this.parent).getScrollYOffset() + this.relativeY + offset;
return absOffset;
// Clayton Sims - Feb 10, 2009 : Rolled back because it doesn't work on the 3110c, apparently!
// Fixing soon.
//return ((Container)this.parent).getScrollYOffset() + this.relativeY + this.parent.relativeY;
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/** Hack #4! **/
//Clayton Sims - Jun 16, 2009
// Once again we're in the land of hacks.
// This particular hack is responsible for making it so that when a widget is
// brought up on the screen, its selected value (if one exists), is currently
// highlighted. This vastly improves the back/forward usability.
// Only Tested on Polish 2.0.4
public Style focus (Style newStyle, int direction) {
Style retStyle = super.focus(newStyle, direction);
if(this.getSelectedIndex() > -1) {
this.focus(this.getSelectedIndex());
}
return retStyle;
}
};
for (int i = 0; i < question.getSelectItems().size(); i++){
cg.append("", null);
}
this.choicegroup = cg;
return cg;
}
protected ChoiceGroup choiceGroup () {
//return (ChoiceGroup)entryWidget;
return this.choicegroup;
}
protected void updateWidget (QuestionDef question) {
for (int i = 0; i < choiceGroup().size(); i++) {
choiceGroup().getItem(i).setText((String)question.getSelectItems().keyAt(i));
}
}
}
|
package com.xpn.xwiki.api;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.suigeneris.jrcs.diff.delta.Chunk;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.job.Job;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.rendering.renderer.PrintRendererFactory;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.stability.Unstable;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDeletedDocument;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.internal.XWikiInitializerJob;
import com.xpn.xwiki.internal.XWikiInitializerJobStatus;
import com.xpn.xwiki.objects.meta.MetaClass;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.util.Programming;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiEngineContext;
import com.xpn.xwiki.web.XWikiURLFactory;
public class XWiki extends Api
{
/** Logging helper object. */
protected static final Logger LOGGER = LoggerFactory.getLogger(XWiki.class);
/** The internal object wrapped by this API. */
private com.xpn.xwiki.XWiki xwiki;
/**
* @see #getStatsService()
*/
private StatsService statsService;
/**
* @see #getCriteriaService()
*/
private CriteriaService criteriaService;
/**
* @see com.xpn.xwiki.internal.model.reference.CurrentMixedStringDocumentReferenceResolver
*/
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.TYPE_STRING, "currentmixed");
/**
* @see org.xwiki.model.internal.reference.DefaultStringDocumentReferenceResolver
*/
private DocumentReferenceResolver<String> defaultDocumentReferenceResolver = Utils
.getComponent(DocumentReferenceResolver.TYPE_STRING);
/**
* The object used to serialize entity references into strings. We need it because we have script APIs that work
* with entity references but have to call older, often internal, methods that still use string references.
*/
private EntityReferenceSerializer<String> defaultStringEntityReferenceSerializer = Utils
.getComponent(EntityReferenceSerializer.TYPE_STRING);
/**
* XWiki API Constructor
*
* @param xwiki XWiki Main Object to wrap
* @param context XWikiContext to wrap
*/
public XWiki(com.xpn.xwiki.XWiki xwiki, XWikiContext context)
{
super(context);
this.xwiki = xwiki;
this.statsService = new StatsService(context);
this.criteriaService = new CriteriaService(context);
}
/**
* Privileged API allowing to access the underlying main XWiki Object
*
* @return Privileged Main XWiki Object
*/
@Programming
public com.xpn.xwiki.XWiki getXWiki()
{
if (hasProgrammingRights()) {
return this.xwiki;
}
return null;
}
public XWikiInitializerJobStatus getJobStatus()
{
XWikiInitializerJob job = Utils.getComponent((Type) Job.class, XWikiInitializerJob.JOBTYPE);
return job != null ? job.getStatus() : null;
}
/**
* @return XWiki's version in the format <code>(version).(SVN build number)</code>, or "Unknown version" if it
* failed to be retrieved
*/
public String getVersion()
{
return this.xwiki.getVersion();
}
/**
* API Allowing to access the current request URL being requested.
*
* @return the URL
* @throws XWikiException failed to create the URL
*/
public String getRequestURL() throws XWikiException
{
return getXWikiContext().getURLFactory().getRequestURL(getXWikiContext()).toString();
}
/**
* API Allowing to access the current request URL being requested as a relative URL.
*
* @return the URL
* @throws XWikiException failed to create the URL
* @since 4.0M1
*/
public String getRelativeRequestURL() throws XWikiException
{
XWikiURLFactory urlFactory = getXWikiContext().getURLFactory();
return urlFactory.getURL(urlFactory.getRequestURL(getXWikiContext()), getXWikiContext());
}
/**
* Loads an Document from the database. Rights are checked before sending back the document.
*
* @param fullName the full name of the XWiki document to be loaded
* @return a Document object (if the document couldn't be found a new one is created in memory - but not saved, you
* can check whether it's a new document or not by using {@link com.xpn.xwiki.api.Document#isNew()}
* @throws XWikiException
*/
public Document getDocument(String fullName) throws XWikiException
{
DocumentReference reference;
// We ignore the passed full name if it's null to be backward compatible with previous behaviors.
if (fullName != null) {
// Note: We use the CurrentMixed Resolver since we want to use the default page name if the page isn't
// specified in the passed string, rather than use the current document's page name.
reference = this.currentMixedDocumentReferenceResolver.resolve(fullName);
} else {
reference = this.defaultDocumentReferenceResolver.resolve("");
}
return getDocument(reference);
}
/**
* Loads an Document from the database. Rights are checked before sending back the document.
*
* @param reference the reference of the XWiki document to be loaded
* @return a Document object (if the document couldn't be found a new one is created in memory - but not saved, you
* can check whether it's a new document or not by using {@link com.xpn.xwiki.api.Document#isNew()}
* @throws XWikiException
* @since 2.3M1
*/
public Document getDocument(DocumentReference reference) throws XWikiException
{
try {
XWikiDocument doc = this.xwiki.getDocument(reference, getXWikiContext());
if (this.xwiki.getRightService().hasAccessLevel("view", getXWikiContext().getUser(),
doc.getPrefixedFullName(), getXWikiContext()) == false) {
return null;
}
Document newdoc = doc.newDocument(getXWikiContext());
return newdoc;
} catch (Exception ex) {
LOGGER.warn("Failed to access document " + reference + ": " + ex.getMessage());
return new Document(new XWikiDocument(reference), getXWikiContext());
}
}
/**
* Loads an Document from the database. Rights are checked on the author (contentAuthor) of the document containing
* the currently executing script before sending back the loaded document.
*
* @param fullName the full name of the XWiki document to be loaded
* @return a Document object (if the document couldn't be found a new one is created in memory - but not saved, you
* can check whether it's a new document or not by using {@link com.xpn.xwiki.api.Document#isNew()}
* @throws XWikiException
* @since 2.3M2
*/
public Document getDocumentAsAuthor(String fullName) throws XWikiException
{
DocumentReference reference;
// We ignore the passed full name if it's null to match behavior of getDocument
if (fullName != null) {
// Note: We use the CurrentMixed Resolver since we want to use the default page name if the page isn't
// specified in the passed string, rather than use the current document's page name.
reference = this.currentMixedDocumentReferenceResolver.resolve(fullName);
} else {
reference = this.defaultDocumentReferenceResolver.resolve("");
}
return getDocumentAsAuthor(reference);
}
/**
* Loads an Document from the database. Rights are checked on the author (contentAuthor) of the document containing
* the currently executing script before sending back the loaded document.
*
* @param reference the reference of the XWiki document to be loaded
* @return a Document object (if the document couldn't be found a new one is created in memory - but not saved, you
* can check whether it's a new document or not by using {@link com.xpn.xwiki.api.Document#isNew()}
* @throws XWikiException
* @since 2.3M2
*/
public Document getDocumentAsAuthor(DocumentReference reference) throws XWikiException
{
String author = this.getEffectiveScriptAuthorName();
XWikiDocument doc = this.xwiki.getDocument(reference, getXWikiContext());
if (this.xwiki.getRightService().hasAccessLevel("view", author, doc.getFullName(), getXWikiContext()) == false) {
return null;
}
Document newdoc = doc.newDocument(getXWikiContext());
return newdoc;
}
/**
* @param fullname the {@link XWikiDocument#getFullName() name} of the document to search for.
* @param lang an optional {@link XWikiDocument#getLanguage() language} to filter results.
* @return A list with all the deleted versions of a document in the recycle bin.
* @throws XWikiException if any error
*/
public List<DeletedDocument> getDeletedDocuments(String fullname, String lang) throws XWikiException
{
XWikiDeletedDocument[] dds = this.xwiki.getDeletedDocuments(fullname, lang, this.context);
if (dds == null || dds.length == 0) {
return Collections.emptyList();
}
List<DeletedDocument> result = new ArrayList<DeletedDocument>(dds.length);
for (int i = 0; i < dds.length; i++) {
result.add(new DeletedDocument(dds[i], this.context));
}
return result;
}
/**
* @return specified documents in recycle bin
* @param fullname - {@link XWikiDocument#getFullName()}
* @param lang - {@link XWikiDocument#getLanguage()}
* @throws XWikiException if any error
*/
public DeletedDocument getDeletedDocument(String fullname, String lang, String index) throws XWikiException
{
if (!NumberUtils.isDigits(index)) {
return null;
}
XWikiDeletedDocument dd = this.xwiki.getDeletedDocument(fullname, lang, Integer.parseInt(index), this.context);
if (dd == null) {
return null;
}
return new DeletedDocument(dd, this.context);
}
/**
* Retrieve all the deleted attachments that belonged to a certain document. Note that this does not distinguish
* between different incarnations of a document name, and it does not require that the document still exists, it
* returns all the attachments that at the time of their deletion had a document with the specified name as their
* owner.
*
* @param docName the {@link XWikiDocument#getFullName() name} of the owner document
* @return A list with all the deleted attachments which belonged to the specified document. If no such attachments
* are found in the trash, an empty list is returned.
*/
public List<DeletedAttachment> getDeletedAttachments(String docName)
{
try {
List<com.xpn.xwiki.doc.DeletedAttachment> attachments =
this.xwiki.getDeletedAttachments(docName, this.context);
if (attachments == null || attachments.isEmpty()) {
attachments = Collections.emptyList();
}
List<DeletedAttachment> result = new ArrayList<DeletedAttachment>(attachments.size());
for (com.xpn.xwiki.doc.DeletedAttachment attachment : attachments) {
result.add(new DeletedAttachment(attachment, this.context));
}
return result;
} catch (Exception ex) {
LOGGER.warn("Failed to retrieve deleted attachments", ex);
}
return Collections.emptyList();
}
/**
* Retrieve all the deleted attachments that belonged to a certain document and had the specified name. Multiple
* versions can be returned since the same file can be uploaded and deleted several times, creating different
* instances in the trash. Note that this does not distinguish between different incarnations of a document name,
* and it does not require that the document still exists, it returns all the attachments that at the time of their
* deletion had a document with the specified name as their owner.
*
* @param docName the {@link DeletedAttachment#getDocName() name of the document} the attachment belonged to
* @param filename the {@link DeletedAttachment#getFilename() name} of the attachment to search for
* @return A list with all the deleted attachments which belonged to the specified document and had the specified
* filename. If no such attachments are found in the trash, an empty list is returned.
*/
public List<DeletedAttachment> getDeletedAttachments(String docName, String filename)
{
try {
List<com.xpn.xwiki.doc.DeletedAttachment> attachments =
this.xwiki.getDeletedAttachments(docName, filename, this.context);
if (attachments == null) {
attachments = Collections.emptyList();
}
List<DeletedAttachment> result = new ArrayList<DeletedAttachment>(attachments.size());
for (com.xpn.xwiki.doc.DeletedAttachment attachment : attachments) {
result.add(new DeletedAttachment(attachment, this.context));
}
return result;
} catch (Exception ex) {
LOGGER.warn("Failed to retrieve deleted attachments", ex);
}
return Collections.emptyList();
}
/**
* Retrieve a specific attachment from the trash.
*
* @param id the unique identifier of the entry in the trash
* @return specified attachment from the trash, {@code null} if not found
*/
public DeletedAttachment getDeletedAttachment(String id)
{
try {
com.xpn.xwiki.doc.DeletedAttachment attachment = this.xwiki.getDeletedAttachment(id, this.context);
if (attachment != null) {
return new DeletedAttachment(attachment, this.context);
}
} catch (Exception ex) {
LOGGER.warn("Failed to retrieve deleted attachment", ex);
}
return null;
}
/**
* Returns whether a document exists or not
*
* @param fullname Fullname of the XWiki document to be loaded
* @return true if the document exists, false if not
* @throws XWikiException
*/
public boolean exists(String fullname) throws XWikiException
{
return this.xwiki.exists(fullname, getXWikiContext());
}
/**
* Returns whether a document exists or not
*
* @param reference the reference of the document to check for its existence
* @return true if the document exists, false if not
* @since 2.3M2
*/
public boolean exists(DocumentReference reference) throws XWikiException
{
return this.xwiki.exists(reference, getXWikiContext());
}
/**
* Verify the rights the current user has on a document. If the document requires rights and the user is not
* authenticated he will be redirected to the login page.
*
* @param docname fullname of the document
* @param right right to check ("view", "edit", "admin", "delete")
* @return true if it exists
*/
public boolean checkAccess(String docname, String right)
{
try {
DocumentReference docReference = this.currentMixedDocumentReferenceResolver.resolve(docname);
XWikiDocument doc = getXWikiContext().getWiki().getDocument(docReference, this.context);
return getXWikiContext().getWiki().checkAccess(right, doc, getXWikiContext());
} catch (XWikiException e) {
return false;
}
}
/**
* Loads an Document from the database. Rights are checked before sending back the document.
*
* @param space Space to use in case no space is defined in the provided <code>fullname</code>
* @param fullname the full name or relative name of the document to load
* @return a Document object (if the document couldn't be found a new one is created in memory - but not saved, you
* can check whether it's a new document or not by using {@link com.xpn.xwiki.api.Document#isNew()}
* @throws XWikiException
*/
public Document getDocument(String space, String fullname) throws XWikiException
{
XWikiDocument doc = this.xwiki.getDocument(space, fullname, getXWikiContext());
if (this.xwiki.getRightService().hasAccessLevel("view", getXWikiContext().getUser(), doc.getFullName(),
getXWikiContext()) == false) {
return null;
}
return doc.newDocument(getXWikiContext());
}
/**
* Load a specific revision of a document
*
* @param doc Document for which to load a specific revision
* @param rev Revision number
* @return Specific revision of a document
* @throws XWikiException
*/
public Document getDocument(Document doc, String rev) throws XWikiException
{
if ((doc == null) || (doc.getDoc() == null)) {
return null;
}
if (this.xwiki.getRightService().hasAccessLevel("view", getXWikiContext().getUser(), doc.getFullName(),
getXWikiContext()) == false) {
// Finally we return null, otherwise showing search result is a real pain
return null;
}
try {
XWikiDocument revdoc = this.xwiki.getDocument(doc.getDoc(), rev, getXWikiContext());
return revdoc.newDocument(getXWikiContext());
} catch (Exception e) {
// Can't read versioned document
LOGGER.error("Failed to read versioned document", e);
return null;
}
}
/**
* Output content in the edit content textarea
*
* @param content content to output
* @return the textarea text content
*/
public String getTextArea(String content)
{
return com.xpn.xwiki.XWiki.getTextArea(content, getXWikiContext());
}
/**
* Get the list of available classes in the wiki
*
* @return list of classes names
* @throws XWikiException
*/
public List<String> getClassList() throws XWikiException
{
return this.xwiki.getClassList(getXWikiContext());
}
/**
* Get the global MetaClass object
*
* @return MetaClass object
*/
public MetaClass getMetaclass()
{
return this.xwiki.getMetaclass();
}
/**
* API allowing to search for document names matching a query. Examples:
* <ul>
* <li>Query: <code>where doc.space='Main' order by doc.creationDate desc</code>. Result: All the documents in space
* 'Main' ordered by the creation date from the most recent</li>
* <li>Query: <code>where doc.name like '%sport%' order by doc.name asc</code>. Result: All the documents containing
* 'sport' in their name ordered by document name</li>
* <li>Query: <code>where doc.content like '%sport%' order by doc.author</code> Result: All the documents containing
* 'sport' in their content ordered by the author</li>
* <li>Query: <code>where doc.creator = 'XWiki.LudovicDubost' order by doc.creationDate
* desc</code>. Result: All the documents with creator LudovicDubost ordered by the creation date from the
* most recent</li>
* <li>Query: <code>where doc.author = 'XWiki.LudovicDubost' order by doc.date desc</code>. Result: All the
* documents with last author LudovicDubost ordered by the last modification date from the most recent.</li>
* <li>Query: <code>,BaseObject as obj where doc.fullName=obj.name and
* obj.className='XWiki.XWikiComments' order by doc.date desc</code>. Result: All the documents with at least
* one comment ordered by the last modification date from the most recent</li>
* <li>Query: <code>,BaseObject as obj, StringProperty as prop where
* doc.fullName=obj.name and obj.className='XWiki.XWikiComments' and obj.id=prop.id.id
* and prop.id.name='author' and prop.value='XWiki.LudovicDubost' order by doc.date
* desc</code>. Result: All the documents with at least one comment from LudovicDubost ordered by the last
* modification date from the most recent</li>
* </ul>
*
* @param wheresql Query to be run (either starting with ", BaseObject as obj where.." or by "where ..."
* @return List of document names matching (Main.Page1, Main.Page2)
* @throws XWikiException
* @deprecated use query service instead
*/
@Deprecated
public List<String> searchDocuments(String wheresql) throws XWikiException
{
return this.xwiki.getStore().searchDocumentsNames(wheresql, getXWikiContext());
}
/**
* API allowing to search for document names matching a query return only a limited number of elements and skipping
* the first rows. The query part is the same as searchDocuments
*
* @param wheresql query to use similar to searchDocuments(wheresql)
* @param nb return only 'nb' rows
* @param start skip the first 'start' rows
* @return List of document names matching
* @throws XWikiException
* @see List searchDocuments(String where sql)
* @deprecated use query service instead
*/
@Deprecated
public List<String> searchDocuments(String wheresql, int nb, int start) throws XWikiException
{
return this.xwiki.getStore().searchDocumentsNames(wheresql, nb, start, getXWikiContext());
}
/**
* Privileged API allowing to search for document names matching a query return only a limited number of elements
* and skipping the first rows. The return values contain the list of columns specified in addition to the document
* space and name The query part is the same as searchDocuments
*
* @param wheresql query to use similar to searchDocuments(wheresql)
* @param nb return only 'nb' rows
* @param start skip the first 'start' rows
* @param selectColumns List of columns to add to the result
* @return List of Object[] with the column values of the matching rows
* @throws XWikiException
* @deprecated use query service instead
*/
@Deprecated
public List<String> searchDocuments(String wheresql, int nb, int start, String selectColumns) throws XWikiException
{
if (hasProgrammingRights()) {
return this.xwiki.getStore().searchDocumentsNames(wheresql, nb, start, selectColumns, getXWikiContext());
}
return Collections.emptyList();
}
/**
* API allowing to search for documents allowing to have mutliple entries per language
*
* @param wheresql query to use similar to searchDocuments(wheresql)
* @param distinctbylanguage true to return multiple rows per language
* @return List of Document object matching
* @throws XWikiException
*/
public List<Document> searchDocuments(String wheresql, boolean distinctbylanguage) throws XWikiException
{
return convert(this.xwiki.getStore().searchDocuments(wheresql, distinctbylanguage, getXWikiContext()));
}
/**
* API allowing to search for documents allowing to have multiple entries per language
*
* @param wheresql query to use similar to searchDocuments(wheresql)
* @param distinctbylanguage true to return multiple rows per language
* @return List of Document object matching
* @param nb return only 'nb' rows
* @param start skip the first 'start' rows
* @throws XWikiException
*/
public List<Document> searchDocuments(String wheresql, boolean distinctbylanguage, int nb, int start)
throws XWikiException
{
return convert(this.xwiki.getStore()
.searchDocuments(wheresql, distinctbylanguage, nb, start, getXWikiContext()));
}
/**
* Search documents by passing HQL where clause values as parameters. This allows generating a Named HQL query which
* will automatically encode the passed values (like escaping single quotes). This API is recommended to be used
* over the other similar methods where the values are passed inside the where clause and for which you'll need to
* do the encoding/escaping yourself before calling them.
* <p>
* Example
* </p>
*
* <pre>
* <code>
* #set($orphans = $xwiki.searchDocuments(" where doc.fullName <> ? and (doc.parent = ? or "
* + "(doc.parent = ? and doc.space = ?))",
* ["${doc.fullName}as", ${doc.fullName}, ${doc.name}, ${doc.space}]))
* </code>
* </pre>
*
* @param parameterizedWhereClause the HQL where clause. For example <code>" where doc.fullName
* <> ? and (doc.parent = ? or (doc.parent = ? and doc.space = ?))"</code>
* @param maxResults the number of rows to return. If 0 then all rows are returned
* @param startOffset the number of rows to skip. If 0 don't skip any row
* @param parameterValues the where clause values that replace the question marks (?)
* @return a list of document names
* @throws XWikiException in case of error while performing the query
* @deprecated use query service instead
*/
@Deprecated
public List<String> searchDocuments(String parameterizedWhereClause, int maxResults, int startOffset,
List< ? > parameterValues) throws XWikiException
{
return this.xwiki.getStore().searchDocumentsNames(parameterizedWhereClause, maxResults, startOffset,
parameterValues, getXWikiContext());
}
/**
* Same as {@link #searchDocuments(String, int, int, java.util.List)} but returns all rows.
*
* @see #searchDocuments(String, int, int, java.util.List)
* @deprecated use query service instead
*/
@Deprecated
public List<String> searchDocuments(String parameterizedWhereClause, List< ? > parameterValues)
throws XWikiException
{
return this.xwiki.getStore().searchDocumentsNames(parameterizedWhereClause, parameterValues, getXWikiContext());
}
/**
* Search documents in the provided wiki by passing HQL where clause values as parameters. See
* {@link #searchDocuments(String, int, int, java.util.List)} for more details.
*
* @param wikiName the name of the wiki where to search.
* @param parameterizedWhereClause the HQL where clause. For example <code>" where doc.fullName
* <> ? and (doc.parent = ? or (doc.parent = ? and doc.space = ?))"</code>
* @param maxResults the number of rows to return. If 0 then all rows are returned
* @param startOffset the number of rows to skip. If 0 don't skip any row
* @param parameterValues the where clause values that replace the question marks (?)
* @return a list of document full names (Space.Name).
* @see #searchDocuments(String, int, int, java.util.List)
* @throws XWikiException in case of error while performing the query
* @deprecated use query service instead
*/
@Deprecated
public List<String> searchDocumentsNames(String wikiName, String parameterizedWhereClause, int maxResults,
int startOffset, List< ? > parameterValues) throws XWikiException
{
String database = this.context.getWikiId();
try {
this.context.setWikiId(wikiName);
return searchDocuments(parameterizedWhereClause, maxResults, startOffset, parameterValues);
} finally {
this.context.setWikiId(database);
}
}
/**
* Search spaces by passing HQL where clause values as parameters. See
* {@link #searchDocuments(String, int, int, List)} for more about parameterized hql clauses.
*
* @param parametrizedSqlClause the HQL where clause. For example <code>" where doc.fullName
* <> ? and (doc.parent = ? or (doc.parent = ? and doc.space = ?))"</code>
* @param nb the number of rows to return. If 0 then all rows are returned
* @param start the number of rows to skip. If 0 don't skip any row
* @param parameterValues the where clause values that replace the question marks (?)
* @return a list of spaces names.
* @throws XWikiException in case of error while performing the query
*/
public List<String> searchSpacesNames(String parametrizedSqlClause, int nb, int start, List< ? > parameterValues)
throws XWikiException
{
return this.xwiki.getStore().search(
"select distinct doc.space from XWikiDocument doc " + parametrizedSqlClause, nb, start, parameterValues,
this.context);
}
/**
* Search attachments by passing HQL where clause values as parameters. See
* {@link #searchDocuments(String, int, int, List)} for more about parameterized hql clauses. You can specify
* properties of attach (the attachment) or doc (the document it is attached to)
*
* @param parametrizedSqlClause The HQL where clause. For example <code>" where doc.fullName
* <> ? and (attach.author = ? or (attach.filename = ? and doc.space = ?))"</code>
* @param nb The number of rows to return. If 0 then all rows are returned
* @param start The number of rows to skip at the beginning.
* @param parameterValues A {@link java.util.List} of the where clause values that replace the question marks (?)
* @return A List of {@link Attachment} objects.
* @throws XWikiException in case of error while performing the query
* @since 5.0M2
*/
@Unstable
public List<Attachment> searchAttachments(String parametrizedSqlClause, int nb, int start, List< ? > parameterValues)
throws XWikiException
{
return convertAttachments(this.xwiki.searchAttachments(parametrizedSqlClause, true, nb, start, parameterValues,
this.context));
}
/**
* Count attachments returned by a given parameterized query
*
* @param parametrizedSqlClause Everything which would follow the "WHERE" in HQL see:
* {@link #searchDocuments(String, int, int, List)}
* @param parameterValues A {@link java.util.List} of the where clause values that replace the question marks (?)
* @return int number of attachments found.
* @throws XWikiException
* @see #searchAttachments(String, int, int, List)
* @since 5.0M2
*/
@Unstable
public int countAttachments(String parametrizedSqlClause, List< ? > parameterValues) throws XWikiException
{
return this.xwiki.countAttachments(parametrizedSqlClause, parameterValues, this.context);
}
/**
* Function to wrap a list of XWikiDocument into Document objects
*
* @param docs list of XWikiDocument
* @return list of Document objects
*/
public List<Document> wrapDocs(List< ? > docs)
{
List<Document> result = new ArrayList<Document>();
if (docs != null) {
for (java.lang.Object obj : docs) {
try {
if (obj instanceof XWikiDocument) {
XWikiDocument doc = (XWikiDocument) obj;
Document wrappedDoc = doc.newDocument(getXWikiContext());
result.add(wrappedDoc);
} else if (obj instanceof Document) {
result.add((Document) obj);
} else if (obj instanceof String) {
Document doc = getDocument(obj.toString());
if (doc != null) {
result.add(doc);
}
}
} catch (XWikiException ex) {
}
}
}
return result;
}
/**
* API allowing to parse a text content to evaluate velocity scripts
*
* @param content
* @return evaluated content if the content contains velocity scripts
*/
public String parseContent(String content)
{
return this.xwiki.parseContent(content, getXWikiContext());
}
/**
* API to parse a velocity template provided by the current Skin The template is first looked in the skin active for
* the user, the space or the wiki. If the template does not exist in that skin, the template is looked up in the
* "parent skin" of the skin
*
* @param template Template name ("view", "edit", "comment")
* @return Evaluated content from the template
*/
public String parseTemplate(String template)
{
return this.xwiki.parseTemplate(template, getXWikiContext());
}
/**
* API to render a velocity template provided by the current Skin The template is first looked in the skin active
* for the user, the space or the wiki. If the template does not exist in that skin, the template is looked up in
* the "parent skin" of the skin
*
* @param template Template name ("view", "edit", "comment")
* @return Evaluated content from the template
*/
public String renderTemplate(String template)
{
return this.xwiki.renderTemplate(template, getXWikiContext());
}
/**
* Designed to include dynamic content, such as Servlets or JSPs, inside Velocity templates; works by creating a
* RequestDispatcher, buffering the output, then returning it as a string.
*
* @param url URL of the servlet
* @return text result of the servlet
*/
public String invokeServletAndReturnAsString(String url)
{
return this.xwiki.invokeServletAndReturnAsString(url, getXWikiContext());
}
/**
* Return the URL of the static file provided by the current skin The file is first looked in the skin active for
* the user, the space or the wiki. If the file does not exist in that skin, the file is looked up in the "parent
* skin" of the skin. The file can be a CSS file, an image file, a javascript file, etc.
*
* @param filename Filename to be looked up in the skin (logo.gif, style.css)
* @return URL to access this file
*/
public String getSkinFile(String filename)
{
return this.xwiki.getSkinFile(filename, getXWikiContext());
}
/**
* Return the URL of the static file provided by the current skin The file is first looked in the skin active for
* the user, the space or the wiki. If the file does not exist in that skin, the file is looked up in the "parent
* skin" of the skin. The file can be a CSS file, an image file, a javascript file, etc.
*
* @param filename Filename to be looked up in the skin (logo.gif, style.css)
* @param forceSkinAction true to make sure that static files are retrieved through the skin action, to allow
* parsing of velocity on CSS files
* @return URL to access this file
*/
public String getSkinFile(String filename, boolean forceSkinAction)
{
return this.xwiki.getSkinFile(filename, forceSkinAction, getXWikiContext());
}
/**
* API to retrieve the current skin for this request and user The skin is first derived from the request "skin"
* parameter If this parameter does not exist, the user preference "skin" is looked up If this parameter does not
* exist or is empty, the space preference "skin" is looked up If this parameter does not exist or is empty, the
* XWiki preference "skin" is looked up If this parameter does not exist or is empty, the xwiki.cfg parameter
* xwiki.defaultskin is looked up If this parameter does not exist or is empty, the xwiki.cfg parameter
* xwiki.defaultbaseskin is looked up If this parameter does not exist or is empty, the skin is "colibri"
*
* @return The current skin for this request and user
*/
public String getSkin()
{
return this.xwiki.getSkin(getXWikiContext());
}
/**
* API to retrieve the current skin for this request and user. Each skin has a skin it is based on. If not the base
* skin is the xwiki.cfg parameter "xwiki.defaultbaseskin". If this parameter does not exist or is empty, the base
* skin is "colibri".
*
* @return The current baseskin for this request and user
*/
public String getBaseSkin()
{
return this.xwiki.getBaseSkin(getXWikiContext());
}
public String getSpaceCopyright()
{
return this.xwiki.getSpaceCopyright(getXWikiContext());
}
/**
* API to access an XWiki Preference There can be one preference object per language This function will find the
* right preference object associated to the current active language
*
* @param preference Preference name
* @return The preference for this wiki and the current language
*/
public String getXWikiPreference(String preference)
{
return this.xwiki.getXWikiPreference(preference, getXWikiContext());
}
/**
* API to access an XWiki Preference There can be one preference object per language This function will find the
* right preference object associated to the current active language
*
* @param preference Preference name
* @param defaultValue default value to return if the prefenrece does not exist or is empty
* @return The preference for this wiki and the current language
*/
public String getXWikiPreference(String preference, String defaultValue)
{
return this.xwiki.getXWikiPreference(preference, defaultValue, getXWikiContext());
}
/**
* API to access an Space Preference There can be one preference object per language This function will find the
* right preference object associated to the current active language If no preference is found it will look in the
* XWiki Preferences
*
* @param preference Preference name
* @return The preference for this wiki and the current language
*/
public String getSpacePreference(String preference)
{
return this.xwiki.getSpacePreference(preference, getXWikiContext());
}
/**
* API to access an Space Preference There can be one preference object per language This function will find the
* right preference object associated to the current active language If no preference is found it will look in the
* XWiki Preferences
*
* @param preference Preference name
* @param space The space for which this preference is requested
* @return The preference for this wiki and the current language
*/
public String getSpacePreferenceFor(String preference, String space)
{
return this.xwiki.getSpacePreference(preference, space, "", getXWikiContext());
}
/**
* API to access an Space Preference There can be one preference object per language This function will find the
* right preference object associated to the current active language If no preference is found it will look in the
* XWiki Preferences
*
* @param preference Preference name
* @param defaultValue default value to return if the preference does not exist or is empty
* @return The preference for this wiki and the current language
*/
public String getSpacePreference(String preference, String defaultValue)
{
return this.xwiki.getSpacePreference(preference, defaultValue, getXWikiContext());
}
/**
* API to access a Skin Preference The skin object is the current user's skin
*
* @param preference Preference name
* @return The preference for the current skin
*/
public String getSkinPreference(String preference)
{
return this.xwiki.getSkinPreference(preference, getXWikiContext());
}
/**
* API to access a Skin Preference The skin object is the current user's skin
*
* @param preference Preference name
* @param defaultValue default value to return if the preference does not exist or is empty
* @return The preference for the current skin
*/
public String getSkinPreference(String preference, String defaultValue)
{
return this.xwiki.getSkinPreference(preference, defaultValue, getXWikiContext());
}
/**
* API to access an XWiki Preference as a long number There can be one preference object per language This function
* will find the right preference object associated to the current active language
*
* @param preference Preference name
* @param space The space for which this preference is requested
* @param defaultValue default value to return if the prefenrece does not exist or is empty
* @return The preference for this wiki and the current language in long format
*/
public String getSpacePreferenceFor(String preference, String space, String defaultValue)
{
return this.xwiki.getSpacePreference(preference, space, defaultValue, getXWikiContext());
}
/**
* API to access an XWiki Preference as a long number There can be one preference object per language This function
* will find the right preference object associated to the current active language
*
* @param preference Preference name
* @param defaultValue default value to return if the prefenrece does not exist or is empty
* @return The preference for this wiki and the current language in long format
*/
public long getXWikiPreferenceAsLong(String preference, long defaultValue)
{
return this.xwiki.getXWikiPreferenceAsLong(preference, defaultValue, getXWikiContext());
}
/**
* API to access an XWiki Preference as a long number There can be one preference object per language This function
* will find the right preference object associated to the current active language
*
* @param preference Preference name
* @return The preference for this wiki and the current language in long format
*/
public long getXWikiPreferenceAsLong(String preference)
{
return this.xwiki.getXWikiPreferenceAsLong(preference, getXWikiContext());
}
/**
* API to access a Space Preference as a long number There can be one preference object per language This function
* will find the right preference object associated to the current active language If no preference is found it will
* look for the XWiki Preference
*
* @param preference Preference name
* @param defaultValue default value to return if the prefenrece does not exist or is empty
* @return The preference for this wiki and the current language in long format
*/
public long getSpacePreferenceAsLong(String preference, long defaultValue)
{
return this.xwiki.getSpacePreferenceAsLong(preference, defaultValue, getXWikiContext());
}
/**
* API to access a Space Preference as a long number There can be one preference object per language This function
* will find the right preference object associated to the current active language If no preference is found it will
* look for the XWiki Preference
*
* @param preference Preference name
* @return The preference for this wiki and the current language in long format
*/
public long getSpacePreferenceAsLong(String preference)
{
return this.xwiki.getSpacePreferenceAsLong(preference, getXWikiContext());
}
/**
* API to access an XWiki Preference as an int number There can be one preference object per language This function
* will find the right preference object associated to the current active language
*
* @param preference Preference name
* @param defaultValue default value to return if the prefenrece does not exist or is empty
* @return The preference for this wiki and the current language in int format
*/
public int getXWikiPreferenceAsInt(String preference, int defaultValue)
{
return this.xwiki.getXWikiPreferenceAsInt(preference, defaultValue, getXWikiContext());
}
/**
* API to access an XWiki Preference as a int number There can be one preference object per language This function
* will find the right preference object associated to the current active language
*
* @param preference Preference name
* @return The preference for this wiki and the current language in int format
*/
public int getXWikiPreferenceAsInt(String preference)
{
return this.xwiki.getXWikiPreferenceAsInt(preference, getXWikiContext());
}
/**
* API to access a space Preference as a int number There can be one preference object per language This function
* will find the right preference object associated to the current active language If no preference is found it will
* look for the XWiki Preference
*
* @param preference Preference name
* @param defaultValue default value to return if the prefenrece does not exist or is empty
* @return The preference for this wiki and the current language in int format
*/
public int getSpacePreferenceAsInt(String preference, int defaultValue)
{
return this.xwiki.getSpacePreferenceAsInt(preference, defaultValue, getXWikiContext());
}
/**
* API to access a Space Preference as a int number There can be one preference object per language This function
* will find the right preference object associated to the current active language If no preference is found it will
* look for the XWiki Preference
*
* @param preference Preference name
* @return The preference for this wiki and the current language in int format
*/
public int getSpacePreferenceAsInt(String preference)
{
return this.xwiki.getSpacePreferenceAsInt(preference, getXWikiContext());
}
/**
* API to access a User Preference This function will look in the User profile for the preference If no preference
* is found it will look in the Space Preferences If no preference is found it will look in the XWiki Preferences
*
* @param preference Preference name
* @return The preference for this wiki and the current language
*/
public String getUserPreference(String preference)
{
return this.xwiki.getUserPreference(preference, getXWikiContext());
}
/**
* API to access a User Preference from cookie This function will look in the session cookie for the preference
*
* @param preference Preference name
* @return The preference for this wiki and the current language
*/
public String getUserPreferenceFromCookie(String preference)
{
return this.xwiki.getUserPreferenceFromCookie(preference, getXWikiContext());
}
/**
* First try to find the current language in use from the XWiki context. If none is used and if the wiki is not
* multilingual use the default language defined in the XWiki preferences. If the wiki is multilingual try to get
* the language passed in the request. If none was passed try to get it from a cookie. If no language cookie exists
* then use the user default language and barring that use the browser's "Accept-Language" header sent in HTTP
* request. If none is defined use the default language.
*
* @return the language to use
*/
public String getLanguagePreference()
{
return this.xwiki.getLanguagePreference(getXWikiContext());
}
/**
* API to access the interface language preference for the request Order of evaluation is: Language of the wiki in
* mono-lingual mode language request paramater language in context language user preference language in cookie
* language accepted by the navigator
*
* @return the document language preference for the request
*/
public String getInterfaceLanguagePreference()
{
return this.xwiki.getInterfaceLanguagePreference(getXWikiContext());
}
/**
* @return the list of all wiki names, including the main wiki, corresponding to the available wiki descriptors.
* Example: the descriptor for the wiki <i>wikiname</i> is a document in the main wiki, named
* <i>XWiki.XWikiServerWikiname</i>, containing an XWiki.XWikiServerClass object.
* @see com.xpn.xwiki.XWiki#getVirtualWikisDatabaseNames(XWikiContext)
*/
public List<String> getWikiNames()
{
List<String> result = new ArrayList<String>();
try {
result = this.xwiki.getVirtualWikisDatabaseNames(getXWikiContext());
} catch (Exception e) {
LOGGER.error("Failed to get the list of all wiki names", e);
}
return result;
}
/**
* Convenience method to ask if the current XWiki instance contains subwikis (in addition to the main wiki)
*
* @return true if at least 1 subwiki exists; false otherwise
* @see #getWikiNames()
*/
public boolean hasSubWikis()
{
return getWikiNames().size() > 1;
}
/**
* API to check is wiki is multi-lingual
*
* @return true for multi-lingual/false for mono-lingual
*/
public boolean isMultiLingual()
{
return this.xwiki.isMultiLingual(getXWikiContext());
}
/**
* Privileged API to flush the cache of the Wiki installation This flushed the cache of all wikis, all plugins, all
* renderers
*/
public void flushCache()
{
if (hasProgrammingRights()) {
this.xwiki.flushCache(getXWikiContext());
}
}
/**
* Privileged API to reset the rendering engine This would restore the rendering engine evaluation loop and take
* into account new configuration parameters
*/
public void resetRenderingEngine()
{
if (hasProgrammingRights()) {
try {
this.xwiki.resetRenderingEngine(getXWikiContext());
} catch (XWikiException e) {
}
}
}
/**
* Privileged API to create a new user from the request This API is used by RegisterNewUser wiki page
*
* @return true for success/false for failure
* @throws XWikiException
*/
public int createUser() throws XWikiException
{
return createUser(false, "edit");
}
/**
* Privileged API to create a new user from the request This API is used by RegisterNewUser wiki page This version
* sends a validation email to the user Configuration of validation email is in the XWiki Preferences
*
* @param withValidation true to send the validationemail
* @return true for success/false for failure
* @throws XWikiException
*/
public int createUser(boolean withValidation) throws XWikiException
{
return createUser(withValidation, "edit");
}
/**
* Privileged API to create a new user from the request This API is used by RegisterNewUser wiki page This version
* sends a validation email to the user Configuration of validation email is in the XWiki Preferences
*
* @param withValidation true to send the validation email
* @param userRights Rights to set for the user for it's own page(defaults to "edit")
* @return true for success/false for failure
* @throws XWikiException
*/
public int createUser(boolean withValidation, String userRights) throws XWikiException
{
boolean registerRight;
try {
// So, what's the register right for? This says that if the creator of the page
// (Admin) has programming rights, anybody can register. Is this OK?
if (hasProgrammingRights()) {
registerRight = true;
} else {
registerRight =
this.xwiki.getRightService().hasAccessLevel("register", getXWikiContext().getUser(),
"XWiki.XWikiPreferences", getXWikiContext());
}
if (registerRight) {
return this.xwiki.createUser(withValidation, userRights, getXWikiContext());
}
return -1;
} catch (Exception e) {
LOGGER.error("Failed to create user", e);
return -2;
}
}
/**
* Privileged API to validate the return code given by a user in response to an email validation email The
* validation information are taken from the request object
*
* @param withConfirmEmail true to send a account confirmation email/false to not send it
* @return Success of Failure code (0 for success, -1 for missing programming rights, > 0 for other errors
* @throws XWikiException
*/
public int validateUser(boolean withConfirmEmail) throws XWikiException
{
return this.xwiki.validateUser(withConfirmEmail, getXWikiContext());
}
/**
* Privileged API to add a user to the XWiki.XWikiAllGroup
*
* @param fullwikiname user name to add
* @throws XWikiException
*/
public void addToAllGroup(String fullwikiname) throws XWikiException
{
if (hasProgrammingRights()) {
this.xwiki.setUserDefaultGroup(fullwikiname, getXWikiContext());
}
}
/**
* Privileged API to send a confirmation email to a user
*
* @param xwikiname user to send the email to
* @param password password to put in the mail
* @param email email to send to
* @param add_message Additional message to send to the user
* @param contentfield Preference field to use as a mail template
* @throws XWikiException if the mail was not send successfully
*/
public void sendConfirmationMail(String xwikiname, String password, String email, String add_message,
String contentfield) throws XWikiException
{
if (hasProgrammingRights()) {
this.xwiki.sendConfirmationEmail(xwikiname, password, email, add_message, contentfield, getXWikiContext());
}
}
/**
* Privileged API to send a confirmation email to a user
*
* @param xwikiname user to send the email to
* @param password password to put in the mail
* @param email email to send to
* @param contentfield Preference field to use as a mail template
* @throws XWikiException if the mail was not send successfully
*/
public void sendConfirmationMail(String xwikiname, String password, String email, String contentfield)
throws XWikiException
{
if (hasProgrammingRights()) {
this.xwiki.sendConfirmationEmail(xwikiname, password, email, "", contentfield, getXWikiContext());
}
}
/**
* API to copy a document to another document in the same wiki
*
* @param docname source document
* @param targetdocname target document
* @return true if the copy was sucessfull
* @throws XWikiException if the document was not copied properly
*/
public boolean copyDocument(String docname, String targetdocname) throws XWikiException
{
return this.copyDocument(docname, targetdocname, null, null, null, false, false);
}
/**
* API to copy a translation of a document to another document in the same wiki
*
* @param docname source document
* @param targetdocname target document
* @param wikilanguage language to copy
* @return true if the copy was sucessfull
* @throws XWikiException if the document was not copied properly
*/
public boolean copyDocument(String docname, String targetdocname, String wikilanguage) throws XWikiException
{
return this.copyDocument(docname, targetdocname, null, null, wikilanguage, false, false);
}
/**
* API to copy a translation of a document to another document of the same name in another wiki
*
* @param docname source document
* @param sourceWiki source wiki
* @param targetWiki target wiki
* @param wikilanguage language to copy
* @return true if the copy was sucessfull
* @throws XWikiException if the document was not copied properly
*/
public boolean copyDocument(String docname, String sourceWiki, String targetWiki, String wikilanguage)
throws XWikiException
{
return this.copyDocument(docname, docname, sourceWiki, targetWiki, wikilanguage, true, false);
}
/**
* API to copy a translation of a document to another document of the same name in another wiki additionally
* resetting the version
*
* @param docname source document
* @param sourceWiki source wiki
* @param targetWiki target wiki
* @param wikilanguage language to copy
* @param reset true to reset versions
* @return true if the copy was sucessfull
* @throws XWikiException if the document was not copied properly
*/
public boolean copyDocument(String docname, String targetdocname, String sourceWiki, String targetWiki,
String wikilanguage, boolean reset) throws XWikiException
{
return this.copyDocument(docname, targetdocname, sourceWiki, targetWiki, wikilanguage, reset, false);
}
/**
* API to copy a translation of a document to another document of the same name in another wiki additionally
* resetting the version and overwriting the previous document
*
* @param docname source document name
* @param targetdocname target document name
* @param sourceWiki source wiki
* @param targetWiki target wiki
* @param wikilanguage language to copy
* @param reset true to reset versions
* @param force true to overwrite the previous document
* @return true if the copy was sucessfull
* @throws XWikiException if the document was not copied properly
*/
public boolean copyDocument(String docname, String targetdocname, String sourceWiki, String targetWiki,
String wikilanguage, boolean reset, boolean force) throws XWikiException
{
DocumentReference sourceDocumentReference = this.currentMixedDocumentReferenceResolver.resolve(docname);
if (!StringUtils.isEmpty(sourceWiki)) {
sourceDocumentReference =
sourceDocumentReference.replaceParent(sourceDocumentReference.getWikiReference(), new WikiReference(
sourceWiki));
}
DocumentReference targetDocumentReference = this.currentMixedDocumentReferenceResolver.resolve(targetdocname);
if (!StringUtils.isEmpty(targetWiki)) {
targetDocumentReference =
targetDocumentReference.replaceParent(targetDocumentReference.getWikiReference(), new WikiReference(
targetWiki));
}
return this.copyDocument(sourceDocumentReference, targetDocumentReference, wikilanguage, reset, force);
}
/**
* API to copy a translation of a document to another document of the same name in another wiki additionally
* resetting the version and overwriting the previous document
*
* @param sourceDocumentReference the reference to the document to copy
* @param targetDocumentReference the reference to the document to create
* @param wikilanguage language to copy
* @param resetHistory {@code true} to reset versions
* @param overwrite {@code true} to overwrite the previous document
* @return {@code true} if the copy was sucessful
* @throws XWikiException if the document was not copied properly
* @since 3.0M3
*/
public boolean copyDocument(DocumentReference sourceDocumentReference, DocumentReference targetDocumentReference,
String wikilanguage, boolean resetHistory, boolean overwrite) throws XWikiException
{
// In order to copy the source document the user must have at least the right to view it.
if (hasAccessLevel("view", this.defaultStringEntityReferenceSerializer.serialize(sourceDocumentReference))) {
String targetDocStringRef = this.defaultStringEntityReferenceSerializer.serialize(targetDocumentReference);
// To create the target document the user must have edit rights. If the target document exists and the user
// wants to overwrite it then he needs delete right.
// Note: We have to check if the target document exists before checking the delete right because delete
// right is denied if not explicitly specified.
if (hasAccessLevel("edit", targetDocStringRef)
&& (!overwrite || !exists(targetDocumentReference) || hasAccessLevel("delete", targetDocStringRef))) {
// Reset creation data otherwise the required rights for page copy need to be reconsidered.
return this.xwiki.copyDocument(sourceDocumentReference, targetDocumentReference, wikilanguage,
resetHistory, overwrite, true, getXWikiContext());
}
}
return false;
}
/**
* Privileged API to copy a space to another wiki, optionally deleting all document of the target space
*
* @param space source Space
* @param sourceWiki source Wiki
* @param targetWiki target Wiki
* @param language language to copy
* @param clean true to delete all document of the target space
* @return number of copied documents
* @throws XWikiException if the space was not copied properly
*/
public int copySpaceBetweenWikis(String space, String sourceWiki, String targetWiki, String language, boolean clean)
throws XWikiException
{
if (hasProgrammingRights()) {
return this.xwiki.copySpaceBetweenWikis(space, sourceWiki, targetWiki, language, clean, getXWikiContext());
}
return -1;
}
/**
* API to include a topic into another The topic is rendered fully in the context of itself
*
* @param topic page name of the topic to include
* @return the content of the included page
* @throws XWikiException if the include failed
*/
public String includeTopic(String topic) throws XWikiException
{
return includeTopic(topic, true);
}
/**
* API to execute a form in the context of an including topic The rendering is evaluated in the context of the
* including topic All velocity variables are the one of the including topic This api is usually called using
* #includeForm in a page, which modifies the behavior of "Edit this page" button to direct for Form mode (inline)
*
* @param topic page name of the form to execute
* @return the content of the included page
* @throws XWikiException if the include failed
*/
public String includeForm(String topic) throws XWikiException
{
return includeForm(topic, true);
}
/**
* API to include a topic into another, optionally surrounding the content with {pre}{/pre} to avoid future wiki
* rendering. The topic is rendered fully in the context of itself.
*
* @param topic page name of the topic to include
* @param pre true to add {pre} {/pre} (only if includer document is 1.0 syntax)
* @return the content of the included page
* @throws XWikiException if the include failed
*/
public String includeTopic(String topic, boolean pre) throws XWikiException
{
String result = this.xwiki.include(topic, false, getXWikiContext());
if (pre) {
String includerSyntax = this.xwiki.getCurrentContentSyntaxId(null, this.context);
if (includerSyntax != null && Syntax.XWIKI_1_0.toIdString().equals(includerSyntax)) {
result = "{pre}" + result + "{/pre}";
}
}
return result;
}
/**
* API to execute a form in the context of an including topic, optionnaly surrounding the content with {pre}{/pre}
* to avoid future wiki rendering The rendering is evaluated in the context of the including topic All velocity
* variables are the one of the including topic This api is usually called using #includeForm in a page, which
* modifies the behavior of "Edit this page" button to direct for Form mode (inline).
*
* @param topic page name of the form to execute
* @param pre true to add {pre} {/pre} (only if includer document is 1.0 syntax)
* @return the content of the included page
* @throws XWikiException if the include failed
*/
public String includeForm(String topic, boolean pre) throws XWikiException
{
String result = this.xwiki.include(topic, true, getXWikiContext());
if (pre) {
String includerSyntax = this.xwiki.getCurrentContentSyntaxId(null, this.context);
if (includerSyntax != null && Syntax.XWIKI_1_0.toIdString().equals(includerSyntax)) {
result = "{pre}" + result + "{/pre}";
}
}
return result;
}
/**
* API to check rights on the current document for the current user
*
* @param level right to check (view, edit, comment, delete)
* @return true if right is granted/false if not
*/
public boolean hasAccessLevel(String level)
{
return hasAccessLevel(level, getXWikiContext().getUser(), getXWikiContext().getDoc().getFullName());
}
/**
* API to check rights on a document for a given user
*
* @param level right to check (view, edit, comment, delete)
* @param user user for which to check the right
* @param docname document on which to check the rights
* @return true if right is granted/false if not
*/
public boolean hasAccessLevel(String level, String user, String docname)
{
try {
return this.xwiki.getRightService().hasAccessLevel(level, user, docname, getXWikiContext());
} catch (Exception e) {
return false;
}
}
/**
* API to render a text in the context of a document
*
* @param text text to render
* @param doc the text is evaluated in the content of this document
* @return evaluated content
* @throws XWikiException if the evaluation went wrong
*/
public String renderText(String text, Document doc) throws XWikiException
{
return this.xwiki.getRenderingEngine().renderText(text, doc.getDoc(), getXWikiContext());
}
/**
* API to render a chunk (difference between two versions
*
* @param chunk difference between versions to render
* @param doc document to use as a context for rendering
* @return resuilt of the rendering
*/
public String renderChunk(Chunk chunk, Document doc)
{
return renderChunk(chunk, false, doc);
}
/**
* API to render a chunk (difference between two versions
*
* @param chunk difference between versions to render
* @param doc document to use as a context for rendering
* @param source true to render the difference as wiki source and not as wiki rendered text
* @return resuilt of the rendering
*/
public String renderChunk(Chunk chunk, boolean source, Document doc)
{
StringBuffer buf = new StringBuffer();
chunk.toString(buf, "", "\n");
if (source == true) {
return buf.toString();
}
try {
return this.xwiki.getRenderingEngine().renderText(buf.toString(), doc.getDoc(), getXWikiContext());
} catch (Exception e) {
return buf.toString();
}
}
/**
* API to list all non-hidden spaces in the current wiki.
*
* @return a list of string representing all non-hidden spaces (ie spaces that have non-hidden pages) for the
* current wiki
* @throws XWikiException if something went wrong
*/
public List<String> getSpaces() throws XWikiException
{
return this.xwiki.getSpaces(getXWikiContext());
}
/**
* API to list all non-hidden documents in a space.
*
* @param spaceName the space for which to return all non-hidden documents
* @return the list of document names (in the format {@code Space.Page}) for non-hidden documents in the specified
* space
* @throws XWikiException if the loading went wrong
*/
public List<String> getSpaceDocsName(String spaceName) throws XWikiException
{
return this.xwiki.getSpaceDocsName(spaceName, getXWikiContext());
}
/**
* API to retrieve the current encoding of the wiki engine The encoding is stored in xwiki.cfg Default encoding is
* ISO-8891-1
*
* @return encoding active in this wiki
*/
public String getEncoding()
{
return this.xwiki.getEncoding();
}
public String getAttachmentURL(String fullname, String filename) throws XWikiException
{
return this.xwiki.getAttachmentURL(fullname, filename, getXWikiContext());
}
public String getURL(String fullname) throws XWikiException
{
return this.xwiki.getURL(fullname, "view", getXWikiContext());
}
public String getURL(DocumentReference reference) throws XWikiException
{
return this.xwiki.getURL(reference, "view", getXWikiContext());
}
public String getURL(String fullname, String action) throws XWikiException
{
return this.xwiki.getURL(fullname, action, getXWikiContext());
}
public String getURL(String fullname, String action, String querystring) throws XWikiException
{
return this.xwiki.getURL(fullname, action, querystring, getXWikiContext());
}
public String getURL(DocumentReference reference, String action, String querystring) throws XWikiException
{
return this.xwiki.getURL(reference, action, querystring, null, getXWikiContext());
}
public String getURL(String fullname, String action, String querystring, String anchor) throws XWikiException
{
return this.xwiki.getURL(fullname, action, querystring, anchor, getXWikiContext());
}
public String getRefererText(String referer)
{
try {
return this.xwiki.getRefererText(referer, getXWikiContext());
} catch (Exception e) {
return "";
}
}
public String getShortRefererText(String referer, int length)
{
try {
return this.xwiki.getRefererText(referer, getXWikiContext()).substring(0, length);
} catch (Exception e) {
return this.xwiki.getRefererText(referer, getXWikiContext());
}
}
/**
* API to retrieve a link to the User Name page displayed for the first name and last name of the user. The link
* will link to the page on the wiki where the user is registered
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getUserName(String user)
{
return this.xwiki.getUserName(user, null, getXWikiContext());
}
/**
* API to retrieve a link to the User Name page displayed with a custom view. The link will link to the page on the
* wiki where the user is registered. The formating is done using the format parameter which can contain velocity
* scripting and access all properties of the User profile using variables ($first_name $last_name $email $city)
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @param format formatting to be used ("$first_name $last_name", "$first_name")
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getUserName(String user, String format)
{
return this.xwiki.getUserName(user, format, getXWikiContext());
}
/**
* API to retrieve a link to the User Name page displayed for the first name and last name of the user. The link
* will link to the page on the local wiki even if the user is registered on a different wiki.
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getLocalUserName(String user)
{
try {
return this.xwiki.getUserName(user.substring(user.indexOf(":") + 1), null, getXWikiContext());
} catch (Exception e) {
return this.xwiki.getUserName(user, null, getXWikiContext());
}
}
/**
* API to retrieve a link to the User Name page displayed with a custom view. The link will link to the page on the
* local wiki even if the user is registered on a different wiki. The formating is done using the format parameter
* which can contain velocity scripting and access all properties of the User profile using variables ($first_name
* $last_name $email $city)
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @param format formatting to be used ("$first_name $last_name", "$first_name")
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getLocalUserName(String user, String format)
{
try {
return this.xwiki.getUserName(user.substring(user.indexOf(":") + 1), format, getXWikiContext());
} catch (Exception e) {
return this.xwiki.getUserName(user, format, getXWikiContext());
}
}
/**
* API to retrieve a text representing the user with the first name and last name of the user. With the link param
* set to false it will not link to the user page With the link param set to true, the link will link to the page on
* the wiki where the user was registered.
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @param link false to not add an HTML link to the user profile
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getUserName(String user, boolean link)
{
return this.xwiki.getUserName(user, null, link, getXWikiContext());
}
/**
* API to retrieve a text representing the user with a custom view With the link param set to false it will not link
* to the user page. With the link param set to true, the link will link to the page on the wiki where the user was
* registered. The formating is done using the format parameter which can contain velocity scripting and access all
* properties of the User profile using variables ($first_name $last_name $email $city)
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @param format formatting to be used ("$first_name $last_name", "$first_name")
* @param link false to not add an HTML link to the user profile
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getUserName(String user, String format, boolean link)
{
return this.xwiki.getUserName(user, format, link, getXWikiContext());
}
/**
* API to retrieve a text representing the user with the first name and last name of the user. With the link param
* set to false it will not link to the user page. With the link param set to true, the link will link to the page
* on the local wiki even if the user is registered on a different wiki.
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @param link false to not add an HTML link to the user profile
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getLocalUserName(String user, boolean link)
{
try {
return this.xwiki.getUserName(user.substring(user.indexOf(":") + 1), null, link, getXWikiContext());
} catch (Exception e) {
return this.xwiki.getUserName(user, null, link, getXWikiContext());
}
}
/**
* API to retrieve a text representing the user with a custom view. The formating is done using the format parameter
* which can contain velocity scripting and access all properties of the User profile using variables ($first_name
* $last_name $email $city). With the link param set to false it will not link to the user page. With the link param
* set to true, the link will link to the page on the local wiki even if the user is registered on a different wiki.
*
* @param user Fully qualified username as retrieved from $context.user (XWiki.LudovicDubost)
* @param format formatting to be used ("$first_name $last_name", "$first_name")
* @param link false to not add an HTML link to the user profile
* @return The first name and last name fields surrounded with a link to the user page
*/
public String getLocalUserName(String user, String format, boolean link)
{
try {
return this.xwiki.getUserName(user.substring(user.indexOf(":") + 1), format, link, getXWikiContext());
} catch (Exception e) {
return this.xwiki.getUserName(user, format, link, getXWikiContext());
}
}
public User getUser()
{
return this.xwiki.getUser(getXWikiContext());
}
public User getUser(String username)
{
return this.xwiki.getUser(username, getXWikiContext());
}
/**
* API allowing to format a date according to the default Wiki setting The date format is provided in the
* 'dateformat' parameter of the XWiki Preferences
*
* @param date date object to format
* @return A string with the date formating from the default Wiki setting
*/
public String formatDate(Date date)
{
return this.xwiki.formatDate(date, null, getXWikiContext());
}
/**
* API allowing to format a date according to a custom format The date format is from java.text.SimpleDateFormat
* Example: "dd/MM/yyyy HH:mm:ss" or "d MMM yyyy" If the format is invalid the default format will be used to show
* the date
*
* @param date date to format
* @param format format of the date to be used
* @return the formatted date
* @see java.text.SimpleDateFormat
*/
public String formatDate(Date date, String format)
{
return this.xwiki.formatDate(date, format, getXWikiContext());
}
/*
* Allow to read user setting providing the user timezone All dates will be expressed with this timezone @return the
* timezone
*/
public String getUserTimeZone()
{
return this.xwiki.getUserTimeZone(this.context);
}
public Api get(String name)
{
return this.xwiki.getPluginApi(name, getXWikiContext());
}
/**
* Returns a plugin from the plugin API. Plugin Rights can be verified.
*
* @param name Name of the plugin to retrieve (either short of full class name)
* @return a plugin object
*/
public Api getPlugin(String name)
{
return this.xwiki.getPluginApi(name, getXWikiContext());
}
/**
* Returns the Advertisement system from the preferences
*
* @return "google" or "none"
*/
public String getAdType()
{
return this.xwiki.getAdType(getXWikiContext());
}
/**
* Returns the Advertisement client ID from the preferences
*
* @return an Ad affiliate ID
*/
public String getAdClientId()
{
return this.xwiki.getAdClientId(getXWikiContext());
}
/**
* Returns the content of an HTTP/HTTPS URL protected using Basic Authentication
*
* @param surl url to retrieve
* @param username username for the basic authentication
* @param password password for the basic authentication
* @return Content of the specified URL
* @throws IOException
*/
public String getURLContent(String surl, String username, String password) throws IOException
{
try {
return this.xwiki.getURLContent(surl, username, password, this.context);
} catch (Exception e) {
LOGGER.warn("Failed to retrieve content from [" + surl + "]", e);
return "";
}
}
/**
* Returns the content of an HTTP/HTTPS URL
*
* @param surl url to retrieve
* @return Content of the specified URL
* @throws IOException
*/
public String getURLContent(String surl) throws IOException
{
try {
return this.xwiki.getURLContent(surl, this.context);
} catch (Exception e) {
LOGGER.warn("Failed to retrieve content from [" + surl + "]", e);
return "";
}
}
/**
* Returns the content of an HTTP/HTTPS URL protected using Basic Authentication
*
* @param surl url to retrieve
* @param username username for the basic authentication
* @param password password for the basic authentication
* @param timeout manuel timeout in milliseconds
* @return Content of the specified URL
* @throws IOException
*/
public String getURLContent(String surl, String username, String password, int timeout) throws IOException
{
try {
return this.xwiki.getURLContent(surl, username, password, timeout,
this.xwiki.getHttpUserAgent(this.context));
} catch (Exception e) {
return "";
}
}
/**
* Returns the content of an HTTP/HTTPS URL
*
* @param surl url to retrieve
* @param timeout manuel timeout in milliseconds
* @return Content of the specified URL
* @throws IOException
*/
public String getURLContent(String surl, int timeout) throws IOException
{
try {
return this.xwiki.getURLContent(surl, timeout, this.xwiki.getHttpUserAgent(this.context));
} catch (Exception e) {
return "";
}
}
/**
* Returns the content of an HTTP/HTTPS URL protected using Basic Authentication as Bytes
*
* @param surl url to retrieve
* @param username username for the basic authentication
* @param password password for the basic authentication
* @return Content of the specified URL
* @throws IOException
*/
public byte[] getURLContentAsBytes(String surl, String username, String password) throws IOException
{
try {
return this.xwiki.getURLContentAsBytes(surl, username, password, this.context);
} catch (Exception e) {
return null;
}
}
/**
* Returns the content of an HTTP/HTTPS URL as Bytes
*
* @param surl url to retrieve
* @return Content of the specified URL
* @throws IOException
*/
public byte[] getURLContentAsBytes(String surl) throws IOException
{
try {
return this.xwiki.getURLContentAsBytes(surl, this.context);
} catch (Exception e) {
return null;
}
}
/**
* Returns the list of Macros documents in the specified content
*
* @param defaultSpace Default space to use for relative path names
* @param content Content to parse
* @return ArrayList of document names
*/
public List<String> getIncludedMacros(String defaultSpace, String content)
{
return this.xwiki.getIncludedMacros(defaultSpace, content, getXWikiContext());
}
/**
* returns true if xwiki.readonly is set in the configuration file
*
* @return the value of xwiki.isReadOnly()
* @see com.xpn.xwiki.XWiki
*/
public boolean isReadOnly()
{
return this.xwiki.isReadOnly();
}
/**
* Privileged API to set/unset the readonly status of the Wiki After setting this to true no writing to the database
* will be performed All Edit buttons will be removed and save actions disabled This is used for maintenance
* purposes
*
* @param ro true to set read-only mode/false to unset
*/
public void setReadOnly(boolean ro)
{
if (hasAdminRights()) {
this.xwiki.setReadOnly(ro);
}
}
/**
* Priviledge API to regenerate the links/backlinks table Normally links and backlinks are stored when a page is
* modified This function will regenerate all the backlinks This function can be long to run
*
* @throws XWikiException exception if the generation fails
*/
public void refreshLinks() throws XWikiException
{
if (hasAdminRights()) {
this.xwiki.refreshLinks(getXWikiContext());
}
}
/**
* API to check if the backlinks feature is active Backlinks are activated in xwiki.cfg or in the XWiki Preferences
*
* @return true if the backlinks feature is active
* @throws XWikiException exception if the preference could not be retrieved
*/
public boolean hasBacklinks() throws XWikiException
{
return this.xwiki.hasBacklinks(getXWikiContext());
}
/**
* API to check if the tags feature is active. Tags are activated in xwiki.cfg or in the XWiki Preferences
*
* @return true if the tags feature is active, false otherwise
* @throws XWikiException exception if the preference could not be retrieved
*/
public boolean hasTags() throws XWikiException
{
return this.xwiki.hasTags(getXWikiContext());
}
/**
* API to check if the edit comment feature is active Edit comments are activated in xwiki.cfg or in the XWiki
* Preferences
*
* @return
*/
public boolean hasEditComment()
{
return this.xwiki.hasEditComment(this.context);
}
/**
* API to check if the edit comment field is shown in the edit form Edit comments are activated in xwiki.cfg or in
* the XWiki Preferences
*
* @return
*/
public boolean isEditCommentFieldHidden()
{
return this.xwiki.isEditCommentFieldHidden(this.context);
}
/**
* API to check if the edit comment is suggested (prompted once by Javascript if empty) Edit comments are activated
* in xwiki.cfg or in the XWiki Preferences
*
* @return
*/
public boolean isEditCommentSuggested()
{
return this.xwiki.isEditCommentSuggested(this.context);
}
/**
* API to check if the edit comment is mandatory (prompted by Javascript if empty) Edit comments are activated in
* xwiki.cfg or in the XWiki Preferences
*
* @return
*/
public boolean isEditCommentMandatory()
{
return this.xwiki.isEditCommentMandatory(this.context);
}
/**
* API to check if the minor edit feature is active minor edit is activated in xwiki.cfg or in the XWiki Preferences
*/
public boolean hasMinorEdit()
{
return this.xwiki.hasMinorEdit(this.context);
}
/**
* API to check if the recycle bin feature is active recycle bin is activated in xwiki.cfg or in the XWiki
* Preferences
*/
public boolean hasRecycleBin()
{
return this.xwiki.hasRecycleBin(this.context);
}
/**
* API to rename a page (experimental) Rights are necessary to edit the source and target page All objects and
* attachments ID are modified in the process to link to the new page name
*
* @param doc page to rename
* @param newFullName target page name to move the information to
*/
public boolean renamePage(Document doc, String newFullName)
{
try {
if (this.xwiki.exists(newFullName, getXWikiContext())
&& !this.xwiki.getRightService().hasAccessLevel("delete", getXWikiContext().getUser(), newFullName,
getXWikiContext())) {
return false;
}
if (this.xwiki.getRightService().hasAccessLevel("edit", getXWikiContext().getUser(), doc.getFullName(),
getXWikiContext())) {
this.xwiki.renamePage(doc.getFullName(), newFullName, getXWikiContext());
}
} catch (XWikiException e) {
return false;
}
return true;
}
/**
* Retrieves the current editor preference for the request The preference is first looked up in the user preference
* and then in the space and wiki preference
*
* @return "wysiwyg" or "text"
*/
public String getEditorPreference()
{
return this.xwiki.getEditorPreference(getXWikiContext());
}
/**
* Privileged API to retrieve an object instantiated from groovy code in a String. Note that Groovy scripts
* compilation is cached.
*
* @param script the Groovy class definition string (public class MyClass { ... })
* @return An object instantiating this class
* @throws XWikiException
*/
public java.lang.Object parseGroovyFromString(String script) throws XWikiException
{
if (hasProgrammingRights()) {
return this.xwiki.parseGroovyFromString(script, getXWikiContext());
}
return "groovy_missingrights";
}
/**
* Privileged API to retrieve an object instantiated from groovy code in a String, using a classloader including all
* JAR files located in the passed page as attachments. Note that Groovy scripts compilation is cached
*
* @param script the Groovy class definition string (public class MyClass { ... })
* @return An object instantiating this class
* @throws XWikiException
*/
public java.lang.Object parseGroovyFromPage(String script, String jarWikiPage) throws XWikiException
{
XWikiDocument doc = this.xwiki.getDocument(script, getXWikiContext());
if (this.xwiki.getRightService().hasProgrammingRights(doc, getXWikiContext())) {
return this.xwiki.parseGroovyFromString(doc.getContent(), jarWikiPage, getXWikiContext());
}
return "groovy_missingrights";
}
/**
* Privileged API to retrieve an object instanciated from groovy code in a String Groovy scripts compilation is
* cached
*
* @param fullname // script containing a Groovy class definition (public class MyClass { ... })
* @return An object instanciating this class
* @throws XWikiException
*/
public java.lang.Object parseGroovyFromPage(String fullname) throws XWikiException
{
XWikiDocument doc = this.xwiki.getDocument(fullname, getXWikiContext());
if (this.xwiki.getRightService().hasProgrammingRights(doc, getXWikiContext())) {
return this.xwiki.parseGroovyFromString(doc.getContent(), getXWikiContext());
}
return "groovy_missingrights";
}
/**
* API to get the macro list from the XWiki Preferences The macro list are the macros available from the Macro
* Mapping System
*
* @return String with each macro on each line
*/
public String getMacroList()
{
return this.xwiki.getMacroList(getXWikiContext());
}
/**
* API to check if using which toolbars in Wysiwyg editor
*
* @return a string value
*/
public String getWysiwygToolbars()
{
return this.xwiki.getWysiwygToolbars(getXWikiContext());
}
/**
* API to create an object from the request The parameters are the ones that are created from
* doc.display("field","edit") calls
*
* @param className XWiki Class Name to create the object from
* @return a BaseObject wrapped in an Object
* @throws XWikiException exception if the object could not be read
*/
public com.xpn.xwiki.api.Object getObjectFromRequest(String className) throws XWikiException
{
return new com.xpn.xwiki.api.Object(this.xwiki.getObjectFromRequest(className, getXWikiContext()),
getXWikiContext());
}
/**
* API to create an empty document
*
* @return an XWikiDocument wrapped in a Document
*/
public Document createDocument()
{
return new XWikiDocument().newDocument(getXWikiContext());
}
/**
* API to convert the username depending on the configuration The username can be converted from email to a valid
* XWiki page name hidding the email address The username can be then used to login and link to the right user page
*
* @param username username to use for login
* @return converted wiki page name for this username
*/
public String convertUsername(String username)
{
return this.xwiki.convertUsername(username, getXWikiContext());
}
/**
* API to get the Property object from a class based on a property path A property path looks like
* XWiki.ArticleClass_fieldname
*
* @param propPath Property path
* @return a PropertyClass object from a BaseClass object
*/
public com.xpn.xwiki.api.PropertyClass getPropertyClassFromName(String propPath)
{
return new PropertyClass(this.xwiki.getPropertyClassFromName(propPath, getXWikiContext()), getXWikiContext());
}
/**
* Generates a unique page name based on initial page name and already existing pages
*
* @param name
* @return a unique page name
*/
public String getUniquePageName(String name)
{
return this.xwiki.getUniquePageName(name, getXWikiContext());
}
/**
* Generates a unique page name based on initial page name and already existing pages
*
* @param space
* @param name
* @return a unique page name
*/
public String getUniquePageName(String space, String name)
{
return this.xwiki.getUniquePageName(space, name, getXWikiContext());
}
/**
* Inserts a tooltip using toolTip.js
*
* @param html HTML viewed
* @param message HTML Tooltip message
* @param params Parameters in Javascropt added to the tooltip config
* @return HTML with working tooltip
*/
public String addTooltip(String html, String message, String params)
{
return this.xwiki.addTooltip(html, message, params, getXWikiContext());
}
/**
* Inserts a tooltip using toolTip.js
*
* @param html HTML viewed
* @param message HTML Tooltip message
* @return HTML with working tooltip
*/
public String addTooltip(String html, String message)
{
return this.xwiki.addTooltip(html, message, getXWikiContext());
}
/**
* Inserts the tooltip Javascript
*
* @return
*/
public String addTooltipJS()
{
return this.xwiki.addTooltipJS(getXWikiContext());
}
/*
* Inserts a Mandatory asterix
*/
public String addMandatory()
{
return this.xwiki.addMandatory(getXWikiContext());
}
/**
* Get the XWiki Class object defined in the passed Document name.
* <p>
* Note: This method doesn't require any rights for accessing the passed Document (as opposed to the
* {@link com.xpn.xwiki.api.Document#getClass()} method which does require to get a Document object first. This is
* thus useful in cases where the calling code doesn't have the access right to the specified Document. It is safe
* because there are no sensitive data stored in a Class definition.
* </p>
*
* @param documentName the name of the document for which to get the Class object. For example
* "XWiki.XWikiPreferences"
* @return the XWiki Class object defined in the passed Document name. If the passed Document name points to a
* Document with no Class defined then an empty Class object is returned (i.e. a Class object with no
* properties).
* @throws XWikiException if the passed document name doesn't point to a valid Document
*/
public Class getClass(String documentName) throws XWikiException
{
// TODO: The implementation should be done in com.xpn.xwiki.XWiki as this class should
// delegate all implementations to that Class.
DocumentReference docReference = this.currentMixedDocumentReferenceResolver.resolve(documentName);
return new Class(this.xwiki.getDocument(docReference, this.context).getXClass(), this.context);
}
/**
* Provides an absolute counter
*
* @param name Counter name
* @return String
*/
public String getCounter(String name)
{
XWikiEngineContext econtext = this.context.getEngineContext();
Integer counter = (Integer) econtext.getAttribute(name);
if (counter == null) {
counter = new Integer(0);
}
counter = new Integer(counter.intValue() + 1);
econtext.setAttribute(name, counter);
return counter.toString();
}
/**
* Check authentication from request and set according persitent login information If it fails user is unlogged
*
* @return null if failed, non null XWikiUser if sucess
* @throws XWikiException
*/
public XWikiUser checkAuth() throws XWikiException
{
return this.context.getWiki().getAuthService().checkAuth(this.context);
}
/**
* Check authentication from username and password and set according persitent login information If it fails user is
* unlogged
*
* @param username username to check
* @param password password to check
* @param rememberme "1" if you want to remember the login accross navigator restart
* @return null if failed, non null XWikiUser if sucess
* @throws XWikiException
*/
public XWikiUser checkAuth(String username, String password, String rememberme) throws XWikiException
{
return this.context.getWiki().getAuthService().checkAuth(username, password, rememberme, this.context);
}
/**
* Access statistics api
*
* @return a StatsService instance that can be used to retrieve different xwiki statistics
*/
public StatsService getStatsService()
{
return this.statsService;
}
/**
* API to get the xwiki criteria service which allow to create various criteria : integer ranges, date periods, date
* intervals, etc.
*
* @return the xwiki criteria service
*/
public CriteriaService getCriteriaService()
{
return this.criteriaService;
}
/**
* @return the ids of configured syntaxes for this wiki (eg "xwiki/1.0", "xwiki/2.0", "mediawiki/1.0", etc)
*/
public List<String> getConfiguredSyntaxes()
{
return this.xwiki.getConfiguredSyntaxes();
}
/**
* API to get the Servlet path for a given wiki. In mono wiki this is "bin/" or "xwiki/". In virtual mode and if
* <tt>xwiki.virtual.usepath</tt> is enabled in xwiki.cfg, it is "wiki/wikiname/".
*
* @param wikiName wiki for which to get the path
* @return The servlet path
*/
public String getServletPath(String wikiName)
{
return this.xwiki.getServletPath(wikiName, this.context);
}
/**
* API to get the Servlet path for the current wiki. In mono wiki this is "bin/" or "xwiki/". In virtual mode and if
* <tt>xwiki.virtual.usepath</tt> is enabled in xwiki.cfg, it is "wiki/wikiname/".
*
* @return The servlet path
*/
public String getServletPath()
{
return this.xwiki.getServletPath(this.context.getWikiId(), this.context);
}
/**
* API to get the webapp path for the current wiki. This usually is "xwiki/". It can be configured in xwiki.cfg with
* the config <tt>xwiki.webapppath</tt>.
*
* @return The servlet path
*/
public String getWebAppPath()
{
return this.xwiki.getWebAppPath(this.context);
}
/**
* @return the syntax id of the syntax to use when creating new documents.
*/
public String getDefaultDocumentSyntax()
{
return this.xwiki.getDefaultDocumentSyntax();
}
/**
* Find the corresponding available renderer syntax.
* <p>
* If <code>syntaxVersion</code> is null the last version of the available provided syntax type is returned.
*
* @param syntaxType the syntax type
* @param syntaxVersion the syntax version
* @return the available corresponding {@link Syntax}. Null if no available renderer can be found.
*/
public Syntax getAvailableRendererSyntax(String syntaxType, String syntaxVersion)
{
Syntax syntax = null;
try {
List<PrintRendererFactory> factories =
Utils.getContextComponentManager().getInstanceList((Type) PrintRendererFactory.class);
for (PrintRendererFactory factory : factories) {
Syntax factorySyntax = factory.getSyntax();
if (syntaxVersion != null) {
if (factorySyntax.getType().getId().equalsIgnoreCase(syntaxType)
&& factorySyntax.getVersion().equals(syntaxVersion)) {
syntax = factorySyntax;
break;
}
} else {
// TODO: improve version comparaison since it does not work when comparing 2.0 and 10.0 for example.
// should have a Version which implements Comparable like we have SyntaxId in Syntax
if (factorySyntax.getType().getId().equalsIgnoreCase(syntaxType)
&& (syntax == null || factorySyntax.getVersion().compareTo(syntax.getVersion()) > 0)) {
syntax = factorySyntax;
}
}
}
} catch (ComponentLookupException e) {
LOGGER.error("Failed to lookup available renderer syntaxes", e);
}
return syntax;
}
/**
* @return the section depth for which section editing is available (can be configured through
* {@code xwiki.section.depth} configuration property. Defaults to 2 when not defined
*/
public long getSectionEditingDepth()
{
return this.xwiki.getSectionEditingDepth();
}
/**
* @return true if title handling should be using the compatibility mode or not. When the compatibility mode is
* active, if the document's content first header (level 1 or level 2) matches the document's title the
* first header is stripped.
*/
public boolean isTitleInCompatibilityMode()
{
return this.xwiki.isTitleInCompatibilityMode();
}
/**
* Get the syntax of the document currently being executed.
* <p>
* The document currently being executed is not the same than the context document since when including a page with
* velocity #includeForm(), method for example the context doc is the includer document even if includeForm() fully
* execute and render the included document before insert it in the includer document.
* <p>
* If the current document can't be found, the method assume that the executed document is the context document
* (it's generally the case when a document is directly rendered with
* {@link XWikiDocument#getRenderedContent(XWikiContext)} for example).
*
* @return the syntax identifier
*/
public String getCurrentContentSyntaxId()
{
return this.xwiki.getCurrentContentSyntaxId(getXWikiContext());
}
}
|
package com.justdavis.karl.misc.datasources.provisioners;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.justdavis.karl.misc.datasources.IDataSourceCoordinates;
/**
* This class is a user friendly front-end to the various
* {@link IDataSourceProvisioner} implementations. The
* {@link #provision(IProvisioningRequest)} method will select the correct
* {@link IDataSourceProvisioner} implementation to meet the specified request
* and will find a usable {@link IProvisioningTarget} from those provided by the
* specified {@link IProvisioningTargetsProvider}.
*
* @see IProvisioningTargetsProvider
* @see XmlProvisioningTargetsProvider
*/
@Component
public final class DataSourceProvisionersManager {
private final Set<IDataSourceProvisioner<? extends IDataSourceCoordinates, ? extends IProvisioningTarget, ? extends IProvisioningRequest>> provisioners;
/**
* Constructs a new {@link DataSourceProvisionersManager} instance.
*
* @param provisioners
* the available {@link IDataSourceProvisioner}s
*/
@Inject
public DataSourceProvisionersManager(
Set<IDataSourceProvisioner<? extends IDataSourceCoordinates, ? extends IProvisioningTarget, ? extends IProvisioningRequest>> provisioners) {
if (provisioners == null)
throw new IllegalArgumentException();
if (provisioners.isEmpty())
throw new IllegalArgumentException();
this.provisioners = provisioners;
}
/**
* Constructs a new {@link DataSourceProvisionersManager} instance.
*
* @param provisioners
* the available {@link IDataSourceProvisioner}s
*/
public DataSourceProvisionersManager(
IDataSourceProvisioner<? extends IDataSourceCoordinates, ? extends IProvisioningTarget, ? extends IProvisioningRequest>... provisioners) {
this(
new HashSet<IDataSourceProvisioner<? extends IDataSourceCoordinates, ? extends IProvisioningTarget, ? extends IProvisioningRequest>>(
Arrays.asList(provisioners)));
}
/**
* @return the available {@link IDataSourceProvisioner}s
*/
public Set<IDataSourceProvisioner<? extends IDataSourceCoordinates, ? extends IProvisioningTarget, ? extends IProvisioningRequest>> getProvisioners() {
return provisioners;
}
/**
* A user-friendly alternative to
* {@link IDataSourceProvisioner#provision(IProvisioningTarget, IProvisioningRequest)}
* .
*
* @param targetsProvider
* the {@link IProvisioningTargetsProvider} with the
* {@link IProvisioningTarget}s that are available for use
* @param request
* the {@link IProvisioningRequest} to fulfill
* @return the {@link IDataSourceCoordinates} generated by fulfilling the
* specified {@link IProvisioningRequest}
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public ProvisioningResult provision(
IProvisioningTargetsProvider targetsProvider,
IProvisioningRequest request) {
// Find the provisioner that matches the request.
IDataSourceProvisioner matchingProvisioner = null;
for (IDataSourceProvisioner provisioner : provisioners) {
if (provisioner.getRequestType().equals(request.getClass()))
matchingProvisioner = provisioner;
}
// Find the available target that matches the provisioner.
IProvisioningTarget target = targetsProvider
.findTarget(matchingProvisioner.getTargetType());
// Run the provisioning request and return the result.
IDataSourceCoordinates provisionedCoords = matchingProvisioner
.provision(target, request);
return new ProvisioningResult(target, request, provisionedCoords);
}
/**
* A user-friendly alternative to
* {@link IDataSourceProvisioner#provision(IProvisioningTarget, IProvisioningRequest)}
* .
*
* @param provisioningResult
* the {@link ProvisioningResult} instance whose provisioned data
* source repository is to be deleted
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void delete(ProvisioningResult provisioningResult) {
// Find the provisioner that matches the request.
IDataSourceProvisioner matchingProvisioner = null;
for (IDataSourceProvisioner provisioner : provisioners) {
if (provisioner.getTargetType().equals(
provisioningResult.getTarget().getClass()))
matchingProvisioner = provisioner;
}
matchingProvisioner.delete(provisioningResult.getTarget(),
provisioningResult.getRequest());
}
/**
* Models the results of a
* {@link DataSourceProvisionersManager#provision(IProvisioningTargetsProvider, IProvisioningRequest)}
* operation.
*/
public static final class ProvisioningResult {
private final IProvisioningTarget target;
private final IProvisioningRequest request;
private final IDataSourceCoordinates coords;
/**
* Constructs a new {@link ProvisioningResult} instance.
*
* @param target
* the value to use for {@link #getTarget()}
* @param request
* the value to use for {@link #getRequest()}
* @param coords
* the value to use for {@link #getCoords()}
*/
public ProvisioningResult(IProvisioningTarget target,
IProvisioningRequest request, IDataSourceCoordinates coords) {
if (target == null)
throw new IllegalArgumentException();
if (request == null)
throw new IllegalArgumentException();
if (coords == null)
throw new IllegalArgumentException();
this.target = target;
this.request = request;
this.coords = coords;
}
/**
* @return the {@link IProvisioningTarget} associated with
* {@link #getCoords()} (generally, represents the server that
* the data source repository was provisioned to)
*/
public IProvisioningTarget getTarget() {
return target;
}
/**
* @return the {@link IProvisioningRequest} that was passed to
* {@link DataSourceProvisionersManager#provision(IProvisioningTargetsProvider, IProvisioningRequest)}
* and led to the creation of this {@link ProvisioningResult}
*/
public IProvisioningRequest getRequest() {
return request;
}
/**
* @return the {@link IDataSourceCoordinates} to the data source
* repository that was provisioned
*/
public IDataSourceCoordinates getCoords() {
return coords;
}
}
}
|
package steamgameselector;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.sqlite.SQLiteDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
/**
*
* @author sfcook
*/
public class SteamData {
private SQLiteDataSource dataSource;
private QueryRunner queryRunner;
private SteamUtils sUtils;
public SteamData(SteamUtils instance)
{
sUtils=instance;
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
dataSource=new SQLiteDataSource();
dataSource.setUrl("jdbc:sqlite:steamdata.db");
queryRunner=new QueryRunner(dataSource);
try {
createTables();
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void createTables() throws SQLException
{
//WARNING:
//DbUtils update() seems to suggest using INSERT, UPDATE, or DELETE only
//examples tend to use tables created through scripts not in code
//seems to work just fine but might break if DbUtils changes
//also this was mostly tested using the cmd/shell utility
//appid is the same as the ones used by valve
queryRunner.update("CREATE TABLE IF NOT EXISTS Game(gameid INTEGER PRIMARY KEY AUTOINCREMENT, appid INTEGER, title TEXT)");
//no idea what valve tag ids are or if they even have one
queryRunner.update("CREATE TABLE IF NOT EXISTS Tag(tagid INTEGER PRIMARY KEY AUTOINCREMENT, tag TEXT)");
queryRunner.update("CREATE TABLE IF NOT EXISTS GameTag(gameid INTEGER , tagid INTEGER , FOREIGN KEY(gameid) REFERENCES Game(gameid), FOREIGN KEY(tagid) REFERENCES Tag(tagid), PRIMARY KEY(gameid, tagid))");
//steamid is the same as the ones used by valve, might break if valve stops using 64-bit signed int
queryRunner.update("CREATE TABLE IF NOT EXISTS Account(accountid INTEGER PRIMARY KEY, steamid TEXT, name TEXT)");
queryRunner.update("CREATE TABLE IF NOT EXISTS AccountGame(accountid INTEGER , gameid INTEGER , FOREIGN KEY(accountid) REFERENCES Account(accountid), FOREIGN KEY(gameid) REFERENCES Game(gameid), PRIMARY KEY(accountid,gameid))");
queryRunner.update("CREATE VIEW IF NOT EXISTS SharedGames AS SELECT g.gameid, g.appid, g.title FROM"
+ "(SELECT COUNT(*) AS num FROM Account) a,"
+ "(SELECT gameid, COUNT(gameid) AS num FROM AccountGame GROUP BY gameid) r,"
+ " game g WHERE a.num=r.num AND r.gameid=g.gameid");
}
public ArrayList<String> getTags()
{
ArrayList<String> tags=new ArrayList<String>();
try {
List<Object[]> objs=queryRunner.query("SELECT tag FROM Tag",new ArrayListHandler());
if(objs.size()>0)
{
for(Object[] item:objs)
{
if(item.length>0)
tags.add((String)item[0]);
}
}
return tags;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return tags;
}
public ArrayList<String> getTags(int gameid)
{
ArrayList<String> tags=new ArrayList<>();
try {
List<Object[]> objs=queryRunner.query("SELECT T.tag FROM Tag T, GameTag G WHERE G.tagid=T.tagid AND G.gameid=?",new ArrayListHandler(),gameid);
if(objs.size()>0)
{
for(Object[] item:objs)
{
if(item.length>0)
tags.add((String)item[0]);
}
}
return tags;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return tags;
}
public int getTagId(String tag)
{
try {
Object[] objs=queryRunner.query("SELECT tagid FROM Tag WHERE tag LIKE ?",new ArrayHandler(),tag);
if(objs.length==0)
return -1;
else
return (Integer)objs[0];
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
public int addTag(String tag)
{
int exist=getTagId(tag);
if(exist!=-1)
return exist;
try {
if(queryRunner.update("INSERT INTO Tag (tag) Values (?)",tag)==1)
return getTagId(tag);
else
return -1;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
public String getTag(int tagid)
{
try {
Object[] objs=queryRunner.query("SELECT tag FROM Tag WHERE tagid=?",new ArrayHandler(),tagid);
if(objs.length==0)
return null;
else
return (String)objs[0];
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public ArrayList<Account> getAccounts()
{
ArrayList<Account> accounts=new ArrayList<Account>();
try {
List<Object[]> objs=queryRunner.query("SELECT steamid FROM Account",new ArrayListHandler());
if(objs.size()>0)
{
for(Object[] item:objs)
{
if(item.length>0)
accounts.add(getAccount((String)item[0]));
}
}
return accounts;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return accounts;
}
public int addAccount(Account account)
{
if(account.name.isEmpty() || account.games.isEmpty() || account.steamid.isEmpty())
return -1;
else
{
try {
Account accountTest=getAccount(account.steamid);
int accountid;
if(accountTest!=null)
accountid=accountTest.accountid;
else
{
Object[] objs=queryRunner.insert("INSERT INTO Account (steamid,name) Values (?,?)",new ArrayHandler(),account.steamid,account.name);
if(objs.length>0)
accountid=(Integer)objs[0];
else
return -1;
}
String query="INSERT INTO AccountGame (accountid,gameid) Values";
for(Game game:account.games)
{
query+=" ("+Integer.toString(accountid)+","+addGame(game)+"),";
}
query=query.substring(0, query.length()-1);
queryRunner.insert(query,new ArrayHandler());
return accountid;
} catch (SQLException ex) {
if(ex.getErrorCode()==org.sqlite.SQLiteErrorCode.SQLITE_CONSTRAINT.code)
return -1;
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
}
public int addAccountGame(int accountid,int gameid)
{
try {
Object[] objs=queryRunner.query("SELECT * FROM AccountGame WHERE accountid=? AND gameid=?",new ArrayHandler(),accountid,gameid);
if(objs.length==0)
objs=queryRunner.insert("INSERT INTO AccountGame (accountid,gameid) Values (?,?)",new ArrayHandler(),accountid,gameid);
if(objs.length>0)
return 0;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
public int addAccount(String url)
{
return addAccount(sUtils.getAccount(url));
}
public Account getAccount(String steamid)
{
Account account=new Account();
try {
Object[] objs=queryRunner.query("SELECT * FROM Account WHERE steamid=?",new ArrayHandler(),steamid);
if(objs.length>0)
{
account.accountid=(Integer)objs[0];
account.steamid=(String)objs[1];
account.name=(String)objs[2];
account.games=getGames(account.accountid);
return account;
}
else
return null;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void removeAccount(int accountid)
{
try {
queryRunner.update("DELETE FROM account WHERE accountid=?", accountid);
//cascade didn't seem to work right
queryRunner.update("DELETE FROM accountgame WHERE accountid=?", accountid);
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Set<Game> getGames(int accountid)
{
Set<Game> games=new HashSet();
try {
List<Object[]> objs=queryRunner.query("SELECT appid FROM AccountGame R, Game G WHERE R.gameid=G.gameid AND R.accountid=?",new ArrayListHandler(),accountid);
if(objs.size()>0)
{
for(Object[] item:objs)
{
if(item.length>0)
games.add(getSteamGame((Integer)item[0]));
}
}
return games;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return games;
}
public int addGame(int appid)
{
Game game=getSteamGame(appid);
if(game!=null)
return game.gameid;
else
{
game=sUtils.getGame(appid);
return addGame(game);
}
}
public int addGame(Game game)
{
try {
Game check=getSteamGame(game.appid);
if(game.appid>0 && check!=null)
return check.gameid;
Object[] objs=queryRunner.insert("INSERT INTO Game (appid,title) Values (?,?)",new ArrayHandler(),game.appid,game.title);
if(objs.length>0)
{
int gameid=(Integer)objs[0];
if(game.tags.isEmpty())
game.tags=sUtils.getGame(game.appid).tags;
String tagQuery="INSERT INTO GameTag (gameid,tagid) Values ";
for(String tag:game.tags)
{
tagQuery+="("+gameid+","+addTag(tag)+"),";
}
tagQuery=tagQuery.substring(0,tagQuery.length()-1);
if(!game.tags.isEmpty())
queryRunner.insert(tagQuery,new ArrayHandler());
return gameid;
}
else
return -1;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
public void addGameTag(int gameid, String tag)
{
int tagid= addTag(tag);
try {
Object[] objs=queryRunner.insert("INSERT INTO GameTag (gameid,tagid) Values (?,?)",new ArrayHandler(),gameid,tagid);
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Game getGame(int gameid)
{
try {
Object[] objs=queryRunner.query("SELECT * FROM Game WHERE gameid=?",new ArrayHandler(),gameid);
return processGame(objs);
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public Game getSteamGame(int appid)
{
if(appid<=0)
return null;
try {
Object[] objs=queryRunner.query("SELECT * FROM Game WHERE appid=?",new ArrayHandler(),appid);
return processGame(objs);
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void reloadSteamGame(int appid)
{
Game game=getSteamGame(appid);
if(game==null)
addGame(appid);
else
{
Game reload=sUtils.getGame(appid);
if(reload.title.isEmpty())
return;
try {
queryRunner.update("UPDATE game SET title=? WHERE appid=?", reload.title,appid);
for(String tag:reload.tags)
{
addGameTag(game.gameid,tag);
}
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public ArrayList<Game> getSharedGames()
{
ArrayList<Game> games=new ArrayList();
try {
List<Object[]> objs=queryRunner.query("SELECT * FROM SharedGames",new ArrayListHandler());
if(objs.size()>0)
{
for(Object[] item:objs)
{
if(item.length>0)
games.add(processGame(item));
}
}
return games;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return games;
}
public ArrayList<Game> getFilteredGames(Set<Integer> andList, Set<Integer> orList, Set<Integer> notList)
{
if((andList==null || andList.isEmpty()) &&
(orList==null || orList.isEmpty()) &&
(notList==null || notList.isEmpty()))
return getSharedGames();
String query="SELECT g.gameid, g.appid, g.title FROM SharedGames g,";
String queryTail=" WHERE ";
if(andList!=null && !andList.isEmpty())
{
query+=" (SELECT DISTINCT gameid FROM gametag WHERE (tagid IN ("+
setToString(andList)+")) GROUP BY gameid HAVING COUNT(gameid)="+andList.size()+") p,";
queryTail+="g.gameid=p.gameid AND";
}
if(orList!=null && !orList.isEmpty())
{
query+=" (SELECT DISTINCT gameid FROM gametag WHERE (tagid IN ("+
setToString(orList)+")) GROUP BY gameid) o,";
queryTail+="g.gameid=o.gameid AND";
}
if(notList!=null && !notList.isEmpty())
{
query+=" (SELECT a.gameid FROM game a LEFT OUTER JOIN (SELECT DISTINCT gameid FROM gametag WHERE tagid IN ("+
setToString(notList)+")) b ON a.gameid=b.gameid WHERE b.gameid IS NULL) n,";
queryTail+="g.gameid=n.gameid AND";
}
queryTail=queryTail.substring(0, queryTail.length()-4);
query=query.substring(0, query.length()-1);
ArrayList<Game> games=new ArrayList();
try {
List<Object[]> objs=queryRunner.query(query+queryTail,
new ArrayListHandler());
if(objs.size()>0)
{
for(Object[] item:objs)
{
if(item.length>0)
games.add(processGame(item));
}
}
return games;
} catch (SQLException ex) {
Logger.getLogger(SteamData.class.getName()).log(Level.SEVERE, null, ex);
}
return games;
}
private String setToString(Set<Integer> set)
{
String list="";
for(Integer item:set)
{
list+=" "+item+",";
}
return list.substring(0,list.length()-1);
}
//TODO:
public ArrayList<Game> getNonSteamGames()
{
ArrayList<Game> games=new ArrayList();
return games;
}
private Game processGame(Object[] objs)
{
Game game=new Game();
if(objs.length>0)
{
game.gameid=(Integer)objs[0];
game.appid=(Integer)objs[1];
game.title=(String)objs[2];
ArrayList<String> tags=getTags(game.gameid);
for(String tag:tags)
{
game.tags.add(tag);
}
return game;
}
else
return null;
}
}
|
package org.eclipse.persistence.testing.tests.jpa.inheritance;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.models.jpa.inheritance.Company;
import org.eclipse.persistence.testing.models.jpa.inheritance.InheritanceTableCreator;
import org.eclipse.persistence.testing.models.jpa.inheritance.SportsCar;
import org.eclipse.persistence.testing.models.jpa.inheritance.Car;
import org.eclipse.persistence.testing.models.jpa.inheritance.Person;
import org.eclipse.persistence.testing.models.jpa.inheritance.Engineer;
import org.eclipse.persistence.testing.models.jpa.inheritance.ComputerPK;
import org.eclipse.persistence.testing.models.jpa.inheritance.Desktop;
import org.eclipse.persistence.testing.models.jpa.inheritance.Laptop;
import org.eclipse.persistence.testing.models.jpa.inheritance.TireInfo;
import org.eclipse.persistence.testing.models.jpa.inheritance.VehicleDirectory;
import junit.framework.Test;
import junit.framework.TestSuite;
import javax.persistence.EntityManager;
public class EntityManagerJUnitTestCase extends JUnitTestCase {
public EntityManagerJUnitTestCase() {
super();
}
public EntityManagerJUnitTestCase(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite(EntityManagerJUnitTestCase.class);
return suite;
}
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
public void testSetup() {
new InheritanceTableCreator().replaceTables(JUnitTestCase.getServerSession());
clearCache();
}
// gf issue 1356 - persisting a polymorphic relationship throws a NPE.
// The order of persist operations is important for this test.
public void testPersistPolymorphicRelationship() {
EntityManager em = createEntityManager();
beginTransaction(em);
Person p = new Person();
p.setName("Evil Knievel");
Car c = new SportsCar();
c.setDescription("Ferrari");
((SportsCar) c).setMaxSpeed(200);
p.setCar(c);
try {
em.persist(c);
em.persist(p);
commitTransaction(em);
} catch (Exception exception ) {
fail("Error persisting polymorphic relationship: " + exception.getMessage());
} finally {
closeEntityManager(em);
}
}
// test if we can associate with a subclass entity
// whose root entity has EmbeddedId in Joined inheritance strategy
// Issue: GF#1153 && GF#1586 (desktop amendment)
public void testAssociationWithEmbeddedIdSubclassEntityInJoinedStrategy() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Engineer engineer = new Engineer();
em.persist(engineer);
ComputerPK laptopPK = new ComputerPK("Dell", 10001);
Laptop laptop = em.find(Laptop.class, laptopPK);
if (laptop == null){
laptop = new Laptop(laptopPK);
em.persist(laptop);
}
ComputerPK desktopPK = new ComputerPK("IBM", 10002);
Desktop desktop = em.find(Desktop.class, desktopPK);
if (desktop == null){
desktop = new Desktop(desktopPK);
em.persist(desktop);
}
// associate many-to-many relationships
engineer.getLaptops().add(laptop);
engineer.getDesktops().add(desktop);
commitTransaction(em);
} catch(RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
public void testUpateTireInfo(){
EntityManager em = createEntityManager();
beginTransaction(em);
TireInfo tireInfo = new TireInfo();
tireInfo.setPressure(35);
em.persist(tireInfo);
commitTransaction(em);
beginTransaction(em);
TireInfo localTire = em.find(TireInfo.class, tireInfo.getId());
assertTrue("TireInfo was not persisted with the proper pressure", localTire.getPressure().equals(35));
localTire.setPressure(40);
commitTransaction(em);
em.clear();
localTire = em.find(TireInfo.class, tireInfo.getId());
assertTrue("TireInfo was not updated", localTire.getPressure().equals(40));
}
// Note: this test will potentially fail in a number of different ways
// see the above bug for details of the non-derminism
// also: This test only tests the above bug when weaving is disabled
// also note: This test is testing for exceptions on the final flush, that
// is why where are no asserts
public void testMapKeyInheritance(){
EntityManager em = createEntityManager();
beginTransaction(em);
VehicleDirectory directory = new VehicleDirectory();
directory.setName("MyVehicles");
em.persist(directory);
Company company = new Company();
company.setName("A Blue Company");
em.persist(company);
em.flush();
Car car = new Car();
car.setDescription("a Blue Car");
car.setOwner(company);
em.persist(car);
directory.getVehicleDirectory().put(car.getOwner(), car);
company.getVehicles().add(car);
try{
em.flush();
} catch(RuntimeException e){
fail("Exception was thrown while flushing a MapKey with inheritance. " + e.getMessage());
}
rollbackTransaction(em);;
}
}
|
package de.mycrobase.ssim.ed.app;
import org.apache.log4j.Logger;
import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppState;
import com.jme3.app.state.AppStateManager;
import de.mycrobase.ssim.ed.SSimApplication;
/**
* Base class for all other {@linkplain AppState}s that provides a reference
* to the {@link SSimApplication} app and, more important, one to the
* {@link AppStateManager} which is kept internally to provide
* {@link #getState(Class)} which is the basic dependency mechanism for all
* AppStates.
*
* Additionally it implements a basic interval timer for the
* {@link #update(float)} loop that performs calls to {@link #intervalUpdate(float)}
* after the specified {@link #intervalTime} passed.
*
* @author cn
*/
public class BasicAppState extends AbstractAppState {
private static final Logger logger = Logger.getLogger(BasicAppState.class);
private AppStateManager stateManager;
private SSimApplication app;
/**
* Time (in seconds) that must pass to execute another {@link #intervalUpdate(float)}
*/
private float intervalTime;
/**
* Time (in seconds) that is passed since the last {@link #intervalUpdate(float)}
*/
private float passedTime;
public BasicAppState() {
this.intervalTime = 60f; // seconds
}
public BasicAppState(float intervalTime) {
this.intervalTime = intervalTime;
}
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
logger.debug("Initialize app state: " + getClass().getSimpleName());
// keep references of state manager and the main app
this.stateManager = stateManager;
this.app = (SSimApplication) app;
passedTime = 0;
}
@Override
public void update(float dt) {
super.update(dt);
if(passedTime >= intervalTime) {
intervalUpdate(passedTime);
passedTime = 0;
}
passedTime += dt;
}
@Override
public void cleanup() {
super.cleanup();
logger.debug("Cleanup app state: " + getClass().getSimpleName());
}
// internal API
/**
* Method invoked from {@link #update(float)} after a certain
* ({@link #intervalTime}) amount of time passed.
* Designed to be overridden.
*
* @param dt time that is passed since last invocation
*/
protected void intervalUpdate(float dt) {
}
protected float getIntervalTime() {
return intervalTime;
}
protected void setIntervalTime(float intervalTime) {
this.intervalTime = intervalTime;
}
protected SSimApplication getApp() {
return app;
}
protected AppStateManager getStateManager() {
return stateManager;
}
protected <T extends AppState> T getState(Class<T> stateClass) {
return stateManager.getState(stateClass);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.tor.tribes.ui.models;
import de.tor.tribes.types.FarmInformation;
import de.tor.tribes.types.StorageStatus;
import de.tor.tribes.util.farm.FarmManager;
import java.util.Date;
import javax.swing.table.AbstractTableModel;
import org.apache.commons.lang.time.DurationFormatUtils;
/**
*
* @author Torridity
*/
public class FarmTableModel extends AbstractTableModel {
private Class[] types = new Class[]{FarmInformation.FARM_STATUS.class, Boolean.class, Date.class, String.class, Integer.class, StorageStatus.class, String.class, FarmInformation.FARM_RESULT.class, Float.class};
private String[] colNames = new String[]{"Status", "Letztes Ergebnis", "Letzter Bericht", "Dorf", "Wall", "Rohstoffe", "Ankunft", "Übertragen", "Erfolgsquote"};
public FarmTableModel() {
}
@Override
public int getRowCount() {
return FarmManager.getSingleton().getElementCount();
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public String getColumnName(int column) {
return colNames[column];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public int getColumnCount() {
return colNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
FarmInformation elem = (FarmInformation) FarmManager.getSingleton().getAllElements().get(rowIndex);
switch (columnIndex) {
case 0:
return elem.getStatus();
case 1:
return elem.isResourcesFoundInLastReport();
case 2:
return new Date(elem.getLastReport());
case 3:
return elem.getVillage().getShortName();
case 4:
return elem.getWallLevel();
case 5:
return elem.getStorageStatus();
case 6:
long t = elem.getRuntimeInformation();
t = (t <= 0) ? 0 : t;
if (t == 0) {
return "Keine Truppen unterwegs";
}
return DurationFormatUtils.formatDuration(t, "HH:mm:ss", true);
case 7:
return elem.getLastResult();
default:
return elem.getCorrectionFactor();
}
}
}
|
package org.xcolab.service.contest.domain.contest;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.SelectQuery;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.xcolab.model.tables.pojos.Contest;
import org.xcolab.model.tables.records.ContestRecord;
import org.xcolab.service.contest.exceptions.NotFoundException;
import org.xcolab.service.utils.PaginationHelper;
import org.xcolab.service.utils.PaginationHelper.SortColumn;
import java.util.List;
import static org.xcolab.model.Tables.CONTEST;
@Repository
public class ContestDaoImpl implements ContestDao {
private final DSLContext dslContext;
@Autowired
public ContestDaoImpl(DSLContext dslContext) {
Assert.notNull(dslContext, "DSLContext bean is required");
this.dslContext = dslContext;
}
@Override
public Contest create(Contest contest) {
this.dslContext.insertInto(CONTEST)
.set(CONTEST.CONTEST_PK, contest.getContestPK())
.set(CONTEST.CONTEST_TYPE_ID, contest.getContestTypeId())
.set(CONTEST.CONTEST_NAME, contest.getContestName())
.set(CONTEST.CONTEST_SHORT_NAME, contest.getContestShortName())
.set(CONTEST.CONTEST_URL_NAME, contest.getContestUrlName())
.set(CONTEST.CONTEST_YEAR, contest.getContestYear())
.set(CONTEST.CONTEST_DESCRIPTION, contest.getContestDescription())
.set(CONTEST.CONTEST_MODEL_DESCRIPTION, contest.getContestModelDescription())
.set(CONTEST.CONTEST_POSITIONS_DESCRIPTION, contest.getContestPositionsDescription())
.set(CONTEST.CREATED, contest.getCreated())
.set(CONTEST.UPDATED, contest.getUpdated())
.set(CONTEST.AUTHOR_ID, contest.getAuthorId())
.set(CONTEST.CONTEST_ACTIVE, contest.getContestActive())
.set(CONTEST.PLAN_TEMPLATE_ID, contest.getPlanTemplateId())
.set(CONTEST.CONTEST_SCHEDULE_ID, contest.getContestScheduleId())
.set(CONTEST.PROPOSAL_CREATION_TEMPLATE_STRING, contest.getProposalCreationTemplateString())
.set(CONTEST.VOTE_TEMPLATE_STRING, contest.getVoteTemplateString())
.set(CONTEST.PROPOSAL_VOTE_TEMPLATE_STRING, contest.getProposalVoteTemplateString())
.set(CONTEST.PROPOSAL_VOTE_CONFIRMATION_TEMPLATE_STRING, contest.getProposalVoteConfirmationTemplateString())
.set(CONTEST.VOTE_QUESTION_TEMPLATE_STRING, contest.getVoteQuestionTemplateString())
.set(CONTEST.FOCUS_AREA_ID, contest.getFocusAreaId())
.set(CONTEST.CONTEST_TIER, contest.getContestTier())
.set(CONTEST.CONTEST_LOGO_ID, contest.getContestLogoId())
.set(CONTEST.FEATURED_, contest.getFeatured_())
.set(CONTEST.PLANS_OPEN_BY_DEFAULT, contest.getPlansOpenByDefault())
.set(CONTEST.SPONSOR_LOGO_ID, contest.getSponsorLogoId())
.set(CONTEST.SPONSOR_TEXT, contest.getSponsorText())
.set(CONTEST.SPONSOR_LINK, contest.getSponsorLink())
.set(CONTEST.FLAG, contest.getFlag())
.set(CONTEST.FLAG_TEXT, contest.getFlagText())
.set(CONTEST.FLAG_TOOLTIP, contest.getFlagTooltip())
.set(CONTEST.GROUP_ID, contest.getGroupId())
.set(CONTEST.DISCUSSION_GROUP_ID, contest.getDiscussionGroupId())
.set(CONTEST.WEIGHT, contest.getWeight())
.set(CONTEST.RESOURCES_URL, contest.getResourcesUrl())
.set(CONTEST.CONTEST_PRIVATE, contest.getContestPrivate())
.set(CONTEST.USE_PERMISSIONS, contest.getUsePermissions())
.set(CONTEST.CONTEST_CREATION_STATUS, contest.getContestCreationStatus())
.set(CONTEST.DEFAULT_MODEL_ID, contest.getDefaultModelId())
.set(CONTEST.OTHER_MODELS, contest.getOtherModels())
.set(CONTEST.DEFAULT_MODEL_SETTINGS, contest.getDefaultModelSettings())
.set(CONTEST.POINTS, contest.getPoints())
.set(CONTEST.DEFAULT_PARENT_POINT_TYPE, contest.getDefaultParentPointType())
.set(CONTEST.POINT_DISTRIBUTION_STRATEGY, contest.getPointDistributionStrategy())
.set(CONTEST.EMAIL_TEMPLATE_URL, contest.getEmailTemplateUrl())
.set(CONTEST.SHOW_IN_TILE_VIEW, contest.getShow_in_tile_view())
.set(CONTEST.SHOW_IN_LIST_VIEW, contest.getShow_in_list_view())
.set(CONTEST.SHOW_IN_OUTLINE_VIEW, contest.getShow_in_outline_view())
.set(CONTEST.HIDE_RIBBONS, contest.getHideRibbons())
.set(CONTEST.RESOURCE_ARTICLE_ID, contest.getResourceArticleId())
.set(CONTEST.IS_SHARED_CONTEST, contest.getIsSharedContest())
.set(CONTEST.SHARED_ORIGIN, contest.getSharedOrigin())
.execute();
return contest;
}
public boolean update(Contest contest) {
return dslContext.update(CONTEST)
.set(CONTEST.CONTEST_PK, contest.getContestPK())
.set(CONTEST.CONTEST_TYPE_ID, contest.getContestTypeId())
.set(CONTEST.CONTEST_NAME, contest.getContestName())
.set(CONTEST.CONTEST_SHORT_NAME, contest.getContestShortName())
.set(CONTEST.CONTEST_URL_NAME, contest.getContestUrlName())
.set(CONTEST.CONTEST_YEAR, contest.getContestYear())
.set(CONTEST.CONTEST_DESCRIPTION, contest.getContestDescription())
.set(CONTEST.CONTEST_MODEL_DESCRIPTION, contest.getContestModelDescription())
.set(CONTEST.CONTEST_POSITIONS_DESCRIPTION, contest.getContestPositionsDescription())
.set(CONTEST.CREATED, contest.getCreated())
.set(CONTEST.UPDATED, contest.getUpdated())
.set(CONTEST.AUTHOR_ID, contest.getAuthorId())
.set(CONTEST.CONTEST_ACTIVE, contest.getContestActive())
.set(CONTEST.PLAN_TEMPLATE_ID, contest.getPlanTemplateId())
.set(CONTEST.CONTEST_SCHEDULE_ID, contest.getContestScheduleId())
.set(CONTEST.PROPOSAL_CREATION_TEMPLATE_STRING, contest.getProposalCreationTemplateString())
.set(CONTEST.VOTE_TEMPLATE_STRING, contest.getVoteTemplateString())
.set(CONTEST.PROPOSAL_VOTE_TEMPLATE_STRING, contest.getProposalVoteTemplateString())
.set(CONTEST.PROPOSAL_VOTE_CONFIRMATION_TEMPLATE_STRING, contest.getProposalVoteConfirmationTemplateString())
.set(CONTEST.VOTE_QUESTION_TEMPLATE_STRING, contest.getVoteQuestionTemplateString())
.set(CONTEST.FOCUS_AREA_ID, contest.getFocusAreaId())
.set(CONTEST.CONTEST_TIER, contest.getContestTier())
.set(CONTEST.CONTEST_LOGO_ID, contest.getContestLogoId())
.set(CONTEST.FEATURED_, contest.getFeatured_())
.set(CONTEST.PLANS_OPEN_BY_DEFAULT, contest.getPlansOpenByDefault())
.set(CONTEST.SPONSOR_LOGO_ID, contest.getSponsorLogoId())
.set(CONTEST.SPONSOR_TEXT, contest.getSponsorText())
.set(CONTEST.SPONSOR_LINK, contest.getSponsorLink())
.set(CONTEST.FLAG, contest.getFlag())
.set(CONTEST.FLAG_TEXT, contest.getFlagText())
.set(CONTEST.FLAG_TOOLTIP, contest.getFlagTooltip())
.set(CONTEST.GROUP_ID, contest.getGroupId())
.set(CONTEST.DISCUSSION_GROUP_ID, contest.getDiscussionGroupId())
.set(CONTEST.WEIGHT, contest.getWeight())
.set(CONTEST.RESOURCES_URL, contest.getResourcesUrl())
.set(CONTEST.CONTEST_PRIVATE, contest.getContestPrivate())
.set(CONTEST.USE_PERMISSIONS, contest.getUsePermissions())
.set(CONTEST.CONTEST_CREATION_STATUS, contest.getContestCreationStatus())
.set(CONTEST.DEFAULT_MODEL_ID, contest.getDefaultModelId())
.set(CONTEST.OTHER_MODELS, contest.getOtherModels())
.set(CONTEST.DEFAULT_MODEL_SETTINGS, contest.getDefaultModelSettings())
.set(CONTEST.POINTS, contest.getPoints())
.set(CONTEST.DEFAULT_PARENT_POINT_TYPE, contest.getDefaultParentPointType())
.set(CONTEST.POINT_DISTRIBUTION_STRATEGY, contest.getPointDistributionStrategy())
.set(CONTEST.EMAIL_TEMPLATE_URL, contest.getEmailTemplateUrl())
.set(CONTEST.SHOW_IN_TILE_VIEW, contest.getShow_in_tile_view())
.set(CONTEST.SHOW_IN_LIST_VIEW, contest.getShow_in_list_view())
.set(CONTEST.SHOW_IN_OUTLINE_VIEW, contest.getShow_in_outline_view())
.set(CONTEST.HIDE_RIBBONS, contest.getHideRibbons())
.set(CONTEST.RESOURCE_ARTICLE_ID, contest.getResourceArticleId())
.set(CONTEST.IS_SHARED_CONTEST, contest.getIsSharedContest())
.set(CONTEST.SHARED_ORIGIN, contest.getSharedOrigin())
.where(CONTEST.CONTEST_PK.eq(contest.getContestPK()))
.execute() > 0;
}
@Override
public boolean isShared(long contestId) {
final Record1<Boolean> record = dslContext.select(CONTEST.IS_SHARED_CONTEST)
.from(CONTEST)
.where(CONTEST.CONTEST_PK.eq(contestId))
.fetchOne();
return record != null && record.into(Boolean.class);
}
@Override
public Contest get(Long contestId) throws NotFoundException {
final Record record = dslContext.select()
.from(CONTEST)
.where(CONTEST.CONTEST_PK.eq(contestId))
.fetchOne();
if (record == null) {
throw new NotFoundException("Contest with id " + contestId + " was not found");
}
return record.into(Contest.class);
}
@Override
public List<Contest> findByGiven(PaginationHelper paginationHelper, String contestUrlName, Long contestYear, Boolean active, Boolean featured, Long contestTier, List<Long> focusAreaOntologyTerms, Long contestScheduleId, Long planTemplateId, Long contestTypeId, Boolean contestPrivate) {
final SelectQuery<Record> query = dslContext.select()
.from(CONTEST).getQuery();
if(contestPrivate != null){
query.addConditions(CONTEST.CONTEST_PRIVATE.eq(contestPrivate));
}
if (contestTier != null) {
query.addConditions(CONTEST.CONTEST_TIER.eq(contestTier));
}
if (contestScheduleId != null) {
query.addConditions(CONTEST.CONTEST_SCHEDULE_ID.eq(contestScheduleId));
}
if (planTemplateId != null) {
query.addConditions(CONTEST.PLAN_TEMPLATE_ID.eq(planTemplateId));
}
if (focusAreaOntologyTerms != null && !focusAreaOntologyTerms.isEmpty()) {
query.addConditions(CONTEST.FOCUS_AREA_ID.in(focusAreaOntologyTerms));
}
if (contestTypeId != null ) {
query.addConditions(CONTEST.CONTEST_TYPE_ID.eq(contestTypeId));
}
if (contestUrlName != null) {
query.addConditions(CONTEST.CONTEST_URL_NAME.eq(contestUrlName));
}
if (contestYear != null) {
query.addConditions(CONTEST.CONTEST_YEAR.eq(contestYear));
}
if (active != null) {
query.addConditions(CONTEST.CONTEST_ACTIVE.eq(active));
}
if (featured != null) {
query.addConditions(CONTEST.FEATURED_.eq(featured));
}
for (SortColumn sortColumn : paginationHelper.getSortColumns()) {
switch (sortColumn.getColumnName()) {
case "createDate":
query.addOrderBy(sortColumn.isAscending()
? CONTEST.CREATED.asc() : CONTEST.CREATED.desc());
break;
case "weight":
query.addOrderBy(sortColumn.isAscending()
? CONTEST.WEIGHT.asc() : CONTEST.WEIGHT.desc());
break;
default:
}
}
query.addLimit(paginationHelper.getStartRecord(), paginationHelper.getCount());
return query.fetchInto(Contest.class);
}
@Override
public Integer countByGiven(String contestUrlName, Long contestYear, Boolean active, Boolean featured, Long contestTier, List<Long> focusAreaOntologyTerms, Long contestScheduleId, Long planTemplateId, Long contestTypeId, Boolean contestPrivate) {
final SelectQuery<Record1<Integer>> query = dslContext.selectCount()
.from(CONTEST).getQuery();
if(contestPrivate != null){
query.addConditions(CONTEST.CONTEST_PRIVATE.eq(contestPrivate));
}
if (contestTier != null) {
query.addConditions(CONTEST.CONTEST_TIER.eq(contestTier));
}
if (contestScheduleId != null) {
query.addConditions(CONTEST.CONTEST_SCHEDULE_ID.eq(contestScheduleId));
}
if (planTemplateId != null) {
query.addConditions(CONTEST.PLAN_TEMPLATE_ID.eq(planTemplateId));
}
if (focusAreaOntologyTerms != null && focusAreaOntologyTerms.size() > 0) {
query.addConditions(CONTEST.FOCUS_AREA_ID.in(focusAreaOntologyTerms));
}
if (contestTypeId != null ) {
query.addConditions(CONTEST.CONTEST_TYPE_ID.eq(contestTypeId));
}
if (contestUrlName != null) {
query.addConditions(CONTEST.CONTEST_URL_NAME.eq(contestUrlName));
}
if (contestYear != null) {
query.addConditions(CONTEST.CONTEST_YEAR.eq(contestYear));
}
if (active != null) {
query.addConditions(CONTEST.CONTEST_ACTIVE.eq(active));
}
if (featured != null) {
query.addConditions(CONTEST.FEATURED_.eq(featured));
}
query.addOrderBy(CONTEST.CREATED.desc());
return query.fetchOne(0, Integer.class);
}
@Override
public boolean existsWithScheduleId(long contestScheduleId) {
return dslContext.fetchExists(DSL.select()
.from(CONTEST)
.where(CONTEST.CONTEST_SCHEDULE_ID.eq(contestScheduleId)));
}
}
|
package org.mifosplatform.portfolio.loanproduct.serialization;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.accounting.common.AccountingConstants.LOAN_PRODUCT_ACCOUNTING_PARAMS;
import org.mifosplatform.accounting.common.AccountingRuleType;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.mifosplatform.infrastructure.core.exception.InvalidJsonException;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper;
import org.mifosplatform.portfolio.loanproduct.LoanProductConstants;
import org.mifosplatform.portfolio.loanproduct.domain.InterestMethod;
import org.mifosplatform.portfolio.loanproduct.domain.LoanProduct;
import org.mifosplatform.portfolio.loanproduct.domain.LoanProductValueConditionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
@Component
public final class LoanProductDataValidator {
/**
* The parameters supported for this command.
*/
private final Set<String> supportedParameters = new HashSet<String>(Arrays.asList("locale", "dateFormat", "name", "description",
"fundId", "currencyCode", "digitsAfterDecimal", "inMultiplesOf", "principal", "minPrincipal", "maxPrincipal", "repaymentEvery",
"numberOfRepayments", "minNumberOfRepayments", "maxNumberOfRepayments", "repaymentFrequencyType", "interestRatePerPeriod",
"minInterestRatePerPeriod", "maxInterestRatePerPeriod", "interestRateFrequencyType", "amortizationType", "interestType",
"interestCalculationPeriodType", "inArrearsTolerance", "transactionProcessingStrategyId", "graceOnPrincipalPayment",
"graceOnInterestPayment", "graceOnInterestCharged", "charges", "accountingRule", "includeInBorrowerCycle", "startDate",
"closeDate", "externalId", LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(), LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(),
LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(), LoanProductConstants.useBorrowerCycleParameterName,
LoanProductConstants.principalVariationsForBorrowerCycleParameterName,
LoanProductConstants.interestRateVariationsForBorrowerCycleParameterName,
LoanProductConstants.numberOfRepaymentVariationsForBorrowerCycleParameterName, LoanProductConstants.shortName,
LoanProductConstants.multiDisburseLoanParameterName, LoanProductConstants.outstandingLoanBalanceParameterName,
LoanProductConstants.maxTrancheCountParameterName, LoanProductConstants.graceOnArrearsAgeingParameterName));
private final FromJsonHelper fromApiJsonHelper;
@Autowired
public LoanProductDataValidator(final FromJsonHelper fromApiJsonHelper) {
this.fromApiJsonHelper = fromApiJsonHelper;
}
public void validateForCreate(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct");
final JsonElement element = this.fromApiJsonHelper.parse(json);
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
final String shortName = this.fromApiJsonHelper.extractStringNamed(LoanProductConstants.shortName, element);
baseDataValidator.reset().parameter(LoanProductConstants.shortName).value(shortName).notBlank().notExceedingLengthOf(4);
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500);
if (this.fromApiJsonHelper.parameterExists("fundId", element)) {
final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element);
baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero();
}
final Boolean includeInBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element);
baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle).ignoreIfNull()
.validateForBooleanValue();
// terms
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault());
baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6);
final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault());
baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater();
final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element);
baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount();
final String minPrincipalParameterName = "minPrincipal";
BigDecimal minPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element);
baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull().positiveAmount();
}
final String maxPrincipalParameterName = "maxPrincipal";
BigDecimal maxPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element);
baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull().positiveAmount();
}
if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) {
if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) {
baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).notLessThanMin(minPrincipalAmount);
if (minPrincipalAmount.compareTo(maxPrincipalAmount) <= 0) {
baseDataValidator.reset().parameter("principal").value(principal)
.inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
}
} else {
baseDataValidator.reset().parameter("principal").value(principal).notGreaterThanMax(maxPrincipalAmount);
}
} else if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) {
baseDataValidator.reset().parameter("principal").value(principal).notLessThanMin(minPrincipalAmount);
}
final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element);
baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull().integerGreaterThanZero();
final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
Integer minNumberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
minNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments).ignoreIfNull()
.integerGreaterThanZero();
}
final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
Integer maxNumberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
maxNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments).ignoreIfNull()
.integerGreaterThanZero();
}
if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) {
if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
.notLessThanMin(minNumberOfRepayments);
if (minNumberOfRepayments.compareTo(maxNumberOfRepayments) <= 0) {
baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments)
.inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments);
}
} else {
baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments)
.notGreaterThanMax(maxNumberOfRepayments);
}
} else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notLessThanMin(minNumberOfRepayments);
}
final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element);
baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull().integerGreaterThanZero();
final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType", element,
Locale.getDefault());
baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull().inMinMaxRange(0, 3);
final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element);
baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull().zeroOrPositiveAmount();
final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod";
BigDecimal minInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) {
minInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName,
element);
baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName).value(minInterestRatePerPeriod).ignoreIfNull()
.zeroOrPositiveAmount();
}
final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod";
BigDecimal maxInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) {
maxInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName,
element);
baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName).value(maxInterestRatePerPeriod).ignoreIfNull()
.zeroOrPositiveAmount();
}
if (maxInterestRatePerPeriod != null && maxInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) {
if (minInterestRatePerPeriod != null && minInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) {
baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName).value(maxInterestRatePerPeriod)
.notLessThanMin(minInterestRatePerPeriod);
if (minInterestRatePerPeriod.compareTo(maxInterestRatePerPeriod) <= 0) {
baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod)
.inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod);
}
} else {
baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod)
.notGreaterThanMax(maxInterestRatePerPeriod);
}
} else if (minInterestRatePerPeriod != null && minInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) {
baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod)
.notLessThanMin(minInterestRatePerPeriod);
}
final Integer interestRateFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType", element,
Locale.getDefault());
baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType).notNull().inMinMaxRange(0, 3);
// settings
final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault());
baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull().inMinMaxRange(0, 1);
final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault());
baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1);
final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType", element,
Locale.getDefault());
baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType).notNull()
.inMinMaxRange(0, 1);
final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element);
baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull().zeroOrPositiveAmount();
final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed("transactionProcessingStrategyId", element);
baseDataValidator.reset().parameter("transactionProcessingStrategyId").value(transactionProcessingStrategyId).notNull()
.integerGreaterThanZero();
// grace validation
final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount();
final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment).zeroOrPositiveAmount();
final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount();
final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(
LoanProductConstants.graceOnArrearsAgeingParameterName, element);
baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName).value(graceOnArrearsAgeing)
.zeroOrPositiveAmount();
// accounting related data validation
final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault());
baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1, 4);
if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) {
final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(),
element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(fundAccountId).notNull()
.integerGreaterThanZero();
final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId)
.notNull().integerGreaterThanZero();
final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue())
.value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero();
final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId)
.notNull().integerGreaterThanZero();
final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId)
.notNull().integerGreaterThanZero();
final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId)
.notNull().integerGreaterThanZero();
final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId)
.notNull().integerGreaterThanZero();
final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue()).value(overpaymentAccountId)
.notNull().integerGreaterThanZero();
validatePaymentChannelFundSourceMappings(baseDataValidator, element);
validateChargeToIncomeAccountMappings(baseDataValidator, element);
}
if (isAccrualBasedAccounting(accountingRuleType)) {
final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue())
.value(receivableInterestAccountId).notNull().integerGreaterThanZero();
final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId)
.notNull().integerGreaterThanZero();
final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue())
.value(receivablePenaltyAccountId).notNull().integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.useBorrowerCycleParameterName, element)) {
final Boolean useBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.useBorrowerCycleParameterName,
element);
baseDataValidator.reset().parameter(LoanProductConstants.useBorrowerCycleParameterName).value(useBorrowerCycle).ignoreIfNull()
.validateForBooleanValue();
if (useBorrowerCycle) {
validateBorrowerCycleVariations(element, baseDataValidator);
}
}
validateMultiDisburseLoanData(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
private void validateMultiDisburseLoanData(final DataValidatorBuilder baseDataValidator, final JsonElement element) {
Boolean multiDisburseLoan = false;
if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.multiDisburseLoanParameterName, element)) {
multiDisburseLoan = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.multiDisburseLoanParameterName, element);
baseDataValidator.reset().parameter(LoanProductConstants.multiDisburseLoanParameterName).value(multiDisburseLoan)
.ignoreIfNull().validateForBooleanValue();
}
if (multiDisburseLoan) {
if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.outstandingLoanBalanceParameterName, element)) {
final BigDecimal outstandingLoanBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
LoanProductConstants.outstandingLoanBalanceParameterName, element);
baseDataValidator.reset().parameter(LoanProductConstants.outstandingLoanBalanceParameterName).value(outstandingLoanBalance)
.ignoreIfNull().zeroOrPositiveAmount();
}
final Integer maxTrancheCount = this.fromApiJsonHelper.extractIntegerNamed(LoanProductConstants.maxTrancheCountParameterName,
element, Locale.getDefault());
baseDataValidator.reset().parameter(LoanProductConstants.maxTrancheCountParameterName).value(maxTrancheCount).notNull()
.integerGreaterThanZero();
final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault());
baseDataValidator.reset().parameter("interestType").value(interestType).ignoreIfNull()
.integerSameAsNumber(InterestMethod.DECLINING_BALANCE.getValue());
}
}
public void validateForUpdate(final String json, final LoanProduct loanProduct) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct");
final JsonElement element = this.fromApiJsonHelper.parse(json);
if (this.fromApiJsonHelper.parameterExists("name", element)) {
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
}
if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.shortName, element)) {
final String shortName = this.fromApiJsonHelper.extractStringNamed(LoanProductConstants.shortName, element);
baseDataValidator.reset().parameter(LoanProductConstants.shortName).value(shortName).notBlank().notExceedingLengthOf(4);
}
if (this.fromApiJsonHelper.parameterExists("description", element)) {
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500);
}
if (this.fromApiJsonHelper.parameterExists("fundId", element)) {
final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element);
baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists("includeInBorrowerCycle", element)) {
final Boolean includeInBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element);
baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle).ignoreIfNull()
.validateForBooleanValue();
}
if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) {
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
}
if (this.fromApiJsonHelper.parameterExists("digitsAfterDecimal", element)) {
final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element,
Locale.getDefault());
baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6);
}
if (this.fromApiJsonHelper.parameterExists("inMultiplesOf", element)) {
final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault());
baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater();
}
final String minPrincipalParameterName = "minPrincipal";
BigDecimal minPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element);
baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull().positiveAmount();
}
final String maxPrincipalParameterName = "maxPrincipal";
BigDecimal maxPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element);
baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull().positiveAmount();
}
if (this.fromApiJsonHelper.parameterExists("principal", element)) {
final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element);
baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount();
}
if (this.fromApiJsonHelper.parameterExists("inArrearsTolerance", element)) {
final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element);
baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull().zeroOrPositiveAmount();
}
final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod";
BigDecimal minInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) {
minInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName,
element);
baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName).value(minInterestRatePerPeriod).ignoreIfNull()
.zeroOrPositiveAmount();
}
final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod";
BigDecimal maxInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) {
maxInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName,
element);
baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName).value(maxInterestRatePerPeriod).ignoreIfNull()
.zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod",
element);
baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull().zeroOrPositiveAmount();
}
final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
Integer minNumberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
minNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments).ignoreIfNull()
.integerGreaterThanZero();
}
final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
Integer maxNumberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
maxNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments).ignoreIfNull()
.integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists("numberOfRepayments", element)) {
final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element);
baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull().integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists("repaymentEvery", element)) {
final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element);
baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull().integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists("repaymentFrequencyType", element)) {
final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType", element,
Locale.getDefault());
baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull().inMinMaxRange(0, 3);
}
if (this.fromApiJsonHelper.parameterExists("transactionProcessingStrategyId", element)) {
final Long transactionProcessingStrategyId = this.fromApiJsonHelper
.extractLongNamed("transactionProcessingStrategyId", element);
baseDataValidator.reset().parameter("transactionProcessingStrategyId").value(transactionProcessingStrategyId).notNull()
.integerGreaterThanZero();
}
// grace validation
if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) {
final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) {
final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment).zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) {
final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.graceOnArrearsAgeingParameterName, element)) {
final Integer graceOnArrearsAgeing = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(
LoanProductConstants.graceOnArrearsAgeingParameterName, element);
baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName).value(graceOnArrearsAgeing)
.zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) {
final Integer interestRateFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType", element,
Locale.getDefault());
baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType).notNull().inMinMaxRange(0, 3);
}
if (this.fromApiJsonHelper.parameterExists("amortizationType", element)) {
final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault());
baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull().inMinMaxRange(0, 1);
}
if (this.fromApiJsonHelper.parameterExists("interestType", element)) {
final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault());
baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1);
}
if (this.fromApiJsonHelper.parameterExists("interestCalculationPeriodType", element)) {
final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType",
element, Locale.getDefault());
baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType).notNull()
.inMinMaxRange(0, 1);
}
final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault());
baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).ignoreIfNull().inMinMaxRange(1, 4);
final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(fundAccountId).ignoreIfNull()
.integerGreaterThanZero();
final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId)
.ignoreIfNull().integerGreaterThanZero();
final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue())
.value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero();
final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId)
.ignoreIfNull().integerGreaterThanZero();
final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(),
element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId)
.ignoreIfNull().integerGreaterThanZero();
final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId)
.ignoreIfNull().integerGreaterThanZero();
final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId)
.ignoreIfNull().integerGreaterThanZero();
final Long overpaymentAccountId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(),
element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue()).value(overpaymentAccountId)
.ignoreIfNull().integerGreaterThanZero();
final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue())
.value(receivableInterestAccountId).ignoreIfNull().integerGreaterThanZero();
final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId)
.ignoreIfNull().integerGreaterThanZero();
final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element);
baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue())
.value(receivablePenaltyAccountId).ignoreIfNull().integerGreaterThanZero();
validatePaymentChannelFundSourceMappings(baseDataValidator, element);
validateChargeToIncomeAccountMappings(baseDataValidator, element);
validateMinMaxConstraints(element, baseDataValidator, loanProduct);
if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.useBorrowerCycleParameterName, element)) {
final Boolean useBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed(LoanProductConstants.useBorrowerCycleParameterName,
element);
baseDataValidator.reset().parameter(LoanProductConstants.useBorrowerCycleParameterName).value(useBorrowerCycle).ignoreIfNull()
.validateForBooleanValue();
if (useBorrowerCycle) {
validateBorrowerCycleVariations(element, baseDataValidator);
}
}
validateMultiDisburseLoanData(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
/*
* Validation for advanced accounting options
*/
private void validatePaymentChannelFundSourceMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element) {
if (this.fromApiJsonHelper.parameterExists(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) {
final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element);
if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) {
int i = 0;
do {
final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject();
final Long paymentTypeId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue(), jsonObject);
final Long paymentSpecificFundAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), jsonObject);
baseDataValidator
.reset()
.parameter(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]."
+ LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue()).value(paymentTypeId).notNull()
.integerGreaterThanZero();
baseDataValidator
.reset()
.parameter(
LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue() + "[" + i + "]."
+ LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(paymentSpecificFundAccountId)
.notNull().integerGreaterThanZero();
i++;
} while (i < paymentChannelMappingArray.size());
}
}
}
private void validateChargeToIncomeAccountMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element) {
// validate for both fee and penalty charges
validateChargeToIncomeAccountMappings(baseDataValidator, element, true);
validateChargeToIncomeAccountMappings(baseDataValidator, element, true);
}
private void validateChargeToIncomeAccountMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element,
final boolean isPenalty) {
String parameterName;
if (isPenalty) {
parameterName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue();
} else {
parameterName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue();
}
if (this.fromApiJsonHelper.parameterExists(parameterName, element)) {
final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(parameterName, element);
if (chargeToIncomeAccountMappingArray != null && chargeToIncomeAccountMappingArray.size() > 0) {
int i = 0;
do {
final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject();
final Long chargeId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue(),
jsonObject);
final Long incomeAccountId = this.fromApiJsonHelper.extractLongNamed(
LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), jsonObject);
baseDataValidator.reset()
.parameter(parameterName + "[" + i + "]." + LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue())
.value(chargeId).notNull().integerGreaterThanZero();
baseDataValidator.reset()
.parameter(parameterName + "[" + i + "]." + LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue())
.value(incomeAccountId).notNull().integerGreaterThanZero();
i++;
} while (i < chargeToIncomeAccountMappingArray.size());
}
}
}
public void validateMinMaxConstraints(final JsonElement element, final DataValidatorBuilder baseDataValidator,
final LoanProduct loanProduct) {
validatePrincipalMinMaxConstraint(element, loanProduct, baseDataValidator);
validateNumberOfRepaymentsMinMaxConstraint(element, loanProduct, baseDataValidator);
validateNominalInterestRatePerPeriodMinMaxConstraint(element, loanProduct, baseDataValidator);
}
public void validateMinMaxConstraints(final JsonElement element, final DataValidatorBuilder baseDataValidator,
final LoanProduct loanProduct, Integer cycleNumber) {
final Map<String, BigDecimal> minmaxValues = loanProduct.fetchBorrowerCycleVariationsForCycleNumber(cycleNumber);
final String principalParameterName = "principal";
BigDecimal principalAmount = null;
BigDecimal minPrincipalAmount = null;
BigDecimal maxPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) {
principalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element);
minPrincipalAmount = minmaxValues.get(LoanProductConstants.minPrincipal);
maxPrincipalAmount = minmaxValues.get(LoanProductConstants.maxPrincipal);
}
if ((minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)
&& (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)) {
baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
.inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
} else {
if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
baseDataValidator.reset().parameter(principalParameterName).value(principalAmount).notLessThanMin(minPrincipalAmount);
} else if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
baseDataValidator.reset().parameter(principalParameterName).value(principalAmount).notGreaterThanMax(maxPrincipalAmount);
}
}
final String numberOfRepaymentsParameterName = "numberOfRepayments";
Integer maxNumberOfRepayments = null;
Integer minNumberOfRepayments = null;
Integer numberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) {
numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
if (minmaxValues.get(LoanProductConstants.minNumberOfRepayments) != null) {
minNumberOfRepayments = minmaxValues.get(LoanProductConstants.minNumberOfRepayments).intValueExact();
}
if (minmaxValues.get(LoanProductConstants.maxNumberOfRepayments) != null) {
maxNumberOfRepayments = minmaxValues.get(LoanProductConstants.maxNumberOfRepayments).intValueExact();
}
}
if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) {
if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
.inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments);
} else {
baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
.notGreaterThanMax(maxNumberOfRepayments);
}
} else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
.notLessThanMin(minNumberOfRepayments);
}
final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
BigDecimal interestRatePerPeriod = null;
BigDecimal minInterestRatePerPeriod = null;
BigDecimal maxInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) {
interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element);
minInterestRatePerPeriod = minmaxValues.get(LoanProductConstants.minInterestRatePerPeriod);
maxInterestRatePerPeriod = minmaxValues.get(LoanProductConstants.maxInterestRatePerPeriod);
}
if (maxInterestRatePerPeriod != null) {
if (minInterestRatePerPeriod != null) {
baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
.inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod);
} else {
baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
.notGreaterThanMax(maxInterestRatePerPeriod);
}
} else if (minInterestRatePerPeriod != null) {
baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
.notLessThanMin(minInterestRatePerPeriod);
}
}
private void validatePrincipalMinMaxConstraint(final JsonElement element, final LoanProduct loanProduct,
final DataValidatorBuilder baseDataValidator) {
boolean principalUpdated = false;
boolean minPrincipalUpdated = false;
boolean maxPrincipalUpdated = false;
final String principalParameterName = "principal";
BigDecimal principalAmount = null;
if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) {
principalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element);
principalUpdated = true;
} else {
principalAmount = loanProduct.getPrincipalAmount().getAmount();
}
final String minPrincipalParameterName = "minPrincipal";
BigDecimal minPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element);
minPrincipalUpdated = true;
} else {
minPrincipalAmount = loanProduct.getMinPrincipalAmount().getAmount();
}
final String maxPrincipalParameterName = "maxPrincipal";
BigDecimal maxPrincipalAmount = null;
if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element);
maxPrincipalUpdated = true;
} else {
maxPrincipalAmount = loanProduct.getMaxPrincipalAmount().getAmount();
}
if (minPrincipalUpdated) {
baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).notGreaterThanMax(maxPrincipalAmount);
}
if (maxPrincipalUpdated) {
baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).notLessThanMin(minPrincipalAmount);
}
if ((principalUpdated || minPrincipalUpdated || maxPrincipalUpdated)) {
if ((minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)
&& (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)) {
baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
.inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
} else {
if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
baseDataValidator.reset().parameter(principalParameterName).value(principalAmount).notLessThanMin(minPrincipalAmount);
} else if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
.notGreaterThanMax(maxPrincipalAmount);
}
}
}
}
private void validateNumberOfRepaymentsMinMaxConstraint(final JsonElement element, final LoanProduct loanProduct,
final DataValidatorBuilder baseDataValidator) {
boolean numberOfRepaymentsUpdated = false;
boolean minNumberOfRepaymentsUpdated = false;
boolean maxNumberOfRepaymentsUpdated = false;
final String numberOfRepaymentsParameterName = "numberOfRepayments";
Integer numberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) {
numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
numberOfRepaymentsUpdated = true;
} else {
numberOfRepayments = loanProduct.getNumberOfRepayments();
}
final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
Integer minNumberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
minNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
minNumberOfRepaymentsUpdated = true;
} else {
minNumberOfRepayments = loanProduct.getMinNumberOfRepayments();
}
final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
Integer maxNumberOfRepayments = null;
if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
maxNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
maxNumberOfRepaymentsUpdated = true;
} else {
maxNumberOfRepayments = loanProduct.getMaxNumberOfRepayments();
}
if (minNumberOfRepaymentsUpdated) {
baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments).ignoreIfNull()
.notGreaterThanMax(maxNumberOfRepayments);
}
if (maxNumberOfRepaymentsUpdated) {
baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
.notLessThanMin(minNumberOfRepayments);
}
if (numberOfRepaymentsUpdated || minNumberOfRepaymentsUpdated || maxNumberOfRepaymentsUpdated) {
if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) {
if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
.inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments);
} else {
baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
.notGreaterThanMax(maxNumberOfRepayments);
}
} else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
.notLessThanMin(minNumberOfRepayments);
}
}
}
private void validateNominalInterestRatePerPeriodMinMaxConstraint(final JsonElement element, final LoanProduct loanProduct,
final DataValidatorBuilder baseDataValidator) {
boolean iRPUpdated = false;
boolean minIRPUpdated = false;
boolean maxIRPUpdated = false;
final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
BigDecimal interestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) {
interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element);
iRPUpdated = true;
} else {
interestRatePerPeriod = loanProduct.getNominalInterestRatePerPeriod();
}
final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod";
BigDecimal minInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) {
minInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName,
element);
minIRPUpdated = true;
} else {
minInterestRatePerPeriod = loanProduct.getMinNominalInterestRatePerPeriod();
}
final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod";
BigDecimal maxInterestRatePerPeriod = null;
if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) {
maxInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName,
element);
maxIRPUpdated = true;
} else {
maxInterestRatePerPeriod = loanProduct.getMaxNominalInterestRatePerPeriod();
}
if (minIRPUpdated) {
baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName).value(minInterestRatePerPeriod).ignoreIfNull()
.notGreaterThanMax(maxInterestRatePerPeriod);
}
if (maxIRPUpdated) {
baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName).value(maxInterestRatePerPeriod).ignoreIfNull()
.notLessThanMin(minInterestRatePerPeriod);
}
if (iRPUpdated || minIRPUpdated || maxIRPUpdated) {
if (maxInterestRatePerPeriod != null) {
if (minInterestRatePerPeriod != null) {
baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
.inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod);
} else {
baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
.notGreaterThanMax(maxInterestRatePerPeriod);
}
} else if (minInterestRatePerPeriod != null) {
baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
.notLessThanMin(minInterestRatePerPeriod);
}
}
}
private boolean isCashBasedAccounting(final Integer accountingRuleType) {
return AccountingRuleType.CASH_BASED.getValue().equals(accountingRuleType);
}
private boolean isAccrualBasedAccounting(final Integer accountingRuleType) {
return isUpfrontAccrualAccounting(accountingRuleType) || isPeriodicAccounting(accountingRuleType);
}
private boolean isUpfrontAccrualAccounting(final Integer accountingRuleType) {
return AccountingRuleType.ACCRUAL_UPFRONT.getValue().equals(accountingRuleType);
}
private boolean isPeriodicAccounting(final Integer accountingRuleType) {
return AccountingRuleType.ACCRUAL_PERIODIC.getValue().equals(accountingRuleType);
}
private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) {
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); }
}
private void validateBorrowerCycleVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) {
validateBorrowerCyclePrincipalVariations(element, baseDataValidator);
validateBorrowerCycleRepaymentVariations(element, baseDataValidator);
validateBorrowerCycleInterestVariations(element, baseDataValidator);
}
private void validateBorrowerCyclePrincipalVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) {
validateBorrowerCycleVariations(element, baseDataValidator, LoanProductConstants.principalVariationsForBorrowerCycleParameterName,
LoanProductConstants.principalPerCycleParameterName, LoanProductConstants.minPrincipalPerCycleParameterName,
LoanProductConstants.maxPrincipalPerCycleParameterName, LoanProductConstants.principalValueUsageConditionParamName,
LoanProductConstants.principalCycleNumbersParamName);
}
private void validateBorrowerCycleRepaymentVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) {
validateBorrowerCycleVariations(element, baseDataValidator,
LoanProductConstants.numberOfRepaymentVariationsForBorrowerCycleParameterName,
LoanProductConstants.numberOfRepaymentsPerCycleParameterName,
LoanProductConstants.minNumberOfRepaymentsPerCycleParameterName,
LoanProductConstants.maxNumberOfRepaymentsPerCycleParameterName,
LoanProductConstants.repaymentValueUsageConditionParamName, LoanProductConstants.repaymentCycleNumberParamName);
}
private void validateBorrowerCycleInterestVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator) {
validateBorrowerCycleVariations(element, baseDataValidator,
LoanProductConstants.interestRateVariationsForBorrowerCycleParameterName,
LoanProductConstants.interestRatePerPeriodPerCycleParameterName,
LoanProductConstants.minInterestRatePerPeriodPerCycleParameterName,
LoanProductConstants.maxInterestRatePerPeriodPerCycleParameterName,
LoanProductConstants.interestRateValueUsageConditionParamName, LoanProductConstants.interestRateCycleNumberParamName);
}
private void validateBorrowerCycleVariations(final JsonElement element, final DataValidatorBuilder baseDataValidator,
final String variationParameterName, final String defaultParameterName, final String minParameterName,
final String maxParameterName, final String valueUsageConditionParamName, final String cycleNumbersParamName) {
final JsonObject topLevelJsonElement = element.getAsJsonObject();
final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
Integer lastCycleNumber = 0;
LoanProductValueConditionType lastConditionType = LoanProductValueConditionType.EQUAL;
if (this.fromApiJsonHelper.parameterExists(variationParameterName, element)) {
final JsonArray variationArray = this.fromApiJsonHelper.extractJsonArrayNamed(variationParameterName, element);
if (variationArray != null && variationArray.size() > 0) {
int i = 0;
do {
final JsonObject jsonObject = variationArray.get(i).getAsJsonObject();
BigDecimal defaultValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanProductConstants.defaultValueParameterName,
jsonObject, locale);
BigDecimal minValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanProductConstants.minValueParameterName,
jsonObject, locale);
BigDecimal maxValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanProductConstants.maxValueParameterName,
jsonObject, locale);
Integer cycleNumber = this.fromApiJsonHelper.extractIntegerNamed(LoanProductConstants.borrowerCycleNumberParamName,
jsonObject, locale);
Integer valueUsageCondition = this.fromApiJsonHelper.extractIntegerNamed(
LoanProductConstants.valueConditionTypeParamName, jsonObject, locale);
baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).notBlank();
if (minValue != null) {
baseDataValidator.reset().parameter(minParameterName).value(minValue).notGreaterThanMax(maxValue);
}
if (maxValue != null) {
baseDataValidator.reset().parameter(maxParameterName).value(maxValue).notLessThanMin(minValue);
}
if ((minValue != null && minValue.compareTo(BigDecimal.ZERO) == 1)
&& (maxValue != null && maxValue.compareTo(BigDecimal.ZERO) == 1)) {
baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue)
.inMinAndMaxAmountRange(minValue, maxValue);
} else {
if (minValue != null && minValue.compareTo(BigDecimal.ZERO) == 1) {
baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).notLessThanMin(minValue);
} else if (maxValue != null && maxValue.compareTo(BigDecimal.ZERO) == 1) {
baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).notGreaterThanMax(maxValue);
}
}
LoanProductValueConditionType conditionType = LoanProductValueConditionType.INVALID;
if (valueUsageCondition != null) {
conditionType = LoanProductValueConditionType.fromInt(valueUsageCondition);
}
baseDataValidator
.reset()
.parameter(valueUsageConditionParamName)
.value(valueUsageCondition)
.notNull()
.inMinMaxRange(LoanProductValueConditionType.EQUAL.getValue(),
LoanProductValueConditionType.GRETERTHAN.getValue());
if (lastConditionType.equals(LoanProductValueConditionType.EQUAL)
&& conditionType.equals(LoanProductValueConditionType.GRETERTHAN)) {
if (lastCycleNumber == 0) {
baseDataValidator.reset().parameter(cycleNumbersParamName)
.failWithCode(LoanProductConstants.VALUE_CONDITION_START_WITH_ERROR);
lastCycleNumber = 1;
}
baseDataValidator.reset().parameter(cycleNumbersParamName).value(cycleNumber).notNull()
.integerSameAsNumber(lastCycleNumber);
} else if (lastConditionType.equals(LoanProductValueConditionType.EQUAL)) {
baseDataValidator.reset().parameter(cycleNumbersParamName).value(cycleNumber).notNull()
.integerSameAsNumber(lastCycleNumber + 1);
} else if (lastConditionType.equals(LoanProductValueConditionType.GRETERTHAN)) {
baseDataValidator.reset().parameter(cycleNumbersParamName).value(cycleNumber).notNull()
.integerGreaterThanNumber(lastCycleNumber);
}
if (conditionType != null) {
lastConditionType = conditionType;
}
if (cycleNumber != null) {
lastCycleNumber = cycleNumber;
}
i++;
} while (i < variationArray.size());
if (!lastConditionType.equals(LoanProductValueConditionType.GRETERTHAN)) {
baseDataValidator.reset().parameter(cycleNumbersParamName)
.failWithCode(LoanProductConstants.VALUE_CONDITION_END_WITH_ERROR);
}
}
}
}
}
|
package de.uni.trier.infsec.utils;
public class MessageTools {
public static byte[] copyOf(byte[] message) {
if (message==null) return null;
byte[] copy = new byte[message.length];
for (int i = 0; i < message.length; i++) {
copy[i] = message[i];
}
return copy;
}
public static boolean equal(byte[] a, byte[] b) {
if( a.length != b.length ) return false;
for( int i=0; i<a.length; ++i)
if( a[i] != b[i] ) return false;
return true;
}
public static byte[] getZeroMessage(int messageSize) {
byte[] zeroVector = new byte[messageSize];
for (int i = 0; i < zeroVector.length; i++) {
zeroVector[i] = 0x00;
}
return zeroVector;
}
/**
* Concatenates messages in a way that makes it possible to unambiguously
* split the message into the original messages (it adds length of the
* first message at the beginning of the returned message).
*/
public static byte[] concatenate(byte[] m1, byte[] m2) {
// Concatenated Message --> byte[0-3] = Integer, Length of Message 1
byte[] out = new byte[m1.length + m2.length + 4];
// 4 bytes for length
byte[] len = intToByteArray(m1.length);
// copy all bytes to output array
int j = 0;
for( int i=0; i<len.length; ++i ) out[j++] = len[i];
for( int i=0; i<m1.length; ++i ) out[j++] = m1[i];
for( int i=0; i<m2.length; ++i ) out[j++] = m2[i];
return out;
}
/**
* Simply concatenates the messages (without adding any information for
* de-concatenation).
*/
public static byte[] raw_concatenate(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
int j = 0;
for( int i=0; i<a.length; ++i ) result[j++] = a[i];
for( int i=0; i<b.length; ++i ) result[j++] = b[i];
return result;
}
/**
* Projection of the message to its two parts (part 1 = position 0, part 2 = position 1) Structure of the expected data: 1 Byte Identifier [0x01], 4 Byte
* length of m1, m1, m2
*/
private static byte[] project(byte[] message, int position) {
try {
int len = byteArrayToInt(message);
if (len > (message.length - 4)) return new byte[]{}; // Something is wrong with the message!
if (position == 0) {
byte[] m1 = new byte[len];
for (int i = 0; i < len; i ++) m1[i] = message[i + 4];
return m1;
} else if (position == 1) {
byte[] m2 = new byte[message.length - len - 4];
for (int i = 0; i < message.length - len - 4; i ++) m2[i] = message[i + 4 + len];
return m2;
} else return new byte[]{};
} catch (Exception e) {
return new byte[]{};
}
}
public static byte[] first(byte[] in) {
return project(in, 0);
}
public static byte[] second(byte[] in) {
return project(in, 1);
}
public static final int byteArrayToInt(byte [] b) {
return (b[0] << 24)
+ ((b[1] & 0xFF) << 16)
+ ((b[2] & 0xFF) << 8)
+ (b[3] & 0xFF);
}
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
}
|
package edu.stuy.starlorn.util;
import edu.stuy.starlorn.world.Path;
import edu.stuy.starlorn.world.Wave;
import edu.stuy.starlorn.world.Level;
import edu.stuy.starlorn.entities.EnemyShip;
import edu.stuy.starlorn.upgrades.*;
public class Generator {
public static Path generatePath(int numPoints, int firstx, int firsty) {
Path p = new Path();
int screenWidth = Preferences.getValue("screenWidth");
int screenHeight = Preferences.getValue("screenHeight") / 2;
p.addCoords(firstx, firsty);
for (int i = 0; i < numPoints; i++) {
// Pick locations within the size of the screen / 10 nearby the previous value, and make sure it's in the range of the screen
int x = (int) (Math.random() * screenWidth);
int y = (int) (Math.random() * screenHeight);
p.addCoords(x, y);
}
p.addCoords(Math.abs(firstx - screenWidth), (int) (Math.random() *screenHeight)); // Add a point somewhere on the opposite side of spawn
return p;
}
public static Path generatePath(int numPoints) {
int screenWidth = Preferences.getValue("screenWidth");
int screenHeight = Preferences.getValue("screenHeight") / 2;
int firstx = (int) Math.round(Math.random()) * screenWidth; // Spawn us at one edge
int firsty = (int) (Math.random() * screenHeight);
return generatePath(numPoints, firstx, firsty);
}
public static Path generatePath() {
return generatePath(1000);
}
public static Wave generateWave(int difficulty) {
Wave wave = new Wave();
int numEnemies = (int) (difficulty / 2 + (Math.random() * difficulty));
EnemyShip enemyType = generateEnemy(difficulty);
Path path = generatePath();
wave.setPath(path);
wave.setEnemyType(enemyType);
wave.setNumEnemies(numEnemies);
return wave;
}
public static Wave generateWave() {
return generateWave(1);
}
public static Level generateLevel(int numWaves, int difficulty) {
Level level = new Level();
for (int i = 0; i < numWaves; i++) {
level.addWave(generateWave(difficulty));
}
return level;
}
public static Level generateLevel(int number) {
return generateLevel(number + 1, number * 3);
}
public static EnemyShip generateEnemy(int difficulty) {
Path path = generatePath(difficulty + 5);
EnemyShip enemy = new EnemyShip(path);
int shotSpeed = (int) (1 + Math.random() * difficulty) + 5;
int cooldown = (int) (Math.random() * (100 / difficulty) + 30);
int cooldownRate = (int) Math.sqrt(difficulty) + 1;
int maxSpeed = (int) Math.ceil(Math.random() * Math.log(difficulty)) * 5;
enemy.setBaseShotSpeed(shotSpeed);
enemy.setBaseCooldown(cooldown);
enemy.setCooldownRate(cooldownRate);
enemy.setMovementSpeed(maxSpeed);
return enemy;
}
public static EnemyShip generateEnemy() {
return generateEnemy(1);
}
public static GunUpgrade getRandomUpgrade() {
GunUpgrade[] upgrades = new GunUpgrade[8];
upgrades[0] = new ScatterShotUpgrade();
upgrades[1] = new TripleShotUpgrade();
upgrades[2] = new DoubleShotUpgrade();
upgrades[3] = new DualShotUpgrade();
upgrades[4] = new SpeedShotUpgrade();
upgrades[5] = new LawnSprinklerUpgrade();
upgrades[6] = new GuidedMissileUpgrade();
upgrades[7] = new SideShotUpgrade();
return upgrades[(int) (Math.random() * upgrades.length)];
}
}
|
package org.opennms.netmgt.ticketer.centric;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.aspcfs.apps.transfer.DataRecord;
import org.aspcfs.utils.CRMConnection;
import org.aspcfs.utils.XMLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.util.Assert;
import org.w3c.dom.Element;
import org.opennms.api.integration.ticketing.Plugin;
import org.opennms.api.integration.ticketing.Ticket;
import org.opennms.api.integration.ticketing.Ticket.State;
public class CentricTicketerPlugin implements Plugin {
private static final Logger LOG = LoggerFactory.getLogger(CentricTicketerPlugin.class);
/**
* This class extends Centric Class that is responsible for transferring data
* to/from the Centric server via their HTTP-XML API.
*
* @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a>
* @author <a href="mailto:david@opennms.org">David Hustace</a>
*
*/
public static class CentricConnection extends CRMConnection {
/**
* Convenience method added to retrieve error message embedded in the XML
* packet returned by the CentricCRM API.
*
* @return <code>java.lang.String</code> if an error message exists in the server response.
*/
public String getErrorText() throws CentricPluginException {
XMLUtils xml;
try {
String responseXML = getLastResponse();
if (responseXML == null) {
return "Connection failed. See output.log for details";
}
xml = new XMLUtils(responseXML);
Element response = xml.getFirstChild("response");
Element errorText = XMLUtils.getFirstChild(response, "errorText");
return errorText.getTextContent();
} catch (Throwable e) {
throw new CentricPluginException(e);
}
}
/**
* Wrapper class used to nicely handle Centric API exceptions
*
* @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a>
* @author <a href="mailto:david@opennms.org">David Hustace</a>
*
*/
class CentricPluginException extends RuntimeException {
private static final long serialVersionUID = -2279922257910422937L;
public CentricPluginException(Throwable e) {
super(e);
}
}
}
/**
* Implementation of TicketerPlugin API call to retrieve a CentricCRM trouble ticket.
* @return an OpenNMS
*/
public Ticket get(String ticketId) {
CentricConnection crm = createConnection();
ArrayList<String> returnFields = new ArrayList<String>();
returnFields.add("id");
returnFields.add("modified");
returnFields.add("problem");
returnFields.add("comment");
returnFields.add("stateId");
crm.setTransactionMeta(returnFields);
DataRecord query = new DataRecord();
query.setName("ticketList");
query.setAction(DataRecord.SELECT);
query.addField("id", ticketId);
boolean success = crm.load(query);
if (!success) {
throw new DataRetrievalFailureException(crm.getLastResponse());
}
Ticket ticket = new Ticket();
ticket.setId(crm.getResponseValue("id"));
ticket.setModificationTimestamp(crm.getResponseValue("modified"));
ticket.setSummary(crm.getResponseValue("problem"));
ticket.setDetails(crm.getResponseValue("comment"));
ticket.setState(getStateFromId(crm.getResponseValue("stateId")));
return ticket;
}
/**
* Convenience method of determining a "close" state of a ticket.
* @param newState
* @return true if canceled or closed state
*/
private boolean isClosingState(State newState) {
switch(newState) {
case CANCELLED:
case CLOSED:
return true;
case OPEN:
default:
return false;
}
}
/**
* Convenience method for converting a string representation of
* the OpenNMS enumerated ticket states.
*
* @param stateIdString
* @return the converted <code>org.opennms.api.integration.ticketing.Ticket.State</code>
*/
private State getStateFromId(String stateIdString) {
if (stateIdString == null) {
return State.OPEN;
}
int stateId = Integer.parseInt(stateIdString);
switch(stateId) {
case 1:
return State.OPEN;
case 2:
return State.OPEN;
case 3:
return State.OPEN;
case 4:
return State.OPEN;
case 5:
return State.CLOSED;
case 6:
return State.CANCELLED;
case 7:
return State.CANCELLED;
default:
return State.OPEN;
}
}
/**
* Helper method for creating a CentricCRM DataRecord from properties
* defined in the centric.properties file.
*
* @return a populated <code>org.aspcfs.apps.transfer.DataRecord</code>
*/
private DataRecord createDataRecord() {
DataRecord record = new DataRecord();
Properties props = getProperties();
for(Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String)entry.getKey();
String val = (String)entry.getValue();
if (!key.startsWith("connection.")) {
record.addField(key, val);
}
}
return record;
}
/**
* Retrieves the properties defined in the centric.properties file.
*
* @return a <code>java.util.Properties object containing centric plugin defined properties
*/
private Properties getProperties() {
File home = new File(System.getProperty("opennms.home"));
File etc = new File(home, "etc");
File config = new File(etc, "centric.properties");
Properties props = new Properties();
InputStream in = null;
try {
in = new FileInputStream(config);
props.load(in);
} catch (IOException e) {
LOG.error("Unable to load {} ignoring.", e, config);
} finally {
IOUtils.closeQuietly(in);
}
return props;
}
/*
* (non-Javadoc)
* @see org.opennms.api.integration.ticketing.Plugin#saveOrUpdate(org.opennms.api.integration.ticketing.Ticket)
*/
public void saveOrUpdate(Ticket ticket) {
CentricConnection crm = createConnection();
ArrayList<String> returnFields = new ArrayList<String>();
returnFields.add("id");
crm.setTransactionMeta(returnFields);
DataRecord record = createDataRecord();
record.setName("ticket");
if (ticket.getId() == null) {
record.setAction(DataRecord.INSERT);
} else {
record.setAction(DataRecord.UPDATE);
record.addField("id", ticket.getId());
record.addField("modified", ticket.getModificationTimestamp());
}
record.addField("problem", ticket.getSummary());
record.addField("comment", ticket.getDetails());
record.addField("stateId", getStateId(ticket.getState()));
record.addField("closeNow", isClosingState(ticket.getState()));
crm.save(record);
boolean success = crm.commit();
if (!success) {
throw new DataRetrievalFailureException("Failed to commit Centric transaction: "+crm.getErrorText());
}
Assert.isTrue(1 == crm.getRecordCount(), "Unexpected record count from CRM");
String id = crm.getResponseValue("id");
ticket.setId(id);
/*
<map class="org.aspcfs.modules.troubletickets.base.Ticket" id="ticket">
<property alias="guid">id</property>
<property lookup="account">orgId</property>
<property lookup="contact">contactId</property>
<property>problem</property>
<property>entered</property>
<property lookup="user">enteredBy</property>
<property>modified</property>
<property lookup="user">modifiedBy</property>
<property>closed</property>
<property lookup="ticketPriority">priorityCode</property>
<property>levelCode</property>
<property lookup="lookupDepartment">departmentCode</property>
<property lookup="lookupTicketSource">sourceCode</property>
<property lookup="ticketCategory">catCode</property>
<property lookup="ticketCategory">subCat1</property>
<property lookup="ticketCategory">subCat2</property>
<property lookup="ticketCategory">subCat3</property>
<property lookup="user">assignedTo</property>
<property>comment</property>
<property>solution</property>
<property lookup="ticketSeverity">severityCode</property>
<!-- REMOVE: critical -->
<!-- REMOVE: notified -->
<!-- REMOVE: custom_data -->
<property>location</property>
<property>assignedDate</property>
<property>estimatedResolutionDate</property>
<property>resolutionDate</property>
<property>cause</property>
<property>contractId</property>
<property>assetId</property>
<property>productId</property>
<property>customerProductId</property>
<property>expectation</property>
<property>projectTicketCount</property>
<property>estimatedResolutionDateTimeZone</property>
<property>assignedDateTimeZone</property>
<property>resolutionDateTimeZone</property>
<property>statusId</property>
<property>trashedDate</property>
<property>userGroupId</property>
<property>causeId</property>
<property>resolutionId</property>
<property>defectId</property>
<property>escalationLevel</property>
<property>resolvable</property>
<property>resolvedBy</property>
<property>resolvedByDeptCode</property>
<property>stateId</property>
<property>siteId</property>
</map>
*/
}
/*
private String getModifiedTimestamp(String id) {
CentricConnection crm = createConnection();
ArrayList<String> returnFields = new ArrayList<String>();
returnFields.add("id");
returnFields.add("modified");
crm.setTransactionMeta(returnFields);
DataRecord query = new DataRecord();
query.setAction(DataRecord.SELECT);
query.setName("ticketList");
query.addField("id", 91);
crm.load(query);
return crm.getResponseValue("modified");
}
*/
/**
* Convenience method for converting OpenNMS Ticket.State enum
* to an int representation compatible with CentricCRM.
*
* TODO: This needs to be configurable with the ability of the user
* to define.
*/
private int getStateId(State state) {
switch(state) {
case OPEN:
return 2;
case CANCELLED:
return 6;
case CLOSED:
return 5;
default:
return 2;
}
}
/**
* Creates connection to CentricCRM server using CentricCRM HTTP-XML API
* @return a connection to the configured CentricCRM server.
*/
private CentricConnection createConnection() {
// Client ID must already exist in target CRM system and is created
// under Admin -> Configure System -> HTTP-XML API Client Manager
Properties props = getProperties();
// Establish connectivity as a client
CentricConnection crm = new CentricConnection();
crm.setUrl(props.getProperty("connection.url"));
crm.setId(props.getProperty("connection.id"));
crm.setCode(props.getProperty("connection.code"));
crm.setClientId(props.getProperty("connection.clientId"));
// Start a new transaction
crm.setAutoCommit(false);
return crm;
}
}
|
package com.akh.algorithms.palindrome;
import java.util.Scanner;
/**
* @author Akhash
*
*/
public class NumberPalindrome {
*//**
/*
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number : ");
long num = scanner.nextLong();
System.out.println("Input : " +num);
if(isPalindrome(num))
System.out.println("1st Imple : yes");
else
System.out.println("1st Imple : no");
if(isPalindromeMyImpl(num))
System.out.println("2nd Imple : yes");
else
System.out.println("2nd Imple : no");
}
private static boolean isPalindrome(long input){
long rev = 0;
long num = input;
for(int i=0; i<=num; i++){
long r = num%10;
rev = rev*10+r;
num=num/10;
i=0;
}
return (rev == input) ? true : false;
}
private static boolean isPalindromeMyImpl(long input){
String val = String.valueOf(input);
int i = 0;
int j = val.length()-1;
while(i != j && i < j){
if(val.charAt(i) == val.charAt(j)){
i++;
j
}else{
return false;
}
}
return true;
}
}
|
package org.osgi.test.cases.deploymentadmin.mo.tbc.util;
import java.util.Vector;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.test.cases.deploymentadmin.mo.tbc.DeploymentmoTestControl;
/**
* @author Andre Assad
*
*/
public class BundleListenerImpl implements SynchronousBundleListener {
private DeploymentmoTestControl tbc;
private Vector events;
private int currentType;
private Bundle currentBundle;
/**
* @param control
*/
public BundleListenerImpl(DeploymentmoTestControl tbc) {
this.tbc = tbc;
}
public void bundleChanged(BundleEvent event) {
currentType = event.getType();
currentBundle = event.getBundle();
events.add(event);
synchronized (tbc) {
tbc.notifyAll();
}
}
public void begin() {
reset();
tbc.getContext().addBundleListener(this);
}
public void end() {
tbc.getContext().removeBundleListener(this);
}
public void reset() {
currentType = 0;
currentBundle = null;
events = new Vector();
}
/**
* @return Returns the events.
*/
public Vector getEvents() {
return events;
}
/**
* @return Returns the currentBundle.
*/
public Bundle getCurrentBundle() {
return currentBundle;
}
/**
* @return Returns the currentType.
*/
public int getCurrentType() {
return currentType;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.