answer
stringlengths 17
10.2M
|
|---|
package com.github.rosjava.challenge.uorc_publisher;
import orc.Orc;
import orc.SRF02;
import rss_msgs.SonarMsg;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
public class SonarPublisher implements Runnable {
ConnectedNode node;
Orc orc;
SRF02 sonar;
boolean isFront;
int sonarId;
Publisher<SonarMsg> pub;
final int frontAddr = 0x70;
final int backAddr = 0x72;
Object lock;
public static void main(String[] args){
Orc orc = Orc.makeOrc();
SRF02 one = new SRF02(orc);
SRF02 two = new SRF02(orc, 0x72);
while(true){
System.out.println("distance for one:\t" + one.measure());
System.out.println("distance for two:\t" + two.measure());
}
}
public SonarPublisher(ConnectedNode n, Orc o, boolean isFront, Object lock){
this.node = n;
this.orc = o;
this.isFront = isFront;
this.lock = lock;
if (isFront){
this.sonarId = 1;
sonar = new SRF02(orc, frontAddr);
pub = node.newPublisher("rss/sonars", SonarMsg._TYPE);
System.out.println("created front sonar publisher");
} else {
this.sonarId = 0;
sonar = new SRF02(orc, backAddr);
pub = node.newPublisher("rss/sonars", SonarMsg._TYPE);
System.out.println("created back sonar publisher");
}
}
@Override public void run() {
// TODO Auto-generated method stub
SonarMsg msg = pub.newMessage();
while(true){
double s = 0.0;
synchronized(lock) {
s = sonar.measure();
}
if (s!=0){
msg.setRange(s);
}
msg.setIsFront(isFront);
msg.setSonarId(sonarId);
pub.publish(msg);
}
}
}
|
package ca.corefacility.bioinformatics.irida.model.workflow.analysis;
import java.nio.file.Path;
import java.util.Date;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import com.google.common.base.Strings;
import ca.corefacility.bioinformatics.irida.model.IridaResourceSupport;
import ca.corefacility.bioinformatics.irida.model.IridaThing;
import ca.corefacility.bioinformatics.irida.model.VersionedFileFields;
import ca.corefacility.bioinformatics.irida.repositories.filesystem.FilesystemSupplementedRepository;
import ca.corefacility.bioinformatics.irida.repositories.filesystem.FilesystemSupplementedRepositoryImpl.RelativePathTranslatorListener;
/**
* Store file references to files produced by a workflow execution that we
* otherwise don't want to parse metadata from.
*
*
*/
@Entity
@Table(name = "analysis_output_file")
@EntityListeners(RelativePathTranslatorListener.class)
public class AnalysisOutputFile extends IridaResourceSupport implements IridaThing, VersionedFileFields<Long> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private final Long id;
@Column(name = "file_path", unique = true)
@NotNull(message = "{analysis.output.file.file.notnull}")
@com.fasterxml.jackson.annotation.JsonIgnore
@org.codehaus.jackson.annotate.JsonIgnore
private final Path file;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_date", nullable = false)
private final Date createdDate;
@NotNull(message = "{analysis.output.file.execution.manager.file.id}")
@Column(name = "execution_manager_file_id")
private final String executionManagerFileId;
@NotNull
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = false)
@JoinColumn(name = "tool_execution_id")
private final ToolExecution createdByTool;
@Column(name = "label_prefix")
private final String labelPrefix;
/**
* for hibernate
*/
@SuppressWarnings("unused")
private AnalysisOutputFile() {
this.createdDate = new Date();
this.id = null;
this.file = null;
this.executionManagerFileId = null;
this.createdByTool = null;
this.labelPrefix = null;
}
public AnalysisOutputFile(final Path file, final String labelPrefix, final String executionManagerFileId,
final ToolExecution createdByTool) {
this.id = null;
this.createdDate = new Date();
this.file = file;
this.executionManagerFileId = executionManagerFileId;
this.createdByTool = createdByTool;
this.labelPrefix = labelPrefix;
}
@Override
public Date getCreatedDate() {
return this.createdDate;
}
/**
* This intentionally always returns 0. We're abusing
* {@link VersionedFileFields} so that we can get support from
* {@link FilesystemSupplementedRepository}, even though
* {@link AnalysisOutputFile} is immutable and cannot be versioned.
*
* @return *always* {@code 0L} for {@link AnalysisOutputFile}.
*/
@Override
public Long getFileRevisionNumber() {
return 0L;
}
/**
* This intentionally does nothing. We're abusing
* {@link VersionedFileFields} so that we can get support from
* {@link FilesystemSupplementedRepository}, even though
* {@link AnalysisOutputFile} is immutable and cannot be versioned.
*/
@Override
public void incrementFileRevisionNumber() {
}
@Override
public String getLabel() {
return Strings.isNullOrEmpty(labelPrefix) ? file.toFile().getName() : labelPrefix + '-' + file.toFile().getName();
}
@Override
public Long getId() {
return this.id;
}
public Path getFile() {
return file;
}
public String getExecutionManagerFileId() {
return executionManagerFileId;
}
@com.fasterxml.jackson.annotation.JsonIgnore
public final ToolExecution getCreatedByTool() {
return createdByTool;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(file, executionManagerFileId);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof AnalysisOutputFile) {
AnalysisOutputFile a = (AnalysisOutputFile) o;
return Objects.equals(file, a.file) && Objects.equals(executionManagerFileId, a.executionManagerFileId);
}
return false;
}
}
|
package jlibs.nbp;
import java.io.IOException;
import java.util.Arrays;
import static java.lang.Character.*;
/**
* @author Santhosh Kumar T
*/
public abstract class NBParser{
public static final boolean SHOW_STATS = false;
public static int callRuleCount = 0;
public static int chunkCount = 0;
public void printStats(){
System.out.println("callRuleCount = " + callRuleCount);
System.out.println("chunkCount = " + chunkCount);
System.out.println("lineCount = " + (location.getLineNumber()+1));
System.out.println("charCount = " + location.getCharacterOffset());
}
private final Stream stream;
protected final Stream.LookAhead lookAhead;
public final Location location = new Location();
protected final Buffer buffer = new Buffer();
private int startingRule;
public NBParser(int maxLookAhead, int startingRule){
stream = new Stream(maxLookAhead);
lookAhead = stream.lookAhead;
reset(startingRule);
}
public final void reset(int rule){
stream.clear();
location.reset();
buffer.clear();
free = 2;
stack[0] = startingRule = rule;
stack[1] = 0;
}
public final void reset(){
reset(startingRule);
}
private char input[];
private int position;
private int limit;
protected final int EOF = -1;
protected final int EOC = -2;
private int increment;
protected final int codePoint() throws IOException{
int cp = lookAhead.getNext();
if(cp!=EOC)
return cp;
if(position==limit){
assert input!=null;
return EOC;
}
if(input==null){
increment = 1;
return EOF;
}
char ch0 = input[position];
if(ch0>=MIN_HIGH_SURROGATE && ch0<=MAX_HIGH_SURROGATE){
if(position+1==limit)
return EOC;
char ch1 = input[position+1];
if(ch1>=MIN_LOW_SURROGATE && ch1<=MAX_LOW_SURROGATE){
increment = 2;
return ((ch0 - MIN_HIGH_SURROGATE) << 10) + (ch1 - MIN_LOW_SURROGATE) + MIN_SUPPLEMENTARY_CODE_POINT;
}else{
ioError("bad surrogate pair");
throw new Error("Impossible");
}
}else{
increment = 1;
return ch0;
}
}
public boolean coelsceNewLines = false;
protected static final int FROM_LA = -2;
protected final void consume(int cp){
if(stream.length()>0){
if(cp==FROM_LA)
cp = stream.charAt(0);
lookAhead.consumed();
}else
position += increment;
assert cp!=EOF;
if(coelsceNewLines){
if(location.consume(cp) && buffer.isBufferring())
buffer.append(cp=='\r' ? '\n' : cp);
}else{
location.consume(cp);
if(buffer.isBufferring())
buffer.append(cp);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected final void consumeLookAhead(int count){
while(count
int cp = stream.charAt(0);
lookAhead.consumed();
if(coelsceNewLines){
if(location.consume(cp) && buffer.isBufferring())
buffer.append(cp=='\r' ? '\n' : cp);
}else{
location.consume(cp);
if(buffer.isBufferring())
buffer.append(cp);
}
}
}
protected void addToLookAhead(int cp){
if(lookAhead.add(cp))
position += increment;
}
public boolean stop;
public int consume(char chars[], int position, int limit) throws IOException{
if(SHOW_STATS){
chunkCount++;
if(chars!=null)
System.out.println("chunk["+chunkCount+"] = {"+new String(chars, position, limit-position)+'}');
}
try{
stop = false;
input = chars;
this.position = position;
this.limit = limit;
if(free==0){
int cp = codePoint();
if(cp==-1)
return 1;
else
expected(cp, "<EOF>");
}
curState = stack[free-1];
while(callRule()){
if(curState<0){
lookAhead.reset();
do{
free -= 2;
}while(free!=0 && stack[free-1]<0);
if(free==0){
int cp = codePoint();
if(cp==-1)
this.position = 1;
else
expected(cp, "<EOF>");
break;
}else
curState = stack[free-1];
}else
stack[free-1] = curState;
if(stop)
break;
}
if(chars==null && this.position==limit)
onSuccessful();
else
stack[free-1] = curState;
return this.position;
}catch(IOException ex){
throw ex;
}catch(Exception ex){
if(ex.getCause() instanceof IOException)
throw (IOException)ex.getCause();
else
throw new IOException(ex);
}
}
public void eof() throws IOException{
consume(null, 0, 1);
}
protected abstract boolean callRule() throws Exception;
protected void expected(int ch, String... matchers) throws Exception{
String found;
if(stream.length()>0)
found = stream.toString();
else{
if(ch==-1)
found = "<EOF>";
else
found = new String(toChars(ch));
}
StringBuilder buff = new StringBuilder();
for(String matcher: matchers){
if(buff.length()>0)
buff.append(" OR ");
buff.append(matcher);
}
String message = "Found: '"+found+"' Expected: "+buff.toString();
fatalError(message);
throw new IOException(message);
}
protected abstract void fatalError(String message) throws Exception;
protected abstract void onSuccessful() throws Exception;
protected int free = 0;
protected int curState;
protected int stack[] = new int[100];
protected void push(int toRule, int stateAfterRule, int stateInsideRule){
/*
// fails "/Users/santhosh/projects/SAXTest/xmlconf/xmltest/valid/not-sa/001.xml"
if(stateAfterRule==-1)
free -= 2;
else
stack[free-1] = stateAfterRule;
*/
stack[free-1] = stateAfterRule;
free += 2;
if(free>stack.length)
stack = Arrays.copyOf(stack, free*2);
stack[free-2] = toRule;
stack[free-1] = stateInsideRule;
}
protected void ioError(String message) throws IOException{
try{
fatalError(message);
throw new IOException(message);
}catch(IOException ex){
throw ex;
}catch(Exception ex){
throw new IOException(ex);
}
}
public static final int RULE_DYNAMIC_STRING_MATCH = Integer.MIN_VALUE;
public char[] dynamicStringToBeMatched;
protected final boolean matchString(char expected[]) throws Exception{
int length = expected.length;
for(int i=curState; i<length;){
int cp = codePoint();
int expectedCP = Character.codePointAt(expected, i);
if(cp!=expectedCP){
if(cp==EOC){
curState = i;
return false;
}
expected(cp, new String(new int[]{ expectedCP }, 0, 1));
}
consume(cp);
i += cp<MIN_SUPPLEMENTARY_CODE_POINT ? 1 : 2;
}
curState = -1;
return true;
}
protected final boolean matchString(int expected[]) throws Exception{
int length = expected.length;
for(int i=curState; i<length; i++){
int cp = codePoint();
if(cp!=expected[i]){
if(cp==EOC){
curState = i;
return false;
}
expected(cp, new String(expected, i, 1));
}
consume(cp);
}
curState = -1;
return true;
}
protected final int finishAll(int ch, int expected) throws IOException{
while(ch>=0 && ch==expected){
consume(ch);
ch = codePoint();
}
return ch;
}
protected final int finishAll_OtherThan(int ch, int expected) throws IOException{
while(ch>=0 && ch!=expected){
consume(ch);
ch = codePoint();
}
return ch;
}
}
|
package ca.corefacility.bioinformatics.irida.ria.web.projects;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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 com.google.common.collect.ImmutableMap;
import ca.corefacility.bioinformatics.irida.model.joins.Join;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectMetadataTemplateJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.sample.MetadataField;
import ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplate;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import ca.corefacility.bioinformatics.irida.model.sample.SampleMetadata;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import ca.corefacility.bioinformatics.irida.service.sample.MetadataTemplateService;
import ca.corefacility.bioinformatics.irida.service.sample.SampleService;
@Controller
@RequestMapping("/projects/{projectId}/linelist")
public class ProjectLineListController {
private final ProjectService projectService;
private final SampleService sampleService;
private final MetadataTemplateService metadataTemplateService;
private final ProjectControllerUtils projectControllerUtils;
private final MessageSource messageSource;
@Autowired
public ProjectLineListController(ProjectService projectService, SampleService sampleService,
MetadataTemplateService metadataTemplateService, MessageSource messageSource,
ProjectControllerUtils utils) {
this.projectService = projectService;
this.sampleService = sampleService;
this.metadataTemplateService = metadataTemplateService;
this.messageSource = messageSource;
this.projectControllerUtils = utils;
}
/**
* Get a {@link List} of {@link MetadataTemplate}s available for the current {@link Project}
*
* @param locale
* {@link Locale} users current locale
* @param project
* {@link Project} the project to get {@link MetadataTemplate}s for
*
* @return {@link List} of {@link MetadataTemplate}
*/
private List<Map<String, String>> getTemplateNames(Locale locale, Project project) {
List<ProjectMetadataTemplateJoin> metadataTemplatesForProject = metadataTemplateService.getMetadataTemplatesForProject(project);
List<Map<String, String>> templates = new ArrayList<>();
for (ProjectMetadataTemplateJoin projectMetadataTemplateJoin : metadataTemplatesForProject) {
MetadataTemplate template = projectMetadataTemplateJoin.getObject();
templates.add(ImmutableMap.of("label", template.getLabel(), "id", String.valueOf(template.getId())));
}
if (templates.size() == 0) {
templates.add(ImmutableMap
.of("label", messageSource.getMessage("linelist.no-templates-available", new Object[] {}, locale),
"id", ""));
}
return templates;
}
/**
* Get the page to display the project samples linelist.
*
* @param projectId
* {@link Long} identifier for the current {@link Project}
* @param templateId
* {@link Long} id for the current template
* @param model
* {@link Model}
* @param locale
* {@link Locale}
* @param principal
* {@link Principal} currently logged in user.
*
* @return {@link String} path to the current page.
*/
@RequestMapping("")
public String getLineListPage(@PathVariable Long projectId, @RequestParam(required = false) Long templateId,
Model model, Locale locale, Principal principal) {
// Set up the template information
Project project = projectService.read(projectId);
projectControllerUtils.getProjectTemplateDetails(model, principal, project);
model.addAttribute("activeNav", "linelist");
// templateId usually comes into play when a user just uploaded a metadata
// spreadsheet and is being redirected to this page.
if (templateId != null) {
model.addAttribute("currentTemplate", templateId);
}
// Get a list of all available templates for displaying metadata
model.addAttribute("templates", getTemplateNames(locale, project));
// Get the headers (metadata fields)
List<String> headers = getAllProjectMetadataFields(projectId);
model.addAttribute("headers", headers);
// Get all the metadata for each sample in the project
List<Join<Project, Sample>> samplesForProject = sampleService.getSamplesForProject(project);
List<List<Object>> metadataList = new ArrayList<>(samplesForProject.size());
for (Join<Project, Sample> join : samplesForProject) {
Sample sample = join.getObject();
List<Object> fullMetadata = new ArrayList<>();
SampleMetadata sampleMetadata = sampleService.getMetadataForSample(sample);
if (sampleMetadata != null) {
Map<String, Object> metadata = sampleMetadata.getMetadata();
for (String header : headers) {
if (header.equalsIgnoreCase("id")) {
fullMetadata.add(sample.getId());
} else if (header.equalsIgnoreCase("label")) {
fullMetadata.add(sample.getSampleName());
} else {
fullMetadata.add(metadata.getOrDefault(header, ""));
}
}
// Put this here to avoid showing samples that do not have
// any metadata associated with them.
metadataList.add(fullMetadata);
}
}
model.addAttribute("metadataList", metadataList);
return "projects/project_linelist";
}
/**
* Get the page to create new linelist templates
*
* @param projectId
* {@link Long} identifier for the current {@link Project}
* @param model
* {@link Model}
* @param locale
* {@link Locale}
* @param principal
* {@link Principal}
*
* @return {@link String} path to the page.
*/
@RequestMapping("/linelist-templates")
public String getLinelistTemplatePage(@PathVariable Long projectId, Model model, Locale locale,
Principal principal) {
// Set up the template information
Project project = projectService.read(projectId);
projectControllerUtils.getProjectTemplateDetails(model, principal, project);
model.addAttribute("templates", getTemplateNames(locale, project));
return "projects/project_linelist_template";
}
/**
* Get the metadata fields for a specific template
*
* @param templateId
* {@link Long} identifier for a template
*
* @return {@link List} list of {@link MetadataField} for a template.
*/
@RequestMapping("/metadatafields")
@ResponseBody
public List<MetadataField> getMetadaFieldsForTemplate(@RequestParam Long templateId) {
MetadataTemplate template = metadataTemplateService.read(templateId);
return template.getFields();
}
/**
* Save a new line list template.
*
* @param projectId
* {@link Long} id for the current project
* @param templateName
* {@link String} name for the new template
*
* @return The result of saving.
*/
@RequestMapping(value = "/linelist-templates/save-template/{templateName}",
consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> saveLinelistTemplate(@PathVariable Long projectId, @PathVariable String templateName,
@RequestBody List<Map<String, String>> fields) {
Project project = projectService.read(projectId);
List<MetadataField> metadataFields = new ArrayList<>();
for (Map<String, String> field : fields) {
String label = field.get("label");
// Label and identifier are default that are always in the list.
MetadataField metadataField;
if (field.containsKey("identifier")) {
// Identifier would indicate an existing field. Therefore we should use the existing field
// instead of creating a new one.
metadataField = metadataTemplateService.readMetadataField(Long.parseLong(field.get("identifier")));
} else {
metadataField = new MetadataField(label, field.get("type"));
metadataTemplateService.saveMetadataField(metadataField);
}
metadataFields.add(metadataField);
}
MetadataTemplate metadataTemplate = new MetadataTemplate(templateName, metadataFields);
ProjectMetadataTemplateJoin projectMetadataTemplateJoin = metadataTemplateService
.createMetadataTemplateInProject(metadataTemplate, project);
return ImmutableMap.of("templateId", projectMetadataTemplateJoin.getObject().getId());
}
/**
* Get the template the the line list table. This becomes the table headers.
*
* @param projectId
* {@link Long} identifier of the current {@link Project}
*
* @return {@link Set} containing unique metadata fields
*/
private List<String> getAllProjectMetadataFields(Long projectId) {
Project project = projectService.read(projectId);
Set<String> fields = new HashSet<>();
List<Join<Project, Sample>> samplesForProject = sampleService.getSamplesForProject(project);
for (Join<Project, Sample> join : samplesForProject) {
Sample sample = join.getObject();
SampleMetadata sampleMetadata = sampleService.getMetadataForSample(sample);
if (sampleMetadata != null) {
Map<String, Object> metadataFields = sampleMetadata.getMetadata();
fields.addAll(metadataFields.keySet());
}
}
List<String> fieldList = new ArrayList<>(fields);
// These are default fields for the start
fieldList.add(0, "label");
fieldList.add(0, "id");
return fieldList;
}
}
|
package com.appspot.usbhidterminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import com.appspot.usbhidterminal.core.Consts;
import com.appspot.usbhidterminal.core.events.LogMessageEvent;
import com.appspot.usbhidterminal.core.events.USBDataReceiveEvent;
import com.appspot.usbhidterminal.core.events.USBDataSendEvent;
import com.appspot.usbhidterminal.core.services.SocketService;
import com.appspot.usbhidterminal.core.services.USBHIDService;
import com.appspot.usbhidterminal.core.services.WebServerService;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.EventBusException;
public class USBHIDTerminal extends Activity implements View.OnClickListener {
private SharedPreferences sharedPreferences;
private Intent usbService;
private USBServiceResultReceiver usbServiceResultReceiver;
private EditText edtlogText;
private EditText edtxtHidInput;
private Button btnSend;
private Button btnSelectHIDDevice;
private Button btnClear;
private RadioButton rbSendText;
private RadioButton rbSendDataType;
private String settingsDelimiter;
private String receiveDataFormat;
private String delimiter;
protected EventBus eventBus;
class USBServiceResultReceiver extends ResultReceiver {
public USBServiceResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == Consts.ACTION_USB_DEVICE_ATTACHED) {
btnSend.setEnabled(true);
} else if (resultCode == Consts.ACTION_USB_DEVICE_DETACHED) {
btnSend.setEnabled(false);
} else if (resultCode == Consts.ACTION_USB_SHOW_DEVICES_LIST_RESULT) {
showListOfDevices(resultData.getCharSequenceArray(Consts.ACTION_USB_SHOW_DEVICES_LIST));
}
}
}
private SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ("enable_socket_server".equals(key) || "socket_server_port".equals(key)) {
socketServiceIsStart(false);
socketServiceIsStart(sharedPreferences.getBoolean("enable_socket_server", false));
}
}
};
private void prepareServices() {
usbService = new Intent(this, USBHIDService.class);
usbServiceResultReceiver = new USBServiceResultReceiver(null);
usbService.putExtra("receiver", usbServiceResultReceiver);
startService(usbService);
/*
Intent webServerService = new Intent(this, WebServerService.class);
webServerService.setAction("start");
startService(webServerService);*/
socketServiceIsStart(sharedPreferences.getBoolean("enable_socket_server", false));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
eventBus = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).installDefaultEventBus();
} catch (EventBusException e) {
eventBus = EventBus.getDefault();
}
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(listener);
initUI();
}
private void initUI() {
setVersionToTitle();
btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(this);
btnSelectHIDDevice = (Button) findViewById(R.id.btnSelectHIDDevice);
btnSelectHIDDevice.setOnClickListener(this);
btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
edtxtHidInput = (EditText) findViewById(R.id.edtxtHidInput);
edtlogText = (EditText) findViewById(R.id.edtlogText);
rbSendDataType = (RadioButton) findViewById(R.id.rbSendData);
rbSendText = (RadioButton) findViewById(R.id.rbSendText);
rbSendDataType.setOnClickListener(this);
rbSendText.setOnClickListener(this);
mLog("Initialized\nPlease select your USB HID device\n", false);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
edtxtHidInput.setText("test");
// btnSend.setEnabled(true);
}
public void onClick(View v) {
if (v == btnSend) {
eventBus.post(new USBDataSendEvent(edtxtHidInput.getText().toString()));
} else if (v == rbSendText || v == rbSendDataType) {
sendToUSBService(Consts.ACTION_USB_DATA_TYPE, rbSendDataType.isChecked());
} else if (v == btnClear) {
edtlogText.setText("");
} else if (v == btnSelectHIDDevice) {
sendToUSBService(Consts.ACTION_USB_SHOW_DEVICES_LIST);
}
}
void showListOfDevices(CharSequence devicesName[]) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (devicesName.length == 0) {
builder.setTitle(Consts.MESSAGE_CONNECT_YOUR_USB_HID_DEVICE);
} else {
builder.setTitle(Consts.MESSAGE_SELECT_YOUR_USB_HID_DEVICE);
}
builder.setItems(devicesName, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendToUSBService(Consts.ACTION_USB_SELECT_DEVICE, which);
}
});
builder.setCancelable(true);
builder.show();
}
public void onEvent(USBDataReceiveEvent event) {
mLog(event.getData() + " \nReceived " + event.getBytesCount() + " bytes", true);
}
public void onEvent(LogMessageEvent event) {
mLog(event.getData(), true);
}
@Override
protected void onStart() {
super.onStart();
receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT);
prepareServices();
setDelimiter();
eventBus.register(this);
}
@Override
protected void onStop() {
eventBus.unregister(this);
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
setSelectedMenuItemsFromSettings(menu);
return true;
}
private void setSelectedMenuItemsFromSettings(Menu menu) {
receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT);
if (receiveDataFormat.equals(Consts.BINARY)) {
menu.findItem(R.id.menuSettingsReceiveBinary).setChecked(true);
} else if (receiveDataFormat.equals(Consts.INTEGER)) {
menu.findItem(R.id.menuSettingsReceiveInteger).setChecked(true);
} else if (receiveDataFormat.equals(Consts.HEXADECIMAL)) {
menu.findItem(R.id.menuSettingsReceiveHexadecimal).setChecked(true);
} else if (receiveDataFormat.equals(Consts.TEXT)) {
menu.findItem(R.id.menuSettingsReceiveText).setChecked(true);
}
setDelimiter();
if (settingsDelimiter.equals(Consts.DELIMITER_NONE)) {
menu.findItem(R.id.menuSettingsDelimiterNone).setChecked(true);
} else if (settingsDelimiter.equals(Consts.DELIMITER_NEW_LINE)) {
menu.findItem(R.id.menuSettingsDelimiterNewLine).setChecked(true);
} else if (settingsDelimiter.equals(Consts.DELIMITER_SPACE)) {
menu.findItem(R.id.menuSettingsDelimiterSpace).setChecked(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences.Editor editor = sharedPreferences.edit();
item.setChecked(true);
switch (item.getItemId()) {
case R.id.menuSettings:
Intent i = new Intent(this, SettingsActivity.class);
startActivityForResult(i, Consts.RESULT_SETTINGS);
break;
case R.id.menuSettingsReceiveBinary:
editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.BINARY).apply();
break;
case R.id.menuSettingsReceiveInteger:
editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.INTEGER).apply();
break;
case R.id.menuSettingsReceiveHexadecimal:
editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.HEXADECIMAL).apply();
break;
case R.id.menuSettingsReceiveText:
editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT).apply();
break;
case R.id.menuSettingsDelimiterNone:
editor.putString(Consts.DELIMITER, Consts.DELIMITER_NONE).apply();
break;
case R.id.menuSettingsDelimiterNewLine:
editor.putString(Consts.DELIMITER, Consts.DELIMITER_NEW_LINE).apply();
break;
case R.id.menuSettingsDelimiterSpace:
editor.putString(Consts.DELIMITER, Consts.DELIMITER_SPACE).apply();
break;
}
receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT);
setDelimiter();
return true;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String action = intent.getAction();
if (action == null) {
return;
}
switch (action) {
case Consts.WEB_SERVER_CLOSE_ACTION:
stopService(new Intent(this, WebServerService.class));
break;
case Consts.USB_HID_TERMINAL_CLOSE_ACTION:
stopService(new Intent(this, SocketService.class));
stopService(new Intent(this, WebServerService.class));
stopService(new Intent(this, USBHIDService.class));
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(Consts.USB_HID_TERMINAL_NOTIFICATION);
finish();
break;
case Consts.SOCKET_SERVER_CLOSE_ACTION:
stopService(new Intent(this, SocketService.class));
sharedPreferences.edit().putBoolean("enable_socket_server", false).apply();
break;
}
}
private void setDelimiter() {
settingsDelimiter = sharedPreferences.getString(Consts.DELIMITER, Consts.DELIMITER_NEW_LINE);
if (settingsDelimiter.equals(Consts.DELIMITER_NONE)) {
delimiter = "";
} else if (settingsDelimiter.equals(Consts.DELIMITER_NEW_LINE)) {
delimiter = Consts.NEW_LINE;
} else if (settingsDelimiter.equals(Consts.DELIMITER_SPACE)) {
delimiter = Consts.SPACE;
}
usbService.setAction(Consts.RECEIVE_DATA_FORMAT);
usbService.putExtra(Consts.RECEIVE_DATA_FORMAT, receiveDataFormat);
usbService.putExtra(Consts.DELIMITER, delimiter);
startService(usbService);
}
void sendToUSBService(String action) {
usbService.setAction(action);
startService(usbService);
}
void sendToUSBService(String action, boolean data) {
usbService.putExtra(action, data);
sendToUSBService(action);
}
void sendToUSBService(String action, int data) {
usbService.putExtra(action, data);
sendToUSBService(action);
}
private void mLog(String log, boolean newLine) {
if (newLine) {
edtlogText.append(Consts.NEW_LINE);
}
edtlogText.append(log);
if(edtlogText.getLineCount()>200) {
edtlogText.setText("cleared");
}
}
private void socketServiceIsStart(boolean isStart) {
if (isStart) {
Intent socketServerService = new Intent(this, SocketService.class);
socketServerService.setAction("start");
socketServerService.putExtra("SOCKET_PORT", Integer.parseInt(sharedPreferences.getString("socket_server_port", "7899")));
startService(socketServerService);
} else {
stopService(new Intent(this, SocketService.class));
}
}
private void setVersionToTitle() {
try {
this.setTitle(Consts.SPACE + this.getTitle() + Consts.SPACE + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
|
package hudson.plugins.emailext.plugins.recipients;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.User;
import hudson.plugins.emailext.ExtendedEmailPublisherContext;
import hudson.plugins.emailext.ExtendedEmailPublisherDescriptor;
import hudson.plugins.emailext.plugins.RecipientProvider;
import hudson.plugins.emailext.plugins.RecipientProviderDescriptor;
import hudson.scm.ChangeLogSet;
import hudson.tasks.test.TestResult;
import hudson.tasks.test.AbstractTestResultAction;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Set;
import javax.mail.internet.InternetAddress;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* A recipient provider that assigns ownership of a failing test to the set of developers (including any initiator)
* that committed changes that first broke the test.
*/
public class FailingTestSuspectsRecipientProvider extends RecipientProvider {
@DataBoundConstructor
public FailingTestSuspectsRecipientProvider() {
}
@Override
public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env,
final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> bcc) {
final class Debug implements RecipientProviderUtilities.IDebug {
private final ExtendedEmailPublisherDescriptor descriptor
= Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
private final PrintStream logger = context.getListener().getLogger();
public void send(final String format, final Object... args) {
descriptor.debug(logger, format, args);
}
}
final Debug debug = new Debug();
Set<User> users = null;
final Run<?, ?> currentRun = context.getRun();
if (currentRun == null) {
debug.send("currentRun was null");
} else {
final AbstractTestResultAction<?> testResultAction = currentRun.getAction(AbstractTestResultAction.class);
if (testResultAction == null) {
debug.send("testResultAction was null");
} else {
if (testResultAction.getFailCount() <= 0) {
debug.send("getFailCount() returned <= 0");
} else {
users = new HashSet<>();
debug.send("Collecting builds where a test started failing...");
final HashSet<Run<?, ?>> buildsWhereATestStartedFailing = new HashSet<>();
for (final TestResult caseResult : testResultAction.getFailedTests()) {
final Run<?, ?> runWhereTestStartedFailing = caseResult.getFailedSinceRun();
if (runWhereTestStartedFailing != null) {
debug.send(" runWhereTestStartedFailing: %d", runWhereTestStartedFailing.getNumber());
buildsWhereATestStartedFailing.add(runWhereTestStartedFailing);
} else {
context.getListener().error("getFailedSinceRun returned null for %s", caseResult.getFullDisplayName());
}
}
// For each build where a test started failing, walk backward looking for build results worse than
// UNSTABLE. All of those builds will be used to find suspects.
debug.send("Collecting builds with suspects...");
final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>();
for (final Run<?, ?> buildWhereATestStartedFailing : buildsWhereATestStartedFailing) {
debug.send(" buildWhereATestStartedFailing: %d", buildWhereATestStartedFailing.getNumber());
buildsWithSuspects.add(buildWhereATestStartedFailing);
Run<?, ?> previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild();
if (previousBuildToCheck != null) {
debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber());
}
while (previousBuildToCheck != null) {
if (buildsWithSuspects.contains(previousBuildToCheck)) {
// Short-circuit if the build to check has already been checked.
debug.send(" already contained in buildsWithSuspects; stopping search");
break;
}
final Result previousResult = previousBuildToCheck.getResult();
if (previousResult == null) {
debug.send(" previousResult was null");
} else {
debug.send(" previousResult: %s", previousResult.toString());
if (previousResult.isBetterThan(Result.FAILURE)) {
debug.send(" previousResult was better than FAILURE; stopping search");
break;
} else {
debug.send(" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search");
buildsWithSuspects.add(previousBuildToCheck);
previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild();
if (previousBuildToCheck != null) {
debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber());
}
}
}
}
}
debug.send("Collecting suspects...");
users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug));
users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug));
}
}
}
if (users != null) {
RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug);
}
}
@Extension
public static final class DescriptorImpl extends RecipientProviderDescriptor {
@Override
public String getDisplayName() {
return "Suspects Causing Unit Tests to Begin Failing";
}
}
}
|
package com.cowlark.sake.backend.make;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Set;
import com.cowlark.sake.BasicBlock;
import com.cowlark.sake.ast.nodes.ExpressionStatementNode;
import com.cowlark.sake.ast.nodes.MethodCallNode;
import com.cowlark.sake.backend.Backend;
import com.cowlark.sake.instructions.ArrayConstructorInstruction;
import com.cowlark.sake.instructions.BooleanConstantInstruction;
import com.cowlark.sake.instructions.DiscardInstruction;
import com.cowlark.sake.instructions.FunctionCallInstruction;
import com.cowlark.sake.instructions.FunctionExitInstruction;
import com.cowlark.sake.instructions.GetGlobalVariableInstruction;
import com.cowlark.sake.instructions.GetLocalVariableInstruction;
import com.cowlark.sake.instructions.GotoInstruction;
import com.cowlark.sake.instructions.IfInstruction;
import com.cowlark.sake.instructions.Instruction;
import com.cowlark.sake.instructions.IntegerConstantInstruction;
import com.cowlark.sake.instructions.MethodCallInstruction;
import com.cowlark.sake.instructions.SetGlobalVariableInstruction;
import com.cowlark.sake.instructions.SetLocalVariableInInstruction;
import com.cowlark.sake.instructions.SetReturnValueInstruction;
import com.cowlark.sake.instructions.StringConstantInstruction;
import com.cowlark.sake.symbols.Function;
import com.cowlark.sake.symbols.LocalVariable;
import com.cowlark.sake.types.Type;
public class MakeBackend extends Backend
{
private HashMap<LocalVariable, Integer> _variableAllocation =
new HashMap<LocalVariable, Integer>();
public MakeBackend(OutputStream stream)
{
super(stream);
}
@Override
public void prologue()
{
InputStream is = getClass().getResourceAsStream("sakelib.mk");
print(is);
}
@Override
public void epilogue()
{
print("$(call $(sake.globals.<main>))\n");
}
@Override
public void compileFunction(Function f)
{
print("sake.globals.");
print(f.getSymbolName().getText());
print(" := sake.bb.");
print(f.getEntryBB().getName());
print("\n");
super.compileFunction(f);
}
@Override
public void compileBasicBlock(BasicBlock bb)
{
/* Assign numbers to each variable. */
_variableAllocation.clear();
int i = 1;
for (LocalVariable var : bb.getInputVariables())
{
_variableAllocation.put(var, i);
i++;
}
/* Actually emit the code for the bb. */
print("sake.bb.");
print(bb.getName());
print(" = ");
super.compileBasicBlock(bb);
print("\n");
}
private void emit_output_map()
{
for (LocalVariable var : getCurrentBasicBlock().getOutputVariables())
{
print(",");
emit_var(var);
}
}
private void emit_string(String s)
{
int o = 0;
while (o < s.length())
{
int c = s.codePointAt(o);
switch (c)
{
case '~': print("~T"); break;
case ',': print("~C"); break;
case ' ': print("~S"); break;
default:
print(String.valueOf(Character.toChars(c)));
break;
}
o += Character.charCount(c);
}
}
private void emit_int(long i)
{
if (i < 0)
{
print('N');
i = -i;
}
else
print('P');
String s = Long.toString(i);
for (int n = s.length()-1; n >= 0; n
{
print(' ');
print(s.charAt(n));
}
}
private void emit_var(LocalVariable var)
{
int id = _variableAllocation.get(var);
print("$(");
print(id);
print(")");
}
@Override
public void visit(FunctionExitInstruction insn)
{
}
@Override
public void visit(GotoInstruction insn)
{
print("$(call sake.bb.");
print(insn.getTarget().getName());
emit_output_map();
print(")");
}
@Override
public void visit(IfInstruction insn)
{
print("$(call sake.bb.$(if ");
compileFromIterator();
print(",");
print(insn.getPositiveTarget().getName());
print(",");
print(insn.getNegativeTarget().getName());
print(")");
emit_output_map();
print(")");
}
@Override
public void visit(MethodCallInstruction insn)
{
print("$(call sake.method.");
MethodCallNode node = (MethodCallNode) insn.getNode();
print(node.getMethod().getIdentifier());
print(",");
compileFromIterator();
for (int i = 0; i < insn.getNumberOfArguments(); i++)
{
print(",");
compileFromIterator();
}
print(")");
}
@Override
public void visit(FunctionCallInstruction insn)
{
print("$(call ");
compileFromIterator();
for (int i = 0; i < insn.getNumberOfArguments(); i++)
{
print(",");
compileFromIterator();
}
print(")");
}
@Override
public void visit(GetGlobalVariableInstruction insn)
{
print("$(sake.globals.");
print(insn.getVariable().getSymbolName().getText());
print(")");
}
@Override
public void visit(SetGlobalVariableInstruction insn)
{
print("$(eval sake.globals.");
print(insn.getVariable().getSymbolName().getText());
print(" := ");
compileFromIterator();
print(")");
}
@Override
public void visit(GetLocalVariableInstruction insn)
{
LocalVariable var = insn.getVariable();
emit_var(var);
}
@Override
public void visit(SetLocalVariableInInstruction insn)
{
LocalVariable var = insn.getVariable();
Set<LocalVariable> outputs = getCurrentBasicBlock().getOutputVariables();
if (!outputs.contains(var))
{
/* The variable we're setting is never actually exported;
* evaluate it here, discard the result, and then jump to the
* destination bb. */
print("$(call sake.discard,");
compileFromIterator();
print(")");
}
print("$(call sake.bb.");
print(insn.getTarget().getName());
for (LocalVariable v : getCurrentBasicBlock().getOutputVariables())
{
print(",");
if (v == var)
compileFromIterator();
else
emit_var(v);
}
print(")");
}
@Override
public void visit(SetReturnValueInstruction insn)
{
compileFromIterator();
}
@Override
public void visit(ArrayConstructorInstruction insn)
{
int length = insn.getNumberOfOperands();
print("$(call sake.array.new,");
emit_int(length);
for (int i=0; i<length; i++)
{
print(",");
compileFromIterator();
}
print(")");
}
@Override
public void visit(BooleanConstantInstruction insn)
{
if (insn.getValue())
print("$(sake.boolean.true)");
else
print("$(sake.boolean.false)");
}
@Override
public void visit(StringConstantInstruction insn)
{
emit_string(insn.getValue());
}
@Override
public void visit(IntegerConstantInstruction insn)
{
emit_int(insn.getValue());
}
@Override
public void visit(DiscardInstruction insn)
{
ExpressionStatementNode node = (ExpressionStatementNode) insn.getNode();
Type type = node.getExpression().getType();
if (type.isVoidType())
compileFromIterator();
else
{
print("$(call sake.discard,");
compileFromIterator();
print(")");
}
}
@Override
public void visit(Instruction insn)
{
assert(false);
}
}
|
package com.ecyrd.jspwiki.render;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.event.WikiEvent;
import com.ecyrd.jspwiki.event.WikiEventListener;
import com.ecyrd.jspwiki.event.WikiEventUtils;
import com.ecyrd.jspwiki.event.WikiPageEvent;
import com.ecyrd.jspwiki.modules.InternalModule;
import com.ecyrd.jspwiki.parser.JSPWikiMarkupParser;
import com.ecyrd.jspwiki.parser.MarkupParser;
import com.ecyrd.jspwiki.parser.WikiDocument;
import com.ecyrd.jspwiki.providers.CachingProvider;
import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
/**
* This class provides a facade towards the differing rendering routines. You should
* use the routines in this manager instead of the ones in WikiEngine, if you don't
* want the different side effects to occur - such as WikiFilters.
* <p>
* This class also manages a rendering cache, i.e. documents are stored between calls.
* You may control the size of the cache by using the "jspwiki.renderingManager.cacheSize"
* parameter in jspwiki.properties. The property value is the number of items that
* are stored in the cache. By default, the value of this parameter is taken from
* the "jspwiki.cachingProvider.cacheSize" parameter (i.e. the rendering cache is
* the same size as the page cache), but you may control them separately.
* <p>
* You can turn caching completely off by stating a cacheSize of zero.
*
* @author jalkanen
* @since 2.4
*/
public class RenderingManager implements WikiEventListener, InternalModule
{
private static Logger log = Logger.getLogger( RenderingManager.class );
private int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
private WikiEngine m_engine;
public static final String PROP_CACHESIZE = "jspwiki.renderingManager.capacity";
private static final int DEFAULT_CACHESIZE = 1000;
private static final String VERSION_DELIMITER = "::";
private static final String OSCACHE_ALGORITHM = "com.opensymphony.oscache.base.algorithm.LRUCache";
private static final String PROP_RENDERER = "jspwiki.renderingManager.renderer";
public static final String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
/**
* Stores the WikiDocuments that have been cached.
*/
private Cache m_documentCache;
private Constructor m_rendererConstructor;
public static final String WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
public static final String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
/**
* Initializes the RenderingManager.
* Checks for cache size settings, initializes the document cache.
* Looks for alternative WikiRenderers, initializes one, or the default
* XHTMLRenderer, for use.
*
* @param engine A WikiEngine instance.
* @param properties A list of properties to get parameters from.
*/
public void initialize( WikiEngine engine, Properties properties )
throws WikiException
{
m_engine = engine;
int cacheSize = TextUtil.getIntegerProperty( properties, PROP_CACHESIZE, -1 );
if( cacheSize == -1 )
{
cacheSize = TextUtil.getIntegerProperty( properties,
CachingProvider.PROP_CACHECAPACITY,
DEFAULT_CACHESIZE );
}
if( cacheSize > 0 )
{
m_documentCache = new Cache(true,false,false,false,
OSCACHE_ALGORITHM,
cacheSize);
}
else
{
log.info( "RenderingManager caching is disabled." );
}
String renderImplName = properties.getProperty( PROP_RENDERER );
if( renderImplName == null )
{
renderImplName = DEFAULT_RENDERER;
}
Class[] rendererParams = { WikiContext.class, WikiDocument.class };
try
{
Class c = Class.forName( renderImplName );
m_rendererConstructor = c.getConstructor( rendererParams );
}
catch( ClassNotFoundException e )
{
log.error( "Unable to find WikiRenderer implementation " + renderImplName );
}
catch( SecurityException e )
{
log.error( "Unable to access the WikiRenderer(WikiContext,WikiDocument) constructor for " + renderImplName );
}
catch( NoSuchMethodException e )
{
log.error( "Unable to locate the WikiRenderer(WikiContext,WikiDocument) constructor for " + renderImplName );
}
if( m_rendererConstructor == null )
{
throw new WikiException( "Failed to get WikiRenderer '" + renderImplName + "'." );
}
log.info( "Rendering content with " + renderImplName + "." );
WikiEventUtils.addWikiEventListener(m_engine, WikiPageEvent.POST_SAVE_BEGIN, this);
}
/**
* Returns the default Parser for this context.
*
* @param context the wiki context
* @param pagedata the page data
* @return A MarkupParser instance.
*/
public MarkupParser getParser( WikiContext context, String pagedata )
{
MarkupParser parser = new JSPWikiMarkupParser( context, new StringReader(pagedata) );
return parser;
}
/**
* Returns a cached document, if one is found.
*
* @param context the wiki context
* @param pagedata the page data
* @return the rendered wiki document
* @throws IOException
*/
// FIXME: The cache management policy is not very good: deleted/changed pages
// should be detected better.
protected WikiDocument getRenderedDocument( WikiContext context, String pagedata )
throws IOException
{
String pageid = context.getRealPage().getName()+VERSION_DELIMITER+context.getRealPage().getVersion();
boolean wasUpdated = false;
if( m_documentCache != null )
{
try
{
WikiDocument doc = (WikiDocument) m_documentCache.getFromCache( pageid,
m_cacheExpiryPeriod );
wasUpdated = true;
// This check is needed in case the different filters have actually
// changed the page data.
// FIXME: Figure out a faster method
if( pagedata.equals(doc.getPageData()) )
{
if( log.isDebugEnabled() ) log.debug("Using cached HTML for page "+pageid );
return doc;
}
}
catch( NeedsRefreshException e )
{
if( log.isDebugEnabled() ) log.debug("Re-rendering and storing "+pageid );
}
}
// Refresh the data content
try
{
MarkupParser parser = getParser( context, pagedata );
WikiDocument doc = parser.parse();
doc.setPageData( pagedata );
if( m_documentCache != null )
{
m_documentCache.putInCache( pageid, doc );
wasUpdated = true;
}
return doc;
}
catch( IOException ex )
{
log.error("Unable to parse",ex);
}
finally
{
if( m_documentCache != null && !wasUpdated ) m_documentCache.cancelUpdate( pageid );
}
return null;
}
/**
* Simply renders a WikiDocument to a String. This version does not get the document
* from the cache - in fact, it does not cache the document at all. This is
* very useful, if you have something that you want to render outside the caching
* routines. Because the cache is based on full pages, and the cache keys are
* based on names, use this routine if you're rendering anything for yourself.
*
* @param context The WikiContext to render in
* @param doc A proper WikiDocument
* @return Rendered HTML.
* @throws IOException If the WikiDocument is poorly formed.
*/
public String getHTML( WikiContext context, WikiDocument doc )
throws IOException
{
WikiRenderer rend = getRenderer( context, doc );
return rend.getString();
}
/**
* Returns a WikiRenderer instance, initialized with the given
* context and doc. The object is an XHTMLRenderer, unless overridden
* in jspwiki.properties with PROP_RENDERER.
*/
public WikiRenderer getRenderer( WikiContext context, WikiDocument doc )
{
Object[] params = { context, doc };
WikiRenderer rval = null;
try
{
rval = (WikiRenderer)m_rendererConstructor.newInstance( params );
}
catch( Exception e )
{
log.error( "Unable to create WikiRenderer", e );
}
return rval;
}
/**
* Convinience method for rendering, using the default parser and renderer. Note that
* you can't use this method to do any arbitrary rendering, as the pagedata MUST
* be the data from the that the WikiContext refers to - this method caches the HTML
* internally, and will return the cached version. If the pagedata is different
* from what was cached, will re-render and store the pagedata into the internal cache.
*
* @param context the wiki context
* @param pagedata the page data
* @return XHTML data.
*/
public String getHTML( WikiContext context, String pagedata )
{
try
{
WikiDocument doc = getRenderedDocument( context, pagedata );
return getHTML( context, doc );
}
catch( IOException e )
{
log.error("Unable to parse",e);
}
return null;
}
/**
* Flushes the document cache in response to a POST_SAVE_BEGIN event.
*
* @see com.ecyrd.jspwiki.event.WikiEventListener#actionPerformed(com.ecyrd.jspwiki.event.WikiEvent)
*/
public void actionPerformed(WikiEvent event)
{
if( (event instanceof WikiPageEvent) && (event.getType() == WikiPageEvent.POST_SAVE_BEGIN) )
{
if( m_documentCache != null )
{
String pageName = ((WikiPageEvent) event).getPageName();
m_documentCache.flushPattern( pageName );
Collection referringPages = m_engine.getReferenceManager().findReferrers( pageName );
// Flush also those pages that refer to this page (if an nonexistant page
// appears; we need to flush the HTML that refers to the now-existant page
if( referringPages != null )
{
Iterator i = referringPages.iterator();
while (i.hasNext())
{
String page = (String) i.next();
if( log.isDebugEnabled() ) log.debug( "Flushing " + page );
m_documentCache.flushPattern( page );
}
}
}
}
}
}
|
package org.xander.chessboard.figuresPlacement;
import static org.xander.chessboard.figuresPlacement.BoardUtils.isBoardElementEmpty;
public abstract class PerpendicularAndDiagonalFiguresPlacement extends FiguresPlacement implements DiagonalPlacement, PerpendicularPlacement {
void perpendicularPlacement(int position, int dimension, char[] boardElements) {
placeHorizontallyRight(dimension, boardElements, position, attackPlacesOnTheRight(position, dimension));
placeHorizontallyLeft(dimension, boardElements, position, attackPlacesOnTheLeft(position, dimension));
placeVerticallyAbove(dimension, boardElements, position, numberOfLinesAbove(position, dimension));
placeVerticallyBelow(dimension, boardElements, position, numberOfLinesBelow(position, dimension, boardElements));
}
void diagonalPlacement(int position, int dimension, char[] boardElements) {
placeDiagonallyAboveLeft(dimension, boardElements, position, attackPlacesOnTheLeft(position, dimension));
placeDiagonallyAboveRight(dimension, boardElements, position, attackPlacesOnTheRight(position, dimension));
placeDiagonallyBelowLeft(dimension, boardElements, position, attackPlacesOnTheLeft(position, dimension));
placeDiagonallyBelowRight(dimension, boardElements, position, attackPlacesOnTheRight(position, dimension));
}
private int numberOfLinesBelow(int position, int dimension, char[] boardElements) {
return numberOfLinesAbove(boardElements.length - position, dimension);
}
private int numberOfLinesAbove(int position, int dimension) {
return position / dimension;
}
private int attackPlacesOnTheLeft(int position, int dimension) {
return position % dimension;
}
private int attackPlacesOnTheRight(int position, int dimension) {
//mind the \n character and counting from 0
return dimension - position % dimension - 1 - 1;
}
void placeDiagonallyBelowLeft(int dimension, char[] boardElements, int position, int attackPlacesOnTheLeft) {
int positionLeftBelow = 1;
while (attackPlacesOnTheLeft > 0) {
if (isPossibleToPlaceDiagLeftBelow(boardElements.length, position, dimension, positionLeftBelow)) {
if (isBoardElementEmpty(boardElements[elementDiagonallyLeftBelow(dimension, position, positionLeftBelow)])) {
boardElements[elementDiagonallyLeftBelow(dimension, position, positionLeftBelow)] = FIELD_UNDER_ATTACK_CHAR;
}
}
positionLeftBelow++;
attackPlacesOnTheLeft
}
}
void placeDiagonallyBelowRight(int dimension, char[] boardElements, int position, int attackPlacesOnTheRight) {
int positionRightBelow = 1;
while (attackPlacesOnTheRight > 0) {
if (isPossibleToPlaceDiagRightBelow(boardElements.length, position, dimension, positionRightBelow)) {
if (isBoardElementEmpty(boardElements[elementDiagonallyRightBelow(dimension, position, positionRightBelow)])) {
boardElements[elementDiagonallyRightBelow(dimension, position, positionRightBelow)] = FIELD_UNDER_ATTACK_CHAR;
}
}
positionRightBelow++;
attackPlacesOnTheRight
}
}
void placeDiagonallyAboveRight(int dimension, char[] boardElements, int position, int attackPlacesOnTheRight) {
int positionRightAbove = 1;
while (attackPlacesOnTheRight > 0) {
if (isPossibleToPlaceDiagRightAbove(position, dimension, positionRightAbove)) {
if (isBoardElementEmpty(boardElements[elementDiagonallyRightAbove(dimension, position, positionRightAbove)])) {
boardElements[elementDiagonallyRightAbove(dimension, position, positionRightAbove)] = FIELD_UNDER_ATTACK_CHAR;
}
}
positionRightAbove++;
attackPlacesOnTheRight
}
}
void placeDiagonallyAboveLeft(int dimension, char[] boardElements, int position, int attackPlacesOnTheLeft) {
int positionLeftAbove = 1;
while (attackPlacesOnTheLeft > 0) {
if (isPossibleToPlaceDiagLeftAbove(position, dimension, positionLeftAbove)) {
if (isBoardElementEmpty(boardElements[elementDiagonallyLeftAbove(dimension, position, positionLeftAbove)])) {
boardElements[elementDiagonallyLeftAbove(dimension, position, positionLeftAbove)] = FIELD_UNDER_ATTACK_CHAR;
}
}
positionLeftAbove++;
attackPlacesOnTheLeft
}
}
void placeHorizontallyRight(int dimension, char[] boardElements, int position, int rightPosition) {
while (rightPosition > 0) {
if (isPossibleToPlaceRight(position, dimension, rightPosition)) {
if (isBoardElementEmpty(boardElements[position + rightPosition])) {
boardElements[position + rightPosition] = FIELD_UNDER_ATTACK_CHAR;
}
}
rightPosition
}
}
void placeHorizontallyLeft(int dimension, char[] boardElements, int position, int leftPosition) {
while (leftPosition > 0) {
if (isPossibleToPlaceLeft(position, dimension, leftPosition)) {
if (isBoardElementEmpty(boardElements[position - leftPosition])) {
boardElements[position - leftPosition] = FIELD_UNDER_ATTACK_CHAR;
}
}
leftPosition
}
}
void placeVerticallyAbove(int dimension, char[] boardElements, int position, int numberOfLinesAbove) {
while (numberOfLinesAbove > 0) {
if (isPossibleToPlaceOnPreviousLine(elementVerticallyAbove(dimension, position, numberOfLinesAbove))) {
if (isBoardElementEmpty(boardElements[elementVerticallyAbove(dimension, position, numberOfLinesAbove)])) {
boardElements[elementVerticallyAbove(dimension, position, numberOfLinesAbove)] = FIELD_UNDER_ATTACK_CHAR;
}
}
numberOfLinesAbove
}
}
void placeVerticallyBelow(int dimension, char[] boardElements, int position, int numberOfLinesBelow) {
while (numberOfLinesBelow > 0) {
if (isPossibleToPlaceOnNextLine(boardElements, elementVerticallyBelow(dimension, position, numberOfLinesBelow))) {
if (isBoardElementEmpty(boardElements[elementVerticallyBelow(dimension, position, numberOfLinesBelow)])) {
boardElements[elementVerticallyBelow(dimension, position, numberOfLinesBelow)] = FIELD_UNDER_ATTACK_CHAR;
}
}
numberOfLinesBelow
}
}
boolean isPossibleToPlaceOnNextLine(char[] boardElements, int position) {
return position < boardElements.length;
}
boolean isPossibleToPlaceOnPreviousLine(int position) {
return position >= 0;
}
private boolean isPossibleToPlaceRight(int position, int dimension, int rightPosition) {
return position % dimension + rightPosition < dimension;
}
private boolean isPossibleToPlaceLeft(int position, int dimension, int leftPosition) {
return position % dimension - leftPosition >= 0;
}
private boolean isPossibleToPlaceDiagLeftAbove(int position, int dimension, int positionLeftAbove) {
return elementDiagonallyLeftAbove(dimension, position, positionLeftAbove) >= 0
&& (elementDiagonallyLeftAbove(dimension, position, positionLeftAbove)) % dimension >= 0;
}
private boolean isPossibleToPlaceDiagRightAbove(int position, int dimension, int positionRightAbove) {
return elementDiagonallyRightAbove(dimension, position, positionRightAbove) >= 0
&& (elementDiagonallyRightAbove(dimension, position, positionRightAbove)) % dimension < dimension - 1;
}
private boolean isPossibleToPlaceDiagLeftBelow(int boardElementsLength, int position, int dimension, int positionLeftBelow) {
return (elementDiagonallyLeftBelow(dimension, position, positionLeftBelow)) % dimension < dimension
&& elementDiagonallyLeftBelow(dimension, position, positionLeftBelow) < boardElementsLength;
}
private boolean isPossibleToPlaceDiagRightBelow(int boardElementsLength, int position, int dimension, int positionRightBelow) {
return elementDiagonallyRightBelow(dimension, position, positionRightBelow) < boardElementsLength
&& (elementDiagonallyRightBelow(dimension, position, positionRightBelow)) % dimension < dimension;
}
private int elementDiagonallyLeftBelow(int dimension, int position, int positionLeftBelow) {
return elementVerticallyBelow(dimension, position, positionLeftBelow) - positionLeftBelow;
}
private int elementDiagonallyRightBelow(int dimension, int position, int positionRightBelow) {
return position + dimension * positionRightBelow + positionRightBelow;
}
private int elementDiagonallyRightAbove(int dimension, int position, int positionRightAbove) {
return elementVerticallyAbove(dimension, position, positionRightAbove) + positionRightAbove;
}
private int elementDiagonallyLeftAbove(int dimension, int position, int positionLeftAbove) {
return position - dimension * positionLeftAbove - positionLeftAbove;
}
private int elementVerticallyAbove(int dimension, int position, int numberOfLinesAbove) {
return position - dimension * numberOfLinesAbove;
}
private int elementVerticallyBelow(int dimension, int position, int numberOfLinesBelow) {
return position + dimension * numberOfLinesBelow;
}
}
|
package com.github.dvdme.ForecastIOLib;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
public class ForecastIO {
private static final String ForecastIOURL = "https://api.forecast.io/forecast/";
private String ForecastIOApiKey = "";
private String unitsURL;
private String timeURL;
private String excludeURL;
private String langURL;
private boolean extend;
private int connectTimeout = 30000;
private int readTimeout = 30000;
private String Cache_Control;
private String Expires;
private String X_Forecast_API_Calls;
private String X_Response_Time;
private String rawResponse;
private Proxy proxy_to_use;
public static final String UNITS_US = "us";
public static final String UNITS_SI = "si";
public static final String UNITS_CA = "ca";
public static final String UNITS_UK = "uk";
public static final String UNITS_AUTO = "auto";
public static final String LANG_BOSNIAN = "bs";
public static final String LANG_GERMAN = "de";
public static final String LANG_ENGLISH = "en";
public static final String LANG_SPANISH = "es";
public static final String LANG_FRENCH = "fr";
public static final String LANG_ITALIAN = "it";
public static final String LANG_DUTCH = "nl";
public static final String LANG_POLISH = "pl";
public static final String LANG_PORTUGUESE = "pt";
public static final String LANG_TETUM = "tet";
public static final String LANG_PIG_LATIN = "x-pig-latin";
public static final String LANG_RUSSIAN = "ru";
private JsonObject forecast;
private JsonObject currently;
private JsonObject minutely;
private JsonObject hourly;
private JsonObject daily;
private JsonObject flags;
private JsonArray alerts;
public ForecastIO(String API_KEY){
if (API_KEY.length()==32) {
this.ForecastIOApiKey = API_KEY;
this.forecast = new JsonObject();
this.currently = new JsonObject();
this.minutely = new JsonObject();
this.hourly = new JsonObject();
this.daily = new JsonObject();
this.flags = new JsonObject();
this.alerts = new JsonArray();
this.timeURL = null;
this.excludeURL = null;
this.extend = false;
this.unitsURL = UNITS_AUTO;
this.langURL = LANG_ENGLISH;
this.proxy_to_use = null;
}
else {
System.err.println("The API Key doesn't seam to be valid.");
}
}//construtor - end
public ForecastIO(String LATITUDE, String LONGITUDE, String API_KEY){
if (API_KEY.length()==32) {
this.ForecastIOApiKey = API_KEY;
this.forecast = new JsonObject();
this.currently = new JsonObject();
this.minutely = new JsonObject();
this.hourly = new JsonObject();
this.daily = new JsonObject();
this.flags = new JsonObject();
this.alerts = new JsonArray();
this.timeURL = null;
this.excludeURL = null;
this.extend = false;
this.unitsURL = UNITS_AUTO;
this.langURL = LANG_ENGLISH;
this.proxy_to_use = null;
getForecast(LATITUDE, LONGITUDE);
}
else {
System.err.println("The API Key doesn't seam to be valid.");
}
}//construtor - end
public ForecastIO(String LATITUDE, String LONGITUDE, String PROXYNAME, int PROXYPORT, String API_KEY){
if (API_KEY.length()==32) {
this.ForecastIOApiKey = API_KEY;
this.forecast = new JsonObject();
this.currently = new JsonObject();
this.minutely = new JsonObject();
this.hourly = new JsonObject();
this.daily = new JsonObject();
this.flags = new JsonObject();
this.alerts = new JsonArray();
this.timeURL = null;
this.excludeURL = null;
this.extend = false;
this.unitsURL = UNITS_AUTO;
this.langURL = LANG_ENGLISH;
this.proxy_to_use = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYNAME, PROXYPORT));
getForecast(LATITUDE, LONGITUDE);
}
else {
System.err.println("The API Key doesn't seam to be valid.");
}
}//construtor - end
public ForecastIO(String LATITUDE, String LONGITUDE, String UNITS, String LANG, String API_KEY){
if (API_KEY.length()==32) {
this.ForecastIOApiKey = API_KEY;
this.forecast = new JsonObject();
this.currently = new JsonObject();
this.minutely = new JsonObject();
this.hourly = new JsonObject();
this.daily = new JsonObject();
this.flags = new JsonObject();
this.alerts = new JsonArray();
this.timeURL = null;
this.excludeURL = null;
this.extend = false;
this.proxy_to_use = null;
this.setUnits(UNITS);
this.setLang(LANG);
getForecast(LATITUDE, LONGITUDE);
} else {
System.err.println("The API Key doesn't seam to be valid.");
}
}//construtor - end
public ForecastIO(String LATITUDE, String LONGITUDE, String UNITS, String LANG, String PROXYNAME, int PROXYPORT, String API_KEY){
if (API_KEY.length()==32) {
this.ForecastIOApiKey = API_KEY;
this.forecast = new JsonObject();
this.currently = new JsonObject();
this.minutely = new JsonObject();
this.hourly = new JsonObject();
this.daily = new JsonObject();
this.flags = new JsonObject();
this.alerts = new JsonArray();
this.timeURL = null;
this.excludeURL = null;
this.extend = false;
this.proxy_to_use = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYNAME, PROXYPORT));
this.setUnits(UNITS);
this.setLang(LANG);
getForecast(LATITUDE, LONGITUDE);
} else {
System.err.println("The API Key doesn't seam to be valid.");
}
}//construtor - end
/**
* Returns the latitude that is setted for the request.
* @return A Double number with the latitude.
*/
public Double getLatitude(){
return this.forecast.get("latitude").asDouble();
}
/**
* Returns the longitude that is setted for the request.
* @return A Double number with the longitude.
*/
public Double getLongitude(){
return this.forecast.get("longitude").asDouble();
}
/**
* Returns the timezone that is setted.
* @return A String with the timezone.
*/
public String getTimezone(){
return this.forecast.get("timezone").asString();
}
/**
* Returns the time that is setted for the request.
* @return A String with the time
*/
public String getTime() {
return timeURL;
}
public void setTime(String time) {
this.timeURL = time;
}
/**
* Returns the excluded fields that are setted for the request.
* @return A String with the fields excluded
*/
public String getExcludeURL() {
return excludeURL;
}
public void setExcludeURL(String excludeURL) {
this.excludeURL = excludeURL;
}
/**
* Sets the http-proxy to use.
* @param PROXYNAME hostname or ip of the proxy to use (e.g. "127.0.0.1"). If proxyname equals null, no proxy will be used.
* @param PROXYPORT port of the proxy to use (e.g. 8080)
*/
public void setHTTPProxy(String PROXYNAME, int PROXYPORT) {
if (PROXYNAME == null) {
this.proxy_to_use = null;
}
else {
this.proxy_to_use = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYNAME, PROXYPORT));
}
}
/**
* Returns if the hourly report should be extended in the request.
* @return true or false
*/
public boolean isExtend() {
return extend;
}
public void setExtend(boolean extend) {
this.extend = extend;
}
/**
* @return the connection timeout in milliseconds.
*/
public int getConnectTimeout() {
return connectTimeout;
}
/**
* Sets the connection timeout in milliseconds.
* @param connectTimeout timeout in milliseonds.
*/
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
/**
* @return the read timeout in milliseconds.
*/
public int getReadTimeout() {
return readTimeout;
}
/**
* Sets the read timeout in milliseconds.
* @param readTimeout timeout in milliseonds.
*/
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public double offsetValue(){
return this.forecast.get("offset").asDouble();
}
public String offset(){
if(this.forecast.get("offset").asDouble()<0)
return ""+this.forecast.get("offset").asDouble();
else if(this.forecast.get("offset").asDouble()>0)
return ""+"+"+this.forecast.get("offset").asDouble();
else
return "";
}
/**
* Returns the units that are set in the request.
* @return String with the units set
*/
public String getUnits(){
return this.unitsURL;
}
public void setUnits(String units){
this.unitsURL = units;
}
/**
* Returns the language that are set in the request.
* @return String with the language set
*/
public String getLang(){
return this.langURL;
}
public void setLang(String lang){
this.langURL = lang;
}
/**
* Returns the currently data point
* @return JsonObject with the data point
*/
public JsonObject getCurrently(){
return this.currently;
}
/**
* Returns the minutely data block
* @return JsonObject with the data block
*/
public JsonObject getMinutely(){
return this.minutely;
}
/**
* Returns the hourly data block
* @return JsonObject with the data block
*/
public JsonObject getHourly(){
return this.hourly;
}
/**
* Returns the flags data
* @return JsonObject with the data
*/
public JsonObject getFlags(){
return this.flags;
}
/**
* Returns the alerts data
* @return JsonObject with the data
*/
public JsonArray getAlerts(){
return this.alerts;
}
/**
* Returns the daily data block
* @return JsonObject with the data block
*/
public JsonObject getDaily(){
return this.daily;
}
/**
* Checks if there is any currently data available
* @return true or false
*/
public boolean hasCurrently(){
if(this.currently == null)
return false;
else
return true;
}
/**
* Checks if there is any minutely data available
* @return true or false
*/
public boolean hasMinutely(){
if(this.minutely == null)
return false;
else
return true;
}
/**
* Checks if there is any hourly data available
* @return true or false
*/
public boolean hasHourly(){
if(this.hourly == null)
return false;
else
return true;
}
/**
* Checks if there is any daily data available
* @return true or false
*/
public boolean hasDaily(){
if(this.daily == null)
return false;
else
return true;
}
/**
* Checks if there is any flags data available
* @return true or false
*/
public boolean hasFlags(){
if(this.flags == null)
return false;
else
return true;
}
/**
* Checks if there is any flags data available
* @return true or false
*/
public boolean hasAlerts(){
if(this.alerts == null)
return false;
else
return true;
}
private String urlBuilder(String LATITUDE, String LONGITUDE){
StringBuilder url = new StringBuilder("");
url.append(ForecastIOURL);
url.append(ForecastIOApiKey+"/");
url.append(LATITUDE.trim()+","+LONGITUDE.trim());
if(timeURL!=null)
url.append(","+timeURL.trim());
url.append("?units="+unitsURL.trim());
url.append("&lang="+langURL.trim());
if(excludeURL!=null)
url.append("&exclude="+excludeURL.trim());
if(extend)
url.append("&extend=hourly");
return url.toString();
}
/**
* Does another query to the API and updates the data
* This only updates the data in ForecastIO class
* @return True if successful
*/
public boolean update(){
boolean b = getForecast(String.valueOf(getLatitude()), String.valueOf(getLongitude()));
return b;
}
/**
* Gets the forecast reports for the given coordinates with the set options
* @param LATITUDE the geographical latitude
* @param LONGITUDE the geographical longitude
* @return True if successful
*/
public boolean getForecast(String LATITUDE, String LONGITUDE) {
try {
String reply = httpGET( urlBuilder(LATITUDE, LONGITUDE) );
if(reply == null)
return false;
this.forecast = Json.parse(reply).asObject();
//this.forecast = JsonObject.readFrom(reply);
} catch (NullPointerException e) {
System.err.println("Unable to connect to the API: "+e.getMessage());
return false;
}
return getForecast(this.forecast);
}//getForecast - end
/*
* This change was suggested and made by github user brobzilla to add
* the ability to use an external http library. I found this to be a
* nice suggestion and improvement. However, because http libraries
* usually return the raw string response, I find that it would be
* useful to add a getForecast method that receives the response
* String as parameter.
*/
/**
* Parses the forecast reports for the given coordinates with the set options
* Useful to use with an external http library
* @param http_response String
* @return boolean
*/
public boolean getForecast(String http_response) {
this.forecast = Json.parse(http_response).asObject();
//this.forecast = JsonObject.readFrom(http_response);
return getForecast(this.forecast);
}
/**
* Parses the forecast reports for the given coordinates with the setted options
* Useful to use with an external http library
* Hint: The getForecast(String http_response) could be more useful since it receives
* the raw response String instead of the JsonObect.
* @param forecast JsonObject
* @return true if successful
*/
public boolean getForecast(JsonObject forecast) {
this.forecast = forecast;
try {
this.currently = forecast.get("currently").asObject();
} catch (NullPointerException e) {
this.currently = null;
}
try {
this.minutely = forecast.get("minutely").asObject();
} catch (NullPointerException e) {
this.minutely = null;
}
try {
this.hourly = forecast.get("hourly").asObject();
} catch (NullPointerException e) {
this.hourly = null;
}
try {
this.daily = forecast.get("daily").asObject();
} catch (NullPointerException e) {
this.daily = null;
}
try {
this.flags = forecast.get("flags").asObject();
} catch (NullPointerException e) {
this.flags = null;
}
try {
this.alerts = forecast.get("alerts").asArray();
} catch (NullPointerException e) {
this.alerts = null;
}
return true;
}//getForecast - end
public String getUrl(String LATITUDE, String LONGITUDE) {
return urlBuilder(LATITUDE, LONGITUDE);
}
/**
* Returns the Cache-Control response header value
* @return the string with the header value
*/
public String getHeaderCache_Control() {
return Cache_Control;
}
/**
* Returns the Expires response header value
* @return the string with the header value
*/
public String getHeaderExpires() {
return Expires;
}
/**
* Returns the X-Forecast-API-Calls response header value<br>
* This is the number os API calls made today from one given API Key.
* @return the string with the header value
*/
public String getHeaderX_Forecast_API_Calls() {
return X_Forecast_API_Calls;
}
/**
* Returns the X-Response-Time response header value
* @return the string with the header value
*/
public String getHeaderX_Response_Time() {
return X_Response_Time;
}
/**
* Returns the raw JSON response
* @return the string with the JSON response
*/
public String getRawResponse() {
return rawResponse;
}
private String httpGET(String requestURL) {
//Variables
URL request = null;
HttpURLConnection connection = null;
//Scanner scanner = null;
BufferedReader reader = null;
String s = "";
String response = "";
try {
request = new URL(requestURL);
// check, if a proxy was defined, if so, use it for the connection
if (this.proxy_to_use != null) {
connection = (HttpURLConnection) request.openConnection(this.proxy_to_use);
}
else {
connection = (HttpURLConnection) request.openConnection();
}
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
connection.connect();
Cache_Control = connection.getHeaderField("Cache-Control");
Expires = connection.getHeaderField("Expires");
X_Forecast_API_Calls = connection.getHeaderField("X-Forecast-API-Calls");
X_Response_Time = connection.getHeaderField("X-Response-Time");
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
//obtain the encoding returned by the server
String encoding = connection.getContentEncoding();
try {
//create the appropriate stream wrapper based on the encoding type
//use UTF-8 when parsing the JSON responses
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
reader = new BufferedReader(new InputStreamReader( new GZIPInputStream( connection.getInputStream() ), "UTF-8"));
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
reader = new BufferedReader(new InputStreamReader( new InflaterInputStream( connection.getInputStream(), new Inflater(true) ), "UTF-8"));
} else {
reader = new BufferedReader(new InputStreamReader( connection.getInputStream(),"UTF-8" ));
}
while( (s = reader.readLine()) != null )
response = s;
} catch (IOException e){
System.err.println("Error: "+e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
System.err.println("Error: "+e.getMessage());
}
}
}
} //if HTTP_OK - End
// else if HttpURLConnection Not Ok
else {
try {
reader = new BufferedReader(new InputStreamReader( connection.getErrorStream() ));
while( (s = reader.readLine()) != null )
response = s;
} catch (IOException e){
System.err.println("Error: "+e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
System.err.println("Error: "+e.getMessage());
}
}
}
//If response is not ok print error and return null
System.err.println("Bad Response: " + response + "\n");
return null;
} //else if HttpURLConnection Not Ok - End
} catch (IOException e) {
System.err.println("Error: "+e.getMessage());
response = null;
} finally {
connection.disconnect();
}
rawResponse = response;
return response;
}//httpGET - end
}//public class - end
|
package com.lekebilen.quasseldroid;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import android.content.SharedPreferences;
import com.lekebilen.quasseldroid.qtcomm.DataStreamVersion;
import com.lekebilen.quasseldroid.qtcomm.QDataInputStream;
import com.lekebilen.quasseldroid.qtcomm.QDataOutputStream;
import com.lekebilen.quasseldroid.qtcomm.QMetaType;
import com.lekebilen.quasseldroid.qtcomm.QMetaTypeRegistry;
import com.lekebilen.quasseldroid.qtcomm.QVariant;
import com.lekebilen.quasseldroid.qtcomm.serializers.Bool;
//TODO: sandsmark, make the constructor not start a connection and put that into its own method connect or something, also need a method to check if we are connected to a core and to disconnect.
public class CoreConnection {
private enum RequestType {
Invalid(0),
Sync(1),
RpcCall(2),
InitRequest(3),
InitData(4),
HeartBeat(5),
HeartBeatReply(6);
int value;
RequestType(int value){
this.value = value;
}
public int getValue(){
return value;
}
public static RequestType getForVal(int val) {
for (RequestType type: values()) {
if (type.value == val)
return type;
}
return Invalid;
}
}
private QDataOutputStream outStream;
private QDataInputStream inStream;
private Map<Integer, Buffer> buffers;
private Map<String, IrcUser> users;
public Map<String, IrcUser> getUsers() {
return users;
}
public static void main(String[] args) {
try {
CoreConnection conn = new CoreConnection("localhost", 4242, "test", "test", null);
} catch (UnknownHostException e) {
System.err.println("Unknown host!");
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
System.err.println("Security error!");
e.printStackTrace();
}
}
public CoreConnection(String host, int port, String username, String password, Boolean ssl)
throws UnknownHostException, IOException, GeneralSecurityException {
users = new HashMap<String, IrcUser>();
// START CREATE SOCKETS
SocketFactory factory = (SocketFactory)SocketFactory.getDefault();
Socket socket = (Socket)factory.createSocket(host, port);
outStream = new QDataOutputStream(socket.getOutputStream());
// END CREATE SOCKETS
// START CLIENT INFO
Map<String, QVariant<?>> initial = new HashMap<String, QVariant<?>>();
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
Date date = new Date();
initial.put("ClientDate", new QVariant<String>(dateFormat.format(date), QVariant.Type.String));
initial.put("UseSsl", new QVariant<Boolean>(ssl, QVariant.Type.Bool));
initial.put("ClientVersion", new QVariant<String>("v0.6.1 (dist-<a href='http://git.quassel-irc.org/?p=quassel.git;a=commit;h=611ebccdb6a2a4a89cf1f565bee7e72bcad13ffb'>611ebcc</a>)", QVariant.Type.String));
initial.put("UseCompression", new QVariant<Boolean>(false, QVariant.Type.Bool));
initial.put("MsgType", new QVariant<String>("ClientInit", QVariant.Type.String));
initial.put("ProtocolVersion", new QVariant<Integer>(10, QVariant.Type.Int));
sendQVariantMap(initial);
// END CLIENT INFO
// START CORE INFO
inStream = new QDataInputStream(socket.getInputStream());
Map<String, QVariant<?>> reply = readQVariantMap();
System.out.println("CORE INFO: ");
for (String key : reply.keySet()) {
System.out.println("\t" + key + " : " + reply.get(key));
}
// TODO: We should check that the core is new and dandy here.
// END CORE INFO
// START SSL CONNECTION
if (ssl) {
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager [] { new CustomTrustManager() };
sslContext.init(null, trustManagers, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, host, port, true);
sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
sslSocket.setUseClientMode(true);
sslSocket.startHandshake();
inStream = new QDataInputStream(sslSocket.getInputStream());
outStream = new QDataOutputStream(sslSocket.getOutputStream());
}
// FINISHED SSL CONNECTION
// START LOGIN
Map<String, QVariant<?>> login = new HashMap<String, QVariant<?>>();
login.put("MsgType", new QVariant<String>("ClientLogin", QVariant.Type.String));
login.put("User", new QVariant<String>(username, QVariant.Type.String));
login.put("Password", new QVariant<String>(password, QVariant.Type.String));
sendQVariantMap(login);
// FINISH LOGIN
// START LOGIN ACK
reply = readQVariantMap();
if (!reply.get("MsgType").toString().equals("ClientLoginAck"))
throw new GeneralSecurityException("Invalid password?");
// END LOGIN ACK
// START SESSION INIT
reply = readQVariantMap();
System.out.println("SESSION INIT: ");
for (String key : reply.keySet()) {
System.out.println("\t" + key + " : " + reply.get(key));
}
Map<String, QVariant<?>> sessionState = (Map<String, QVariant<?>>) reply.get("SessionState").getData();
List<QVariant<?>> bufferInfos = (List<QVariant<?>>) sessionState.get("BufferInfos").getData();
buffers = new HashMap<Integer, Buffer>();
for (QVariant<?> bufferInfoQV: bufferInfos) {
BufferInfo bufferInfo = (BufferInfo)bufferInfoQV.getData();
buffers.put(bufferInfo.id, new Buffer(bufferInfo));
}
// END SESSION INIT
// Now the fun part starts, where we play signal proxy
// START SIGNAL PROXY INIT
sendInitRequest("BacklogManager", "");
sendInitRequest("Network", "1");
sendInitRequest("BufferSyncer", "");
List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>();
packedFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariant.Type.Int));
packedFunc.add(new QVariant<String>("BufferSyncer", QVariant.Type.String));
packedFunc.add(new QVariant<String>("", QVariant.Type.String));
packedFunc.add(new QVariant<String>("requestSetLastSeenMsg", QVariant.Type.String));
packedFunc.add(new QVariant<Integer>(1, "BufferId"));
packedFunc.add(new QVariant<Integer>(1, "MsgId"));
sendQVariantList(packedFunc);
ReadThread readThread = new ReadThread(this);
readThread.start();
// Apparently the client doesn't send heartbeats?
/*TimerTask sendPingAction = new TimerTask() {
public void run() {
}
};*/
// END SIGNAL PROXY
}
/**
* Returns list of buffers in use.
* @return
*/
public Collection<Buffer> getBuffers() {
return buffers.values();
}
private class ReadThread extends Thread {
boolean running = false;
CoreConnection parent;
public ReadThread(CoreConnection parent) {
this.parent = parent;
}
public void run() {
this.running = true;
List<QVariant<?>> packedFunc;
while (running) {
try {
packedFunc = readQVariantList();
} catch (IOException e) {
running = false;//FIXME: handle this properly?
System.err.println("IO error!");
e.printStackTrace();
return;
}
RequestType type = RequestType.getForVal((Integer)packedFunc.remove(0).getData());
String name;
switch (type) {
case HeartBeat:
System.out.println("Got heartbeat");
break;
case InitData:
name = new String(((ByteBuffer)packedFunc.remove(0).getData()).array());
if (name.equals("Network")) {
// Do nothing, for now
} else if (name.equals("BufferSyncer")) {
packedFunc.remove(0); // Object name, not used
List<QVariant<?>> lastSeen = (List<QVariant<?>>) ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("LastSeenMsg").getData();
for (int i=0; i<lastSeen.size()/2; i++) {
int bufferId = (Integer)lastSeen.remove(0).getData();
int msgId = (Integer)lastSeen.remove(0).getData();
if (buffers.containsKey(bufferId)) // We only care for buffers we have open
buffers.get(bufferId).setLastSeenMessage(msgId);
}
List<QVariant<?>> markerLines = (List<QVariant<?>>) ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("MarkerLines").getData();
for (int i=0; i<lastSeen.size()/2; i++) {
int bufferId = (Integer)lastSeen.remove(0).getData();
int msgId = (Integer)lastSeen.remove(0).getData();
if (buffers.containsKey(bufferId))
buffers.get(bufferId).setMarkerLineMessage(msgId);
}
for (int buffer: buffers.keySet()) {
requestBacklog(buffer, buffers.get(buffer).getLastSeenMessage());
}
} else if (name.equals("IrcUser")) {
IrcUser user = new IrcUser();
user.name = (String) packedFunc.remove(0).getData();
Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) packedFunc.remove(0).getData();
user.away = (Boolean) map.get("away").getData();
user.awayMessage = (String) map.get("awayMessage").getData();
user.ircOperator = (String) map.get("ircOperator").getData();
user.nick = (String) map.get("nick").getData();
user.channels = (List<String>) map.get("channels").getData();
users.put(user.nick, user);
} else {
System.out.println("InitData: " + name);
}
break;
case Sync:
String className = packedFunc.remove(0).toString();
packedFunc.remove(0); // object name, we don't really care
String function = packedFunc.remove(0).toString();
if (className.equals("BacklogManager") && function.equals("receiveBacklog")) {
int buffer = (Integer) packedFunc.remove(0).getData();
packedFunc.remove(0); // first
packedFunc.remove(0); // last
packedFunc.remove(0); // limit
packedFunc.remove(0); // additional
for (QVariant<?> message: (List<QVariant<?>>)(packedFunc.remove(0).getData())) {
buffers.get(buffer).addBacklog((Message) message.getData());
}
} else if (className.equals("Network") && function.equals("addIrcUser")) {
String nick = (String) packedFunc.remove(0).getData();
try {
sendInitRequest("IrcUser", "1/" + nick);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("Sync request: " + className + "::" + function);
}
break;
case RpcCall:
String functionName = packedFunc.remove(0).toString();
// int buffer = functionName.charAt(0);
// functionName = functionName.substring(1);
if (functionName.equals("2displayMsg(Message)")) {
Message message = (Message) packedFunc.remove(0).getData();
buffers.get(message.bufferInfo.id).addBacklog(message);
} else {
System.out.println("RpcCall: " + functionName + " (" + packedFunc + ").");
}
break;
default:
System.out.println(type);
}
}
}
}
private void sendQVariant(QVariant<?> data) throws IOException {
// See how much data we're going to send
ByteArrayOutputStream baos = new ByteArrayOutputStream();
QDataOutputStream bos = new QDataOutputStream(baos);
QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, bos, data);
// Tell the other end how much data to expect
outStream.writeUInt(bos.size(), 32);
// Sanity check, check that we can decode our own stuff before sending it off
QDataInputStream bis = new QDataInputStream(new ByteArrayInputStream(baos.toByteArray()));
QMetaTypeRegistry.instance().getTypeForId(QMetaType.Type.QVariant.getValue()).getSerializer().unserialize(bis, DataStreamVersion.Qt_4_2);
// Send data
QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, outStream, data);
}
private void sendQVariantMap(Map<String, QVariant<?>> data) throws IOException {
QVariant<Map<String, QVariant<?>>> bufstruct = new QVariant<Map<String, QVariant<?>>>(data, QVariant.Type.Map);
sendQVariant(bufstruct);
}
private void sendQVariantList(List<QVariant<?>> data) throws IOException {
QVariant<List<QVariant<?>>> bufstruct = new QVariant<List<QVariant<?>>>(data, QVariant.Type.List);
sendQVariant(bufstruct);
}
private Map<String, QVariant<?>> readQVariantMap() throws IOException {
long len = inStream.readUInt(32);
QVariant <Map<String, QVariant<?>>> v = (QVariant <Map<String, QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream);
Map<String, QVariant<?>>ret = (Map<String, QVariant<?>>)v.getData();
return ret;
}
private List<QVariant<?>> readQVariantList() throws IOException {
long len = inStream.readUInt(32);
QVariant <List<QVariant<?>>> v = (QVariant <List<QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream);
List<QVariant<?>>ret = (List<QVariant<?>>)v.getData();
return ret;
}
private void sendInitRequest(String className, String objectName) throws IOException {
List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>();
packedFunc.add(new QVariant<Integer>(RequestType.InitRequest.getValue(), QVariant.Type.Int));
packedFunc.add(new QVariant<String>(className, QVariant.Type.String));
packedFunc.add(new QVariant<String>(objectName, QVariant.Type.String));
sendQVariantList(packedFunc);
}
private void requestBacklog(int buffer, int first) {
requestBacklog(buffer, first, -1);
}
private void requestBacklog(int buffer, int firstMsg, int lastMsg) {
List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>();
retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariant.Type.Int));
retFunc.add(new QVariant<String>("BacklogManager", QVariant.Type.String));
retFunc.add(new QVariant<String>("", QVariant.Type.String));
retFunc.add(new QVariant<String>("requestBacklog", QVariant.Type.String));
retFunc.add(new QVariant<Integer>(buffer, "BufferId"));
retFunc.add(new QVariant<Integer>(firstMsg, "MsgId"));
retFunc.add(new QVariant<Integer>(lastMsg, "MsgId"));
retFunc.add(new QVariant<Integer>(Config.backlogLimit, QVariant.Type.Int));
retFunc.add(new QVariant<Integer>(Config.backlogAdditional, QVariant.Type.Int));
try {
sendQVariantList(retFunc);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(int buffer, String message) {
List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>();
retFunc.add(new QVariant<Integer>(RequestType.RpcCall.getValue(), QVariant.Type.Int));
retFunc.add(new QVariant<String>("2sendInput(BufferInfo,QString)", QVariant.Type.String));
retFunc.add(new QVariant<BufferInfo>(buffers.get(buffer).getInfo(), "BufferInfo"));
retFunc.add(new QVariant<String>("/SAY " + message, QVariant.Type.String));
try {
sendQVariantList(retFunc);
} catch (IOException e) {
e.printStackTrace();
}
}
private class CustomTrustManager implements javax.net.ssl.X509TrustManager {
/*
* The default X509TrustManager returned by SunX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509TrustManager doesn't trust it.
*/
X509TrustManager defaultTrustManager;
CustomTrustManager() throws GeneralSecurityException {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
//ks.load(new FileInputStream("trustedCerts"),
// "passphrase".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager tms [] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look
* for an instance of X509TrustManager. If found,
* use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new GeneralSecurityException("Couldn't initialize");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
}
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
String hashedCert = hash(chain[0].getEncoded());
//TODO: Had to comment out this because we no longer have a shared preferences here, fix somehow?
// if (CoreConnection.this.settings.contains("certificate")) {
// if (!CoreConnection.this.settings.getString("certificate", "lol").equals(hashedCert)) {
// throw new CertificateException();
// } else {
// System.out.println("Storing new certificate: " + hashedCert);
// CoreConnection.this.settings.edit().putString("certificate", hashedCert).commit();
}
}
private String hash(byte[] s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA1");
digest.update(s);
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return defaultTrustManager.getAcceptedIssuers();
}
}
}
|
package org.jasig.portal.channels;
import org.xml.sax.ContentHandler;
import java.util.*;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.xml.parsers.*;
import org.w3c.tidy.*;
import org.w3c.dom.Document;
import org.jasig.portal.utils.CookieCutter;
import org.jasig.portal.*;
import org.jasig.portal.utils.*;
import org.jasig.portal.services.LogService;
import org.jasig.portal.security.IPerson;
public class CWebProxy implements IMultithreadedChannel, IMultithreadedCacheable, IMultithreadedMimeResponse
{
Map stateTable;
// to prepend to the system-wide cache key
static final String systemCacheId="org.jasig.portal.channels.CWebProxy";
// All state variables now stored here
private class ChannelState
{
private int id;
private IPerson iperson;
private String person;
private String fullxmlUri;
private String buttonxmlUri;
private String xmlUri;
private String passThrough;
private String tidy;
private String sslUri;
private String xslTitle;
private String xslUri;
private String infoUri;
private String helpUri;
private String editUri;
private String cacheDefaultScope;
private String cacheScope;
private String cacheDefaultMode;
private String cacheMode;
private String reqParameters;
private long cacheDefaultTimeout;
private long cacheTimeout;
private ChannelRuntimeData runtimeData;
private CookieCutter cookieCutter;
private URLConnection connHolder;
public ChannelState ()
{
fullxmlUri = buttonxmlUri = xmlUri = passThrough = sslUri = null;
xslTitle = xslUri = infoUri = helpUri = editUri = tidy = null;
id = 0;
cacheMode = cacheScope = null;
iperson = null;
cacheTimeout = cacheDefaultTimeout = PropertiesManager.getPropertyAsLong("org.jasig.portal.channels.CWebProxy.cache_default_timeout");
cacheDefaultMode = PropertiesManager.getProperty("org.jasig.portal.channels.CWebProxy.cache_default_mode");
cacheDefaultScope = PropertiesManager.getProperty("org.jasig.portal.channels.CWebProxy.cache_default_scope");
runtimeData = null;
cookieCutter = new CookieCutter();
}
}
public CWebProxy ()
{
stateTable = Collections.synchronizedMap(new HashMap());
}
/**
* Passes ChannelStaticData to the channel.
* This is done during channel instantiation time.
* see org.jasig.portal.ChannelStaticData
* @param sd channel static data
* @see ChannelStaticData
*/
public void setStaticData (ChannelStaticData sd, String uid) throws ResourceMissingException
{
ChannelState state = new ChannelState();
state.id = sd.getPerson().getID();
state.iperson = sd.getPerson();
state.person = sd.getParameter("cw_person");
state.xmlUri = sd.getParameter ("cw_xml");
state.sslUri = sd.getParameter ("cw_ssl");
state.fullxmlUri = sd.getParameter ("cw_xml");
state.passThrough = sd.getParameter ("cw_passThrough");
state.tidy = sd.getParameter ("cw_tidy");
state.infoUri = sd.getParameter ("cw_info");
state.helpUri = sd.getParameter ("cw_help");
state.editUri = sd.getParameter ("cw_edit");
String cacheScope = sd.getParameter ("cw_cacheDefaultScope");
if (cacheScope != null)
state.cacheDefaultScope = cacheScope;
cacheScope = sd.getParameter ("cw_cacheScope");
if (cacheScope != null)
state.cacheScope = cacheScope;
String cacheMode = sd.getParameter ("cw_cacheDefaultMode");
if (cacheMode != null)
state.cacheDefaultMode = cacheMode;
cacheMode = sd.getParameter ("cw_cacheMode");
if (cacheMode != null)
state.cacheMode = cacheMode;
String cacheTimeout = sd.getParameter("cw_cacheDefaultTimeout");
if (cacheTimeout != null)
state.cacheDefaultTimeout = Long.parseLong(cacheTimeout);
cacheTimeout = sd.getParameter("cw_cacheTimeout");
if (cacheTimeout != null)
state.cacheTimeout = Long.parseLong(cacheTimeout);
stateTable.put(uid,state);
}
/**
* Passes ChannelRuntimeData to the channel.
* This function is called prior to the renderXML() call.
* @param rd channel runtime data
* @see ChannelRuntimeData
*/
public void setRuntimeData (ChannelRuntimeData rd, String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
LogService.instance().log(LogService.ERROR,"CWebProxy:setRuntimeData() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else
{
state.runtimeData = rd;
String xmlUri = state.runtimeData.getParameter("cw_xml");
if (xmlUri != null) {
state.xmlUri = xmlUri;
// don't need an explicit reset if a new URI is provided.
state.buttonxmlUri = null;
}
String sslUri = state.runtimeData.getParameter("cw_ssl");
if (sslUri != null)
state.sslUri = sslUri;
String xslTitle = state.runtimeData.getParameter("cw_xslTitle");
if (xslTitle != null)
state.xslTitle = xslTitle;
String xslUri = state.runtimeData.getParameter("cw_xsl");
if (xslUri != null)
state.xslUri = xslUri;
String passThrough = state.runtimeData.getParameter("cw_passThrough");
if (passThrough != null)
state.passThrough = passThrough;
String tidy = state.runtimeData.getParameter("cw_tidy");
if (tidy != null)
state.tidy = tidy;
String infoUri = state.runtimeData.getParameter("cw_info");
if (infoUri != null)
state.infoUri = infoUri;
String editUri = state.runtimeData.getParameter("cw_edit");
if (editUri != null)
state.editUri = editUri;
String helpUri = state.runtimeData.getParameter("cw_help");
if (helpUri != null)
state.helpUri = helpUri;
// need a way to see if cacheScope, cacheMode, cacheTimeout were
// set in static data if this is the first time.
String cacheTimeout = state.runtimeData.getParameter("cw_cacheDefaultTimeout");
if (cacheTimeout != null)
state.cacheDefaultTimeout = Long.parseLong(cacheTimeout);
cacheTimeout = state.runtimeData.getParameter("cw_cacheTimeout");
if (cacheTimeout != null)
state.cacheTimeout = Long.parseLong(cacheTimeout);
else
state.cacheTimeout = state.cacheDefaultTimeout;
String cacheDefaultScope = state.runtimeData.getParameter("cw_cacheDefaultScope");
if (cacheDefaultScope != null) {
// PSEUDO see if it's a reduction fine, otherwise log error
state.cacheDefaultScope = cacheDefaultScope;
}
String cacheScope = state.runtimeData.getParameter("cw_cacheScope");
if (cacheScope != null) {
// PSEUDO see if it's a reduction fine, otherwise a problem
// for now all instance -> user
if ( state.cacheDefaultScope.equalsIgnoreCase("system") )
state.cacheScope = cacheScope;
else {
state.cacheScope = state.cacheDefaultScope;
LogService.instance().log(LogService.INFO,
"CWebProxy:setRuntimeData() : ignoring illegal scope reduction from "
+ state.cacheDefaultScope + " to " + cacheScope);
}
} else
state.cacheScope = state.cacheDefaultScope;
LogService.instance().log(LogService.DEBUG, "CWebProxy setRuntimeData(): state.cacheDefaultMode was " + state.cacheDefaultMode);
String cacheDefaultMode = state.runtimeData.getParameter("cw_cacheDefaultMode");
LogService.instance().log(LogService.DEBUG, "CWebProxy setRuntimeData(): cw_cacheDefaultMode is " + cacheDefaultMode);
if (cacheDefaultMode != null) {
// maybe don't allow if scope is system?
state.cacheDefaultMode = cacheDefaultMode;
}
LogService.instance().log(LogService.DEBUG, "CWebProxy setRuntimeData(): state.cacheDefaultMode is now " + state.cacheDefaultMode);
LogService.instance().log(LogService.DEBUG, "CWebProxy setRuntimeData(): state.cacheMode was " + state.cacheMode);
String cacheMode = state.runtimeData.getParameter("cw_cacheMode");
LogService.instance().log(LogService.DEBUG, "CWebProxy setRuntimeData(): cw_cacheMode is " + cacheMode);
if (cacheMode != null) {
// maybe don't allow if scope is system?
state.cacheMode = cacheMode;
} else
state.cacheMode = state.cacheDefaultMode;
LogService.instance().log(LogService.DEBUG, "CWebProxy setRuntimeData(): state.cacheMode is now " + state.cacheMode);
// reset is a one-time thing.
String reset = state.runtimeData.getParameter("cw_reset");
if (reset != null) {
if (reset.equalsIgnoreCase("return")) {
state.buttonxmlUri = null;
}
// else if (reset.equalsIgnoreCase("reset")) {
// call setStaticData with our cached copy.
}
if ( state.buttonxmlUri != null )
state.fullxmlUri = state.buttonxmlUri;
else {
//if (this.passThrough != null )
// LogService.instance().log(LogService.DEBUG, "CWebProxy: passThrough: "+this.passThrough);
// Is this a case where we need to pass request parameters to the xmlURI?
if ( state.passThrough != null &&
!state.passThrough.equalsIgnoreCase("none") &&
( state.passThrough.equalsIgnoreCase("all") ||
state.passThrough.equalsIgnoreCase("application") ||
rd.getParameter("cw_inChannelLink") != null ) )
{
LogService.instance().log(LogService.DEBUG, "CWebProxy: xmlUri is " + state.xmlUri);
StringBuffer newXML = new StringBuffer();
String appendchar = "";
// want all runtime parameters not specific to WebProxy
Enumeration e=rd.getParameterNames ();
if (e!=null)
{
while (e.hasMoreElements ())
{
String pName = (String) e.nextElement ();
if ( !pName.startsWith("cw_") && !pName.trim().equals("")) {
String[] value_array = rd.getParameterValues(pName);
if ( value_array == null || value_array.length == 0 ) {
// keyword-style parameter
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
} else {
int i = 0;
while ( i < value_array.length ) {
LogService.instance().log(LogService.DEBUG, "CWebProxy: ANDREW adding runtime parameter: " + pName);
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
newXML.append("=");
newXML.append(URLEncoder.encode(value_array[i++]));
}
}
}
}
}
// here add in attributes according to cw_person
if (state.person != null) {
StringTokenizer st = new StringTokenizer(state.person,",");
if (st != null)
{
while (st.hasMoreElements ())
{
String pName = st.nextToken();
if ((pName!=null)&&(!pName.trim().equals(""))){
LogService.instance().log(LogService.DEBUG, "CWebProxy: ANDREW adding person attribute: " + pName);
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
newXML.append("=");
// note, this only gets the first one if it's a
// java.util.Vector. Should check
String pVal = (String)state.iperson.getAttribute(pName);
if (pVal != null)
newXML.append(URLEncoder.encode(pVal));
}
}
}
}
// end new cw_person code
// to add: if not already set, make a copy of sd for
// the "reset" command
state.reqParameters = newXML.toString();
state.fullxmlUri = state.xmlUri;
if (!state.runtimeData.getHttpRequestMethod().equals("POST")){
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals(""))){
appendchar = (state.xmlUri.indexOf('?') == -1) ? "?" : "&";
// BUG 772 - this doesn't seem to catch all cases.
state.fullxmlUri = state.fullxmlUri+appendchar+state.reqParameters;
}
state.reqParameters = null;
}
LogService.instance().log(LogService.DEBUG, "CWebProxy: fullxmlUri now: " + state.fullxmlUri);
}
}
}
}
/**
* Process portal events. Currently supported events are
* EDIT_BUTTON_EVENT, HELP_BUTTON_EVENT, ABOUT_BUTTON_EVENT,
* and SESSION_DONE. The button events work by changing the xmlUri.
* The new Uri's content should contain a link that will refer back
* to the old one at the end of its task.
* @param ev the event
*/
public void receiveEvent (PortalEvent ev, String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
LogService.instance().log(LogService.ERROR,"CWebProxy:receiveEvent() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else {
int evnum = ev.getEventNumber();
switch (evnum)
{
case PortalEvent.EDIT_BUTTON_EVENT:
if (state.editUri != null)
state.buttonxmlUri = state.editUri;
break;
case PortalEvent.HELP_BUTTON_EVENT:
if (state.helpUri != null)
state.buttonxmlUri = state.helpUri;
break;
case PortalEvent.ABOUT_BUTTON_EVENT:
if (state.infoUri != null)
state.buttonxmlUri = state.infoUri;
break;
case PortalEvent.SESSION_DONE:
stateTable.remove(uid);
break;
// case PortalEvent.UNSUBSCRIBE: // remove db entry for channel
default:
break;
}
}
}
/**
* Acquires ChannelRuntimeProperites from the channel.
* This function may be called by the portal framework throughout the session.
* @see ChannelRuntimeProperties
*/
public ChannelRuntimeProperties getRuntimeProperties (String uid)
{
ChannelRuntimeProperties rp=new ChannelRuntimeProperties();
// determine if such channel is registered
if (stateTable.get(uid) == null)
{
rp.setWillRender(false);
LogService.instance().log(LogService.ERROR,"CWebProxy:getRuntimeProperties() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
}
return rp;
}
/**
* Ask channel to render its content.
* @param out the SAX ContentHandler to output content to
*/
public void renderXML (ContentHandler out, String uid) throws PortalException
{
ChannelState state=(ChannelState)stateTable.get(uid);
if (state == null)
LogService.instance().log(LogService.ERROR,"CWebProxy:renderXML() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else
{
String xml = null;
Document xmlDoc = null;
try
{
if (state.tidy != null && state.tidy.equals("on"))
xml = getXmlString (state.fullxmlUri, state);
else
xmlDoc = getXmlDocument (state.fullxmlUri, state);
}
catch (Exception e)
{
throw new ResourceMissingException (state.fullxmlUri, "", e.getMessage());
}
state.runtimeData.put("baseActionURL", state.runtimeData.getBaseActionURL());
state.runtimeData.put("downloadActionURL", state.runtimeData.getBaseWorkerURL("download"));
// Runtime data parameters are handed to the stylesheet.
// Add any static data parameters so it gets a full set of variables.
// Possibly this should be a copy.
if (state.xmlUri != null)
state.runtimeData.put("cw_xml", state.xmlUri);
if (state.sslUri != null)
state.runtimeData.put("cs_ssl", state.sslUri);
if (state.xslTitle != null)
state.runtimeData.put("cw_xslTitle", state.xslTitle);
if (state.xslUri != null)
state.runtimeData.put("cw_xsl", state.xslUri);
if (state.passThrough != null)
state.runtimeData.put("cw_passThrough", state.passThrough);
if (state.tidy != null)
state.runtimeData.put("cw_tidy", state.tidy);
if (state.infoUri != null)
state.runtimeData.put("cw_info", state.infoUri);
if (state.helpUri != null)
state.runtimeData.put("cw_help", state.helpUri);
if (state.editUri != null)
state.runtimeData.put("cw_edit", state.editUri);
XSLT xslt = new XSLT(this);
if (xmlDoc != null)
xslt.setXML(xmlDoc);
else
xslt.setXML(xml);
if (state.xslUri != null)
xslt.setXSL(state.xslUri);
else
xslt.setXSL(state.sslUri, state.xslTitle, state.runtimeData.getBrowserInfo());
xslt.setTarget(out);
xslt.setStylesheetParameters(state.runtimeData);
xslt.transform();
}
}
/**
* Get the contents of a URI as a Document object. This is used if tidy
* is not set or equals 'off'.
* Also includes support for cookies.
* @param uri the URI
* @return the data pointed to by a URI as a Document object
*/
private Document getXmlDocument(String uri, ChannelState state) throws Exception
{
URLConnection urlConnect = getConnection(uri, state);
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(false);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
DTDResolver dtdResolver = new DTDResolver();
docBuilder.setEntityResolver(dtdResolver);
return docBuilder.parse(urlConnect.getInputStream());
}
/**
* Get the contents of a URI as a String but send it through tidy first.
* Also includes support for cookies.
* @param uri the URI
* @return the data pointed to by a URI as a String
*/
private String getXmlString (String uri, ChannelState state) throws Exception
{
URLConnection urlConnect = getConnection(uri, state);
String xml;
if ( (state.tidy != null) && (state.tidy.equalsIgnoreCase("on")) )
{
Tidy tidy = new Tidy ();
tidy.setXHTML (true);
tidy.setDocType ("omit");
tidy.setQuiet(true);
tidy.setShowWarnings(false);
tidy.setNumEntities(true);
tidy.setWord2000(true);
if ( System.getProperty("os.name").indexOf("Windows") != -1 )
tidy.setErrout( new PrintWriter ( new FileOutputStream (new File ("nul") ) ) );
else
tidy.setErrout( new PrintWriter ( new FileOutputStream (new File ("/dev/null") ) ) );
ByteArrayOutputStream stream = new ByteArrayOutputStream (1024);
tidy.parse (urlConnect.getInputStream(), new BufferedOutputStream (stream));
if ( tidy.getParseErrors() > 0 )
throw new GeneralRenderingException("Unable to convert input document to XHTML");
xml = stream.toString();
}
else
{
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnect.getInputStream()));
StringBuffer sbText = new StringBuffer (1024);
while ((line = in.readLine()) != null)
sbText.append (line).append ("\n");
xml = sbText.toString ();
}
return xml;
}
private URLConnection getConnection(String uri, ChannelState state) throws Exception{
URL url = ResourceLoader.getResourceAsURL(this.getClass(), uri);
String domain = url.getHost().trim();
String path = url.getPath();
if ( path.indexOf("/") != -1 )
{
if (path.lastIndexOf("/") != 0)
path = path.substring(0, path.lastIndexOf("/"));
}
String port = Integer.toString(url.getPort());
URLConnection urlConnect = url.openConnection();
String protocol = url.getProtocol();
if (protocol.equals("http") || protocol.equals("https"))
{
if (domain != null && path != null)
{
HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
httpUrlConnect.setInstanceFollowRedirects(false);
//send any headers to proxied application
if(state.cookieCutter.cookiesExist())
state.cookieCutter.sendCookieHeader(httpUrlConnect, domain, path, port);
// added 5/13/2002 by ASV - print post data
if (state.runtimeData.getHttpRequestMethod().equals("POST")){
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals(""))){
httpUrlConnect.setRequestMethod("POST");
httpUrlConnect.setAllowUserInteraction(false);
httpUrlConnect.setDoOutput(true);
PrintWriter post = new PrintWriter(httpUrlConnect.getOutputStream());
post.print(state.reqParameters);
post.flush();
post.close();
state.reqParameters=null;
}
}
state.cookieCutter.storeCookieHeader(httpUrlConnect, domain, path, port);
int status = httpUrlConnect.getResponseCode();
String location = httpUrlConnect.getHeaderField("Location");
switch (status)
{
case HttpURLConnection.HTTP_NOT_FOUND:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 404: Not Found");
case HttpURLConnection.HTTP_FORBIDDEN:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 403: Forbidden");
case HttpURLConnection.HTTP_INTERNAL_ERROR:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 500: Internal Server Error");
case HttpURLConnection.HTTP_NO_CONTENT:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 204: No Content");
/*
* Note: these cases apply to http status codes 302 and 303
* this will handle automatic redirection to a new GET URL
*/
case HttpURLConnection.HTTP_MOVED_TEMP:
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
break;
case HttpURLConnection.HTTP_SEE_OTHER:
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
break;
/*
* Note: this cases apply to http status code 301
* it will handle the automatic redirection of GET requests.
* The spec calls for a POST redirect to be verified manually by the user
* Rather than bypass this security restriction, we will throw an exception
*/
case HttpURLConnection.HTTP_MOVED_PERM:
if (state.runtimeData.getHttpRequestMethod().equals("GET")){
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
}
else {
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 301: POST Redirection currently not supported");
}
break;
default:
break;
}
return (URLConnection) httpUrlConnect;
}
}
return urlConnect;
}
public ChannelCacheKey generateKey(String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
{
LogService.instance().log(LogService.ERROR,"CWebProxy:generateKey() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
return null;
}
if ( state.cacheMode.equalsIgnoreCase("none") )
return null;
// else if http see first if caching is on or off. if it's on,
// store the validity time in the state, cache it, and further
// resolve later with isValid.
// check cache-control, no-cache, must-revalidate, max-age,
// Date & Expires, expiry in past
// for 1.0 check pragma for no-cache
// add a warning to docs about not a full http 1.1 impl.
ChannelCacheKey k = new ChannelCacheKey();
StringBuffer sbKey = new StringBuffer(1024);
if ( state.cacheScope.equalsIgnoreCase("instance") ) {
k.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE);
} else {
k.setKeyScope(ChannelCacheKey.SYSTEM_KEY_SCOPE);
sbKey.append(systemCacheId).append(": ");
if ( state.cacheScope.equalsIgnoreCase("user") ) {
sbKey.append("userId:").append(state.id).append(", ");
}
}
// Later:
// if scope==guest, do same as user, but use GUEST instead if isGuest()
// Scope descending order: system, guest, user, instance.
sbKey.append("sslUri:").append(state.sslUri).append(", ");
// xslUri may either be specified as a parameter to this channel
// or we will get it by looking in the stylesheet list file
String xslUriForKey = state.xslUri;
try {
if (xslUriForKey == null) {
String sslUri = ResourceLoader.getResourceAsURLString(this.getClass(), state.sslUri);
xslUriForKey = XSLT.getStylesheetURI(sslUri, state.runtimeData.getBrowserInfo());
}
} catch (Exception e) {
xslUriForKey = "Not attainable: " + e;
}
sbKey.append("xslUri:").append(xslUriForKey).append(", ");
sbKey.append("fullxmlUri:").append(state.fullxmlUri).append(", ");
sbKey.append("passThrough:").append(state.passThrough).append(", ");
sbKey.append("tidy:").append(state.tidy);
k.setKey(sbKey.toString());
k.setKeyValidity(new Long(System.currentTimeMillis()));
return k;
}
public boolean isCacheValid(Object validity,String uid)
{
if (!(validity instanceof Long))
return false;
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
{
LogService.instance().log(LogService.ERROR,"CWebProxy:isCacheValid() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
return false;
}
else
return (System.currentTimeMillis() - ((Long)validity).longValue() < state.cacheTimeout*1000);
}
public String getContentType(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
return state.connHolder.getContentType();
}
public InputStream getInputStream(String uid) throws IOException {
ChannelState state = (ChannelState)stateTable.get(uid);
InputStream rs = state.connHolder.getInputStream();
state.connHolder = null;
return rs;
}
public void downloadData(OutputStream out,String uid) throws IOException {
throw(new IOException("CWebProxy: donloadData method not supported - use getInputStream only"));
}
public String getName(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
return "proxyDL";
}
public Map getHeaders(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
try {
state.connHolder= getConnection(state.fullxmlUri, state);
}
catch (Exception e){
LogService.instance().log(LogService.ERROR,e);
}
Map rhdrs = new HashMap();
int i = 0;
while (state.connHolder.getHeaderFieldKey(i) != null){
rhdrs.put(state.connHolder.getHeaderFieldKey(i),state.connHolder.getHeaderField(i));
i++;
}
return rhdrs;
}
}
/*
* Developer's notes for convenience. Will be deleted later.
* Cache control parameters:
* Static params
* cw_cacheDefaultTimeout timeout in seconds.
* cw_cacheDefaultScope "system" - one copy for all users
* "guest" - one copy for guest, others by user
* "user" - one copy per user
* "instance" - cache for this instance only
* cw_cacheDefaultMode "none" - normally don't cache
* "init" - only cache initial view
* "http" - follow http caching directives
* "all" - why not? cache everything.
* Runtime only params:
* cw_cacheTimeout override default for this request only
* cw_cacheScope override default for this request only
* cw_cacheMode override default for this request only
*
* Note: all static parameters can be replaced via equivalent runtime.
*
* The Scope can only be reduced, never increased.
*/
/*
* NOTE could cw_person be multi-valued instead of comma-sep?
* cw_restrict should work the same way.
* NOTE Does IPerson contain multiple instances of attributes?
* cw_restrict - a list of runtime parameters that cannot be changed.
* possibly allow multi-values, with params. indicating
* the param can only be changed to that?
* - can we encode the scope restrictions with this
* as a default?
*/
|
package com.lekebilen.quasseldroid;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Message;
import android.util.Log;
import com.lekebilen.quasseldroid.qtcomm.DataStreamVersion;
import com.lekebilen.quasseldroid.qtcomm.QDataInputStream;
import com.lekebilen.quasseldroid.qtcomm.QDataOutputStream;
import com.lekebilen.quasseldroid.qtcomm.QMetaType;
import com.lekebilen.quasseldroid.qtcomm.QMetaTypeRegistry;
import com.lekebilen.quasseldroid.qtcomm.QVariant;
public class CoreConnection {
@SuppressWarnings("unused")
private static final String TAG = CoreConnection.class.getSimpleName();
public CoreConnection(String address, int port, String username,
String password, Boolean ssl, CoreConnService parent) {
this.address = address;
this.port = port;
this.username = username;
this.password = password;
this.ssl = ssl;
this.service = parent;
this.nicks = new HashMap<Integer, String>();
this.connected = false;
}
/**
* Checks whether the core is available.
*/
public boolean isConnected() {
return (connected &&
socket != null && socket.isConnected() &&
readThread != null && readThread.isAlive());
}
/**
* Gets the users own nick on a given network.
* @param networkId the network to get the nick for
* @return the nick of the user
*/
public String getNick(int networkId) {
return nicks.get(networkId);
}
/**
* requests the core to set a given buffer as read
* @param buffer the buffer id to set as read
*/
public void requestMarkBufferAsRead(int buffer) {
List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>();
retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariant.Type.Int));
retFunc.add(new QVariant<String>("BacklogManager", QVariant.Type.String));
retFunc.add(new QVariant<String>("", QVariant.Type.String));
retFunc.add(new QVariant<String>("requestMarkBufferAsRead", QVariant.Type.String));
retFunc.add(new QVariant<Integer>(buffer, "BufferId"));
try {
sendQVariantList(retFunc);
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
}
/**
* Requests all buffers.
*/
public void requestBuffers() {
try {
sendInitRequest("BufferSyncer", "");
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
}
/**
* Requests the unread backlog for a given buffer.
*/
public void requestBacklog(int buffer) {
requestBacklog(buffer, buffers.get(buffer).getLastSeenMessage());
}
/**
* Requests moar backlog for a give buffer
* @param buffer Buffer id to request moar for
*/
public void requestMoreBacklog(int buffer) {
requestBacklog(buffer, -1, buffers.get(buffer).getBacklogEntry(0).messageId, backlogFetchAmount);
}
/**
* Requests all backlog from a given message ID until the current.
*/
public void requestBacklog(int buffer, int firstMsgId) {
requestBacklog(buffer, firstMsgId, -1);
}
/**
* Requests backlog between two given message IDs.
*/
public void requestBacklog(int buffer, int firstMsgId, int lastMsgId) {
requestBacklog(buffer, firstMsgId, lastMsgId, Config.backlogAdditional);
}
public void requestBacklog(int buffer, int firstMsgId, int lastMsgId, int maxAmount) {
List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>();
retFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariant.Type.Int));
retFunc.add(new QVariant<String>("BacklogManager", QVariant.Type.String));
retFunc.add(new QVariant<String>("", QVariant.Type.String));
retFunc.add(new QVariant<String>("requestBacklog", QVariant.Type.String));
retFunc.add(new QVariant<Integer>(buffer, "BufferId"));
retFunc.add(new QVariant<Integer>(firstMsgId, "MsgId"));
retFunc.add(new QVariant<Integer>(lastMsgId, "MsgId"));
retFunc.add(new QVariant<Integer>(maxAmount, QVariant.Type.Int));
retFunc.add(new QVariant<Integer>(0, QVariant.Type.Int));
try {
sendQVariantList(retFunc);
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
}
/**
* Sends an IRC message to a given buffer
* @param buffer buffer to send to
* @param message content of message
*/
public void sendMessage(int buffer, String message) {
if (message.charAt(0) == '/') {
String t[] = message.split(" ");
message = t[0].toUpperCase();
if (t.length > 1){
for (int i=1; i<t.length; i++) {
message += ' ' + t[i];
}
}
} else {
message = "/SAY " + message;
}
List<QVariant<?>> retFunc = new LinkedList<QVariant<?>>();
retFunc.add(new QVariant<Integer>(RequestType.RpcCall.getValue(), QVariant.Type.Int));
retFunc.add(new QVariant<String>("2sendInput(BufferInfo,QString)", QVariant.Type.String));
retFunc.add(new QVariant<BufferInfo>(buffers.get(buffer).getInfo(), "BufferInfo"));
retFunc.add(new QVariant<String>(message, QVariant.Type.String));
try {
sendQVariantList(retFunc);
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
}
/**
* Initiates a connection.
*/
public void connect() throws UnknownHostException, IOException, GeneralSecurityException {
// START CREATE SOCKETS
SocketFactory factory = (SocketFactory)SocketFactory.getDefault();
socket = (Socket)factory.createSocket(address, port);
outStream = new QDataOutputStream(socket.getOutputStream());
// END CREATE SOCKETS
// START CLIENT INFO
Map<String, QVariant<?>> initial = new HashMap<String, QVariant<?>>();
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
Date date = new Date();
initial.put("ClientDate", new QVariant<String>(dateFormat.format(date), QVariant.Type.String));
initial.put("UseSsl", new QVariant<Boolean>(ssl, QVariant.Type.Bool));
initial.put("ClientVersion", new QVariant<String>("v0.6.1 (dist-<a href='http://git.quassel-irc.org/?p=quassel.git;a=commit;h=611ebccdb6a2a4a89cf1f565bee7e72bcad13ffb'>611ebcc</a>)", QVariant.Type.String));
initial.put("UseCompression", new QVariant<Boolean>(false, QVariant.Type.Bool));
initial.put("MsgType", new QVariant<String>("ClientInit", QVariant.Type.String));
initial.put("ProtocolVersion", new QVariant<Integer>(10, QVariant.Type.Int));
sendQVariantMap(initial);
// END CLIENT INFO
// START CORE INFO
inStream = new QDataInputStream(socket.getInputStream());
Map<String, QVariant<?>> reply = readQVariantMap();
System.out.println("CORE INFO: ");
for (String key : reply.keySet()) {
System.out.println("\t" + key + " : " + reply.get(key));
}
// TODO: We should check that the core is new and dandy here.
// END CORE INFO
// START SSL CONNECTION
if (ssl) {
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager [] { new CustomTrustManager() };
sslContext.init(null, trustManagers, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address, port, true);
sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
sslSocket.setUseClientMode(true);
sslSocket.startHandshake();
inStream = new QDataInputStream(sslSocket.getInputStream());
outStream = new QDataOutputStream(sslSocket.getOutputStream());
socket = sslSocket;
}
// FINISHED SSL CONNECTION
// START LOGIN
Map<String, QVariant<?>> login = new HashMap<String, QVariant<?>>();
login.put("MsgType", new QVariant<String>("ClientLogin", QVariant.Type.String));
login.put("User", new QVariant<String>(username, QVariant.Type.String));
login.put("Password", new QVariant<String>(password, QVariant.Type.String));
sendQVariantMap(login);
// FINISH LOGIN
// START LOGIN ACK
reply = readQVariantMap();
if (!reply.get("MsgType").toString().equals("ClientLoginAck"))
throw new GeneralSecurityException("Invalid password?");
// END LOGIN ACK
// START SESSION INIT
reply = readQVariantMap();
System.out.println("SESSION INIT: ");
for (String key : reply.keySet()) {
System.out.println("\t" + key + " : " + reply.get(key));
}
Map<String, QVariant<?>> sessionState = (Map<String, QVariant<?>>) reply.get("SessionState").getData();
List<QVariant<?>> bufferInfos = (List<QVariant<?>>) sessionState.get("BufferInfos").getData();
buffers = new HashMap<Integer, Buffer>(bufferInfos.size());
for (QVariant<?> bufferInfoQV: bufferInfos) {
BufferInfo bufferInfo = (BufferInfo)bufferInfoQV.getData();
buffers.put(bufferInfo.id, new Buffer(bufferInfo));
}
List<QVariant<?>> networkIds = (List<QVariant<?>>) sessionState.get("NetworkIds").getData();
networks = new ArrayList<Integer>(networkIds.size());
for (QVariant<?> networkId: networkIds) {
networks.add((Integer) networkId.getData());
}
// END SESSION INIT
// Now the fun part starts, where we play signal proxy
// START SIGNAL PROXY INIT
sendInitRequest("BacklogManager", "");
List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>();
packedFunc.add(new QVariant<Integer>(RequestType.Sync.getValue(), QVariant.Type.Int));
packedFunc.add(new QVariant<String>("BufferSyncer", QVariant.Type.String));
packedFunc.add(new QVariant<String>("", QVariant.Type.String));
packedFunc.add(new QVariant<String>("requestSetLastSeenMsg", QVariant.Type.String));
packedFunc.add(new QVariant<Integer>(1, "BufferId"));
packedFunc.add(new QVariant<Integer>(1, "MsgId"));
sendQVariantList(packedFunc);
// We must do this here, to get network names early enough
for(int network: networks) {
sendInitRequest("Network", Integer.toString(network));
}
readThread = new ReadThread();
readThread.start();
TimerTask sendPingAction = new TimerTask() {
public void run() {
List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>();
packedFunc.add(new QVariant<Integer>(RequestType.HeartBeat.getValue(), QVariant.Type.Int));
packedFunc.add(new QVariant<Calendar>(Calendar.getInstance(), QVariant.Type.Time));
try {
sendQVariantList(packedFunc);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
heartbeatTimer = new Timer();
heartbeatTimer.schedule(sendPingAction, 0, 30000); // Send heartbeats every 30 seconds
// END SIGNAL PROXY
connected = true;
}
/**
* Attempts to disconnect from the core, as best as we can.
* Java sucks.
*/
public void disconnect() {
heartbeatTimer.cancel(); // Has this stopped executing now? Nobody knows.
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
readThread.running = false;
connected = false;
}
/****************************
* Private internal communication stuff.
* Please don't look below this line.
* @author sandsmark
*/
/**
* Type of a given request (should be pretty self-explanatory).
*/
private enum RequestType {
Invalid(0),
Sync(1),
RpcCall(2),
InitRequest(3),
InitData(4),
HeartBeat(5),
HeartBeatReply(6);
// Below this line; java sucks. Hard.
int value;
RequestType(int value){
this.value = value;
}
public int getValue(){
return value;
}
public static RequestType getForVal(int val) {
for (RequestType type: values()) {
if (type.value == val)
return type;
}
return Invalid;
}
}
private Socket socket;
private QDataOutputStream outStream;
private QDataInputStream inStream;
private Map<Integer, Buffer> buffers;
private Map<Integer, String> nicks;
private List<Integer> networks;
private String address;
private int port;
private String username;
private String password;
private boolean ssl;
private CoreConnService service;
private Timer heartbeatTimer;
private ReadThread readThread;
private int backlogFetchAmount = 50;
private boolean connected;
private class ReadThread extends Thread {
boolean running = false;
public void run() {
this.running = true;
List<QVariant<?>> packedFunc;
while (running) {
try {
packedFunc = readQVariantList();
} catch (IOException e) {
//TODO: not sure if this is really the best way to check if we are connected, by just waiting untill it fails, but will have to do for now
CoreConnection.this.disconnect();
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_LOST_CONNECTION);
msg.sendToTarget();
System.err.println("IO error!");
e.printStackTrace();
return;
}
long start = System.currentTimeMillis();
RequestType type = RequestType.getForVal((Integer)packedFunc.remove(0).getData());
String className = "", objectName;
/*
* Here we handle different calls from the core.
*/
switch (type) {
/*
* A heartbeat is a simple request sent with fixed intervals,
* to make sure that both ends are still connected (apparently, TCP isn't good enough).
* TODO: We should use this, and disconnect automatically when the core has gone away.
*/
case HeartBeat:
System.out.println("Got heartbeat");
break;
case HeartBeatReply:
System.out.println("Got heartbeat reply");
break;
/*
* This is when the core send us a new object to create.
* Since we don't actually create objects, we parse out the fields
* in the objects manually.
*/
case InitData:
// The class name and name of the object we are about to create
className = (String) packedFunc.remove(0).getData();
objectName = (String) packedFunc.remove(0).getData();
/*
* An object representing an IRC network, containing users and channels ("buffers").
*/
if (className.equals("Network")) {
int networkId = Integer.parseInt(objectName);
Map<String, QVariant<?>> initMap = (Map<String, QVariant<?>>) packedFunc.remove(0).getData();
// Store the network name and associated nick for "our" user
nicks.put(networkId, (String) initMap.get("myNick").getData());
for (Buffer buffer: buffers.values()) {
if (buffer.getInfo().networkId == networkId && buffer.getInfo().name.equals("")) {
buffer.getInfo().name = (String) initMap.get("networkName").getData();
break;
}
}
// Horribly nested maps
Map<String, QVariant<?>> usersAndChans = (Map<String, QVariant<?>>) initMap.get("IrcUsersAndChannels").getData();
Map<String, QVariant<?>> channels = (Map<String, QVariant<?>>) usersAndChans.get("channels").getData();
// Parse out the list of nicks in all channels, and topics
for (QVariant<?> channel: channels.values()) {
Map<String, QVariant<?>> chan = (Map<String, QVariant<?>>) channel.getData();
String chanName = (String)chan.get("name").getData();
Map<String, QVariant<?>> userModes = (Map<String, QVariant<?>>) chan.get("UserModes").getData();
List<String> users = new ArrayList<String>(userModes.keySet());
String topic = (String)chan.get("topic").getData();
// Horribly inefficient search for the right buffer, Java sucks.
Map<String, QVariant<?>> userObjs = (Map<String, QVariant<?>>) usersAndChans.get("users").getData();
ArrayList<IrcUser> ircUsers = new ArrayList<IrcUser>();
for (String nick : userObjs.keySet()) {
IrcUser user = new IrcUser();
user.name = nick;
Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) userObjs.get(nick).getData();
user.away = (Boolean) map.get("away").getData();
user.awayMessage = (String) map.get("awayMessage").getData();
user.ircOperator = (String) map.get("ircOperator").getData();
user.nick = (String) map.get("nick").getData();
user.channels = (List<String>) map.get("channels").getData();
ircUsers.add(user);
}
for (Buffer buffer: buffers.values()) {
if (buffer.getInfo().name.equals(chanName) && buffer.getInfo().networkId == networkId) {
buffer.setTopic(topic);
buffer.setNicks(users);
break;
}
}
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_NEW_USERLIST_ADDED);
msg.obj = ircUsers;
msg.sendToTarget();
}
/*
* An object that is used to synchronize metadata about buffers,
* like the last seen message, marker lines, etc.
*/
} else if (className.equals("BufferSyncer")) {
// Parse out the last seen messages
List<QVariant<?>> lastSeen = (List<QVariant<?>>) ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("LastSeenMsg").getData();
for (int i=0; i<lastSeen.size()/2; i++) {
int bufferId = (Integer)lastSeen.remove(0).getData();
int msgId = (Integer)lastSeen.remove(0).getData();
if (buffers.containsKey(bufferId)){ // We only care for buffers we have open
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_SET_LAST_SEEN_TO_SERVICE);
msg.obj = buffers.get(bufferId);
msg.arg1 = msgId;
msg.sendToTarget();
}
}
// Parse out the marker lines for buffers
List<QVariant<?>> markerLines = (List<QVariant<?>>) ((Map<String, QVariant<?>>)packedFunc.get(0).getData()).get("MarkerLines").getData();
for (int i=0; i<markerLines.size()/2; i++) {
int bufferId = (Integer)markerLines.remove(0).getData();
int msgId = (Integer)markerLines.remove(0).getData();
if (buffers.containsKey(bufferId)){
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_SET_MARKERLINE_TO_SERVICE);
msg.obj = buffers.get(bufferId);
msg.arg1 = msgId;
msg.sendToTarget();
}
}
/*
* We have now received everything we need to know about our buffers,
* and will now notify our listeners about them.
*/
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_ADD_MULTIPLE_BUFFERS);
msg.obj = buffers.values();
msg.sendToTarget();
for (int buffer: buffers.keySet()) {
// Here we might fetch backlog for all buffers, but we don't want to, because phones are slow:
requestBacklog(buffer, -1, -1, 1);
}
/*
* A class representing another user on a given IRC network.
*/
} else if (className.equals("IrcUser")) {
IrcUser user = new IrcUser();
user.name = className;
Map<String, QVariant<?>> map = (Map<String, QVariant<?>>) packedFunc.remove(0).getData();
user.away = (Boolean) map.get("away").getData();
user.awayMessage = (String) map.get("awayMessage").getData();
user.ircOperator = (String) map.get("ircOperator").getData();
user.nick = (String) map.get("nick").getData();
user.channels = (List<String>) map.get("channels").getData();
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_NEW_USER_ADDED);
msg.obj = (IrcUser) user;
msg.sendToTarget();
/*
* There are several objects that we don't care about (at the moment).
*/
} else {
System.out.println("Unparsed InitData: " + className + "(" + objectName + ").");
}
break;
/*
* Sync requests are sent by the core whenever an object needs to be updated.
* Again, we just parse out whatever we need manually
*/
case Sync:
/* See above; parse out information about object,
* and additionally a sync function name.
*/
Object foo = packedFunc.remove(0).getData();
//System.out.println("FUCK" + foo.toString() + " balle " + foo.getClass().getName());
if (foo.getClass().getName().equals("java.nio.ReadWriteHeapByteBuffer")) {
try {
System.out.println("faen i helvete: " + new String(((ByteBuffer)foo).array(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
className = (String)foo; // This is either a byte buffer or a string
objectName = (String) packedFunc.remove(0).getData();
String function = packedFunc.remove(0).toString();
/*
* The BacklogManager object is responsible for synchronizing backlog
* between the core and the client.
*
* The receiveBacklog function is called in the client with a given (requested)
* amount of messages.
*/
if (className.equals("BacklogManager") && function.equals("receiveBacklog")) {
/* Here we first just dump some unused data;
* the buffer id is embedded in the message itself (in a bufferinfo object),
* the rest of the arguments aren't used at all, apparently.
*/
packedFunc.remove(0); // Buffer ID (Integer)
packedFunc.remove(0); // first message
packedFunc.remove(0); // last message
packedFunc.remove(0); // limit to how many messages to fetch
packedFunc.remove(0); // additional messages to fetch
List<QVariant<?>> data = (List<QVariant<?>>)(packedFunc.remove(0).getData());
Collections.reverse(data); // Apparently, we receive them in the wrong order
// Send our the backlog messages to our listeners
for (QVariant<?> message: data) {
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_NEW_BACKLOGITEM_TO_SERVICE);
msg.obj = (IrcMessage) message.getData();
msg.sendToTarget();
}
/*
* The addIrcUser function in the Network class is called whenever a new
* IRC user appears on a given network.
*/
} else if (className.equals("Network") && function.equals("addIrcUser")) {
String nick = (String) packedFunc.remove(0).getData();
try {
sendInitRequest("IrcUser", "1/" + nick);
} catch (IOException e) {
e.printStackTrace();
running = false; // We have obviously lost our connection, just stop this thread.
}
/*
* markBufferAsRead is called whenever a given buffer is set as read by the core.
*/
} else if (className.equals("BufferSyncer") && function.equals("markBufferAsRead")) {
int buffer = (Integer) packedFunc.remove(0).getData();
buffers.get(buffer).setRead();
} else {
System.out.println("Unparsed Sync request: " + className + "::" + function);
}
break;
/*
* Remote procedure calls are direct calls that are not associated with any objects.
*/
case RpcCall:
// Contains a normalized function signature; see QMetaObject::normalizedSignature, I guess.
String functionName = packedFunc.remove(0).toString();
/*
* This is called by the core when a new message should be displayed.
*/
if (functionName.equals("2displayMsg(Message)")) {
IrcMessage message = (IrcMessage) packedFunc.remove(0).getData();
Message msg = service.getHandler().obtainMessage(R.id.CORECONNECTION_NEW_MESSAGE_TO_SERVICE);
msg.obj = message;
msg.sendToTarget();
} else {
System.out.println("Unhandled RpcCall: " + functionName + " (" + packedFunc + ").");
}
break;
default:
System.out.println("Unhandled request type: " + type.name());
}
long end = System.currentTimeMillis();
if (end-start > 500) {
System.err.println("Slow parsing (" + (end-start) + "ms)!: Request type: " + type.name() + " Class name:" + className);
}
}
try {
inStream.close();
} catch (IOException e) {
System.out.println("WARNING: Unable to close input stream (already closed?).");
}
}
}
/**
* Convenience function to send a given QVariant.
* @param data QVariant to send.
*/
private void sendQVariant(QVariant<?> data) throws IOException {
// See how much data we're going to send
ByteArrayOutputStream baos = new ByteArrayOutputStream();
QDataOutputStream bos = new QDataOutputStream(baos);
QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, bos, data);
// Tell the other end how much data to expect
outStream.writeUInt(bos.size(), 32);
// Sanity check, check that we can decode our own stuff before sending it off
QDataInputStream bis = new QDataInputStream(new ByteArrayInputStream(baos.toByteArray()));
QMetaTypeRegistry.instance().getTypeForId(QMetaType.Type.QVariant.getValue()).getSerializer().unserialize(bis, DataStreamVersion.Qt_4_2);
// Send data
QMetaTypeRegistry.serialize(QMetaType.Type.QVariant, outStream, data);
}
/**
* Convenience function to send a given QVariantMap.
* @param data the given QVariantMap to send.
*/
private void sendQVariantMap(Map<String, QVariant<?>> data) throws IOException {
QVariant<Map<String, QVariant<?>>> bufstruct = new QVariant<Map<String, QVariant<?>>>(data, QVariant.Type.Map);
sendQVariant(bufstruct);
}
/**
* A convenience function to send a given QVariantList.
* @param data The QVariantList to send.
*/
private void sendQVariantList(List<QVariant<?>> data) throws IOException {
QVariant<List<QVariant<?>>> bufstruct = new QVariant<List<QVariant<?>>>(data, QVariant.Type.List);
sendQVariant(bufstruct);
}
/**
* A convenience function to read a QVariantMap.
*/
private Map<String, QVariant<?>> readQVariantMap() throws IOException {
// Length of this packet (why do they send this? noone knows!).
inStream.readUInt(32);
QVariant <Map<String, QVariant<?>>> v = (QVariant <Map<String, QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream);
Map<String, QVariant<?>>ret = (Map<String, QVariant<?>>)v.getData();
return ret;
}
/**
* A convenience function to read a QVariantList.
*/
private List<QVariant<?>> readQVariantList() throws IOException {
inStream.readUInt(32); // Length
QVariant <List<QVariant<?>>> v = (QVariant <List<QVariant<?>>>)QMetaTypeRegistry.unserialize(QMetaType.Type.QVariant, inStream);
List<QVariant<?>>ret = (List<QVariant<?>>)v.getData();
return ret;
}
/**
* Convenience function to request an init of a given object.
* @param className The class name of the object we want.
* @param objectName The name of the object we want.
*/
private void sendInitRequest(String className, String objectName) throws IOException {
List<QVariant<?>> packedFunc = new LinkedList<QVariant<?>>();
packedFunc.add(new QVariant<Integer>(RequestType.InitRequest.getValue(), QVariant.Type.Int));
packedFunc.add(new QVariant<String>(className, QVariant.Type.String));
packedFunc.add(new QVariant<String>(objectName, QVariant.Type.String));
sendQVariantList(packedFunc);
}
/**
* A custom trust manager for the SSL socket so we can
* let the user manually verify certificates.
* @author sandsmark
*/
private class CustomTrustManager implements javax.net.ssl.X509TrustManager {
/*
* The default X509TrustManager returned by SunX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509TrustManager doesn't trust it.
*/
X509TrustManager defaultTrustManager;
CustomTrustManager() throws GeneralSecurityException {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager tms [] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look
* for an instance of X509TrustManager. If found,
* use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tms[i];
return;
}
}
throw new GeneralSecurityException("Couldn't initialize certificate management!");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
}
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/* Here we either check the certificate against the last stored one,
* or throw a security exception to let the user know that something is wrong.
*/
String hashedCert = hash(chain[0].getEncoded());
SharedPreferences preferences = CoreConnection.this.service.getSharedPreferences("CertificateStorage", Context.MODE_PRIVATE);
if (preferences.contains("certificate")) {
if (!preferences.getString("certificate", "lol").equals(hashedCert)) {
throw new CertificateException();
}
// We haven't seen a certificate from this core before, just store it
// TODO: let the user decide whether to trust it or not.
} else {
System.out.println("Storing new certificate: " + hashedCert);
preferences.edit().putString("certificate", hashedCert).commit();
}
}
}
/**
* Java sucks.
* @param s The bytes to hash
* @return a hash representing the input bytes.
*/
private String hash(byte[] s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA1");
digest.update(s);
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return defaultTrustManager.getAcceptedIssuers();
}
}
}
|
package com.systematic.trading.backtest;
import java.io.IOException;
import java.math.MathContext;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.systematic.trading.backtest.configuration.BacktestBootstrapConfiguration;
import com.systematic.trading.backtest.configuration.deposit.DepositConfiguration;
import com.systematic.trading.backtest.configuration.equity.EquityConfiguration;
import com.systematic.trading.backtest.configuration.signals.MacdConfiguration;
import com.systematic.trading.backtest.configuration.signals.RsiConfiguration;
import com.systematic.trading.backtest.configuration.signals.SmaConfiguration;
import com.systematic.trading.backtest.display.BacktestDisplay;
import com.systematic.trading.backtest.display.DescriptionGenerator;
import com.systematic.trading.backtest.display.file.FileClearDestination;
import com.systematic.trading.backtest.display.file.FileCompleteDisplay;
import com.systematic.trading.backtest.display.file.FileMinimalDisplay;
import com.systematic.trading.backtest.display.file.FileNoDisplay;
import com.systematic.trading.backtest.exception.BacktestInitialisationException;
import com.systematic.trading.backtest.model.BacktestSimulationDates;
import com.systematic.trading.backtest.model.TickerSymbolTradingDataBacktest;
import com.systematic.trading.data.DataService;
import com.systematic.trading.data.DataServiceUpdater;
import com.systematic.trading.data.DataServiceUpdaterImpl;
import com.systematic.trading.data.HibernateDataService;
import com.systematic.trading.data.TradingDayPrices;
import com.systematic.trading.data.util.HibernateUtil;
import com.systematic.trading.exception.ServiceException;
import com.systematic.trading.model.EquityIdentity;
import com.systematic.trading.model.TickerSymbolTradingData;
/**
* Performs the initial configuration common between all back tests, including hardware configuration.
*
* @author CJ Hare
*/
public class BacktestApplication {
/** Classes logger. */
private static final Logger LOG = LogManager.getLogger(BacktestApplication.class);
/** Minimum amount of historical data needed for back testing. */
private static final int DAYS_IN_A_YEAR = 365;
private static final int HISTORY_REQUIRED = 10 * DAYS_IN_A_YEAR;
private enum DisplayType {
FILE_FULL,
FILE_MINIMUM,
NO_DISPLAY;
}
private final MathContext mathContext;
public BacktestApplication(final MathContext mathContext) {
this.mathContext = mathContext;
}
public void runTest( final BacktestConfigurations configurations, final String... args )
throws ServiceException, BacktestInitialisationException, InterruptedException {
final String baseOutputDirectory = getBaseOutputDirectory(args);
final DescriptionGenerator filenameGenerator = new DescriptionGenerator();
// Date range is from the first of the starting month until now
final LocalDate simulationEndDate = LocalDate.now();
final LocalDate simulationStartDate = simulationEndDate.minus(HISTORY_REQUIRED, ChronoUnit.DAYS)
.withDayOfMonth(1);
// Only for the single equity
final EquityIdentity equity = EquityConfiguration.SP_500_PRICE_INDEX.getEquityIdentity();
// Move the date to included the necessary wind up time for the signals to behave correctly
final Period warmUpPeriod = getWarmUpPeriod();
final BacktestSimulationDates simulationDates = new BacktestSimulationDates(simulationStartDate,
simulationEndDate, warmUpPeriod);
// Retrieve the set of trading data
final TickerSymbolTradingData tradingData = getTradingData(equity, simulationDates);
// Multi-threading support
final int cores = Runtime.getRuntime().availableProcessors();
final ExecutorService pool = Executors.newFixedThreadPool(cores);
final DisplayType outputType = DisplayType.FILE_MINIMUM;
// TODO run the test over the full period with exclusion on filters
// TODO no deposits until actual start date
try {
for (final DepositConfiguration depositAmount : DepositConfiguration.values()) {
final List<BacktestBootstrapConfiguration> tests = configurations.get(equity, simulationDates,
depositAmount, filenameGenerator);
final String outputDirectory = String.format(baseOutputDirectory, depositAmount);
runTest(depositAmount, outputDirectory, tests, tradingData, equity, outputType, pool);
}
} finally {
HibernateUtil.getSessionFactory().close();
pool.shutdown();
LOG.info("Waiting at most 90 minutes for result output to complete...");
pool.awaitTermination(90, TimeUnit.MINUTES);
}
LOG.info("Finished outputting results");
}
private static Period getWarmUpPeriod() {
int windUp = 0;
for (final MacdConfiguration macdConfiguration : MacdConfiguration.values()) {
if (macdConfiguration.getSlowTimePeriods() > windUp)
windUp = macdConfiguration.getSlowTimePeriods();
}
for (final RsiConfiguration rsiConfiguration : RsiConfiguration.values()) {
if (rsiConfiguration.getLookback() > windUp) {
windUp = rsiConfiguration.getLookback();
}
}
for (final SmaConfiguration smaConfiguration : SmaConfiguration.values()) {
if (smaConfiguration.getLookback() + smaConfiguration.getDaysOfGradient() > windUp) {
windUp = smaConfiguration.getLookback() + smaConfiguration.getDaysOfGradient();
}
}
return Period.ofDays(windUp);
}
private BacktestDisplay getDisplay( final DisplayType type, final String outputDirectory,
final ExecutorService pool ) throws BacktestInitialisationException {
try {
switch (type) {
case FILE_FULL:
return new FileCompleteDisplay(outputDirectory, pool, mathContext);
case FILE_MINIMUM:
return new FileMinimalDisplay(outputDirectory, pool, mathContext);
case NO_DISPLAY:
return new FileNoDisplay();
default:
throw new IllegalArgumentException(String.format("Display Type not catered for: %s", type));
}
} catch (final IOException e) {
throw new BacktestInitialisationException(e);
}
}
private void runTest( final DepositConfiguration depositAmount, final String baseOutputDirectory,
final List<BacktestBootstrapConfiguration> configurations, final TickerSymbolTradingData tradingData,
final EquityIdentity equity, final DisplayType type, final ExecutorService pool )
throws BacktestInitialisationException {
// Arrange output to files, only once per a run
FileClearDestination destination = new FileClearDestination(baseOutputDirectory);
destination.clear();
for (final BacktestBootstrapConfiguration configuration : configurations) {
final String outputDirectory = getOutputDirectory(baseOutputDirectory, equity, configuration);
final BacktestDisplay fileDisplay = getDisplay(type, outputDirectory, pool);
final BacktestBootstrap bootstrap = new BacktestBootstrap(tradingData, configuration, fileDisplay,
mathContext);
LOG.info(String.format("Backtesting beginning for: %s", configuration.getDescription()));
bootstrap.run();
LOG.info(String.format("Backtesting complete for: %s", configuration.getDescription()));
}
LOG.info(String.format("All Simulations have been completed for deposit amount: %s", depositAmount));
}
private TickerSymbolTradingData getTradingData( final EquityIdentity equity,
final BacktestSimulationDates simulationDate ) throws ServiceException {
final LocalDate startDate = simulationDate.getSimulationStartDate().minus(simulationDate.getWarmUp());
final LocalDate endDate = simulationDate.getSimulationEndDate();
// Retrieve and cache data range from remote data source
final DataServiceUpdater updateService = DataServiceUpdaterImpl.getInstance();
updateService.get(equity.getTickerSymbol(), startDate, endDate);
// Retrieve from local cache the desired data range
final DataService service = HibernateDataService.getInstance();
final TradingDayPrices[] data = service.get(equity.getTickerSymbol(), startDate, endDate);
return new TickerSymbolTradingDataBacktest(equity, data);
}
private String getOutputDirectory( final String baseOutputDirectory, final EquityIdentity equity,
final BacktestBootstrapConfiguration configuration ) {
return String.format("%s%s_%s", baseOutputDirectory, equity.getTickerSymbol(), configuration.getDescription());
}
private String getBaseOutputDirectory( final String... args ) {
if (args != null && args.length > 0) {
return args[0] + "/%s/";
}
return "../../simulations/%s/";
}
}
|
package nl.mpi.kinnate.svg;
import org.w3c.dom.Element;
public class GraphicsDragHandle extends RelationDragHandle {
// protected UniqueIdentifier graphicsIdentifier;
protected Element graphicsElement;
protected Element highlightElement;
protected Element highlightRectElement;
private String xAttribute;
private String yAttribute;
private boolean isCenteredElement = false;
public GraphicsDragHandle(Element graphicsElement, Element highlightElement, Element highlightRectElement, float elementStartX, float elementStartY, float mouseStartX, float mouseStartY, double diagramScaleFactor) {
super(null, null, elementStartX, elementStartY, mouseStartX, mouseStartY, diagramScaleFactor);
this.graphicsElement = graphicsElement;
this.highlightElement = highlightElement;
this.highlightRectElement = highlightRectElement;
String elementType = graphicsElement.getTagName();
if (elementType.equals("circle")) {
isCenteredElement = true;
xAttribute = "r";
yAttribute = null;
} else if (elementType.equals("rect")) {
xAttribute = "width";
yAttribute = "height";
} else if (elementType.equals("ellipse")) {
isCenteredElement = true;
xAttribute = "rx";
yAttribute = "ry";
}
}
protected void updatedElement(float localDragNodeX, float localDragNodeY, int paddingDistance) {
// this must be only called from within a svg runnable
float dragNodeX = getTranslatedX(localDragNodeX);
float dragNodeY = getTranslatedY(localDragNodeY);
int minSize = 3;
if (dragNodeX < paddingDistance + minSize) {
dragNodeX = paddingDistance + minSize;
}
if (dragNodeY < paddingDistance + minSize) {
dragNodeY = paddingDistance + minSize;
}
graphicsElement.setAttribute(xAttribute, Float.toString(dragNodeX - paddingDistance));
if (yAttribute != null) {
graphicsElement.setAttribute(yAttribute, Float.toString(dragNodeY - paddingDistance));
} else {
dragNodeY = dragNodeX;
}
if (isCenteredElement) {
highlightRectElement.setAttribute("x", Float.toString(-(dragNodeX)));
highlightRectElement.setAttribute("y", Float.toString(-(dragNodeY)));
highlightRectElement.setAttribute("width", Float.toString(dragNodeX * 2) + paddingDistance);
highlightRectElement.setAttribute("height", Float.toString(dragNodeY * 2) + paddingDistance);
} else {
highlightRectElement.setAttribute("width", Float.toString((dragNodeX + paddingDistance)));
highlightRectElement.setAttribute("height", Float.toString((dragNodeY + paddingDistance)));
}
highlightElement.setAttribute("cx", Float.toString(dragNodeX));
highlightElement.setAttribute("cy", Float.toString(dragNodeY));
}
}
|
package org.jasig.portal.i18n;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import org.jasig.portal.PropertiesManager;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.CommonUtils;
import org.jasig.portal.utils.DocumentFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Manages locales on behalf of a user.
* This class currently keeps track of locales at the following levels:<br>
* <ol>
* <li>User's locale preferences (associated with a user ID)</li>
* <li>Browser's locale preferences (from the Accept-Language request header)</li>
* <li>Session's locale preferences (set via the portal request parameter uP_locales)</li>
* <li>Portal's locale preferences (set in portal.properties)</li>
* </ol>
* Eventually, this class will also keep track of locale preferences at
* the following levels:<br>
* <ol>
* <li>Layout node's locale preferences</li>
* <li>User profile's locale preferences</li>
* </ol>
* @author Shoji Kajita <a href="mailto:">kajita@itc.nagoya-u.ac.jp</a>
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class LocaleManager {
private IPerson person;
private static boolean localeAware = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.i18n.LocaleManager.locale_aware");
private static Locale jvmLocale;
private static Locale[] portalLocales;
private Locale[] sessionLocales;
private Locale[] browserLocales;
private Locale[] userLocales;
/**
* Constructor that associates a locale manager with a user.
* @param person the user
*/
public LocaleManager(IPerson person) {
this.person = person;
if (localeAware) {
jvmLocale = Locale.getDefault();
portalLocales = loadPortalLocales();
try {
userLocales = LocaleStoreFactory.getLocaleStoreImpl().getUserLocales(person);
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
}
}
}
/**
* Constructor that sets up locales according to
* the <code>Accept-Language</code> request header
* from a user's browser.
* @param person the user
* @param acceptLanguage the Accept-Language request header from a user's browser
*/
public LocaleManager(IPerson person, String acceptLanguage) {
this(person);
this.browserLocales = parseLocales(acceptLanguage);
}
// Getters
public boolean isLocaleAware() { return localeAware; }
public static Locale getJvmLocale() { return jvmLocale; }
public static Locale[] getPortalLocales() { return portalLocales; }
public Locale[] getBrowserLocales() { return browserLocales; }
public Locale[] getUserLocales() { return userLocales; }
public Locale[] getSessionLocales() { return sessionLocales; }
// Setters
public static void setJvmLocale(Locale jvmLocale) { LocaleManager.jvmLocale = jvmLocale; }
public static void setPortalLocales(Locale[] portalLocales) { LocaleManager.portalLocales = portalLocales; }
public void setBrowserLocales(Locale[] browserLocales) { this.browserLocales = browserLocales; }
public void setUserLocales(Locale[] userLocales) { this.userLocales = userLocales; }
public void setSessionLocales(Locale[] sessionLocales) { this.sessionLocales = sessionLocales; }
/**
* Read and parse portal_locales from portal.properties.
* portal_locales will be in the form of a comma-separated
* list, e.g. en_US,ja_JP,sv_SE
*/
private Locale[] loadPortalLocales() {
String portalLocalesString = PropertiesManager.getProperty("org.jasig.portal.i18n.LocaleManager.portal_locales");
return parseLocales(portalLocalesString);
}
/**
* Produces a sorted list of locales according to locale preferences
* obtained from several places. The following priority is given:
* session, user, browser, portal, and jvm.
* @return the sorted list of locales
*/
public Locale[] getLocales() {
// Need logic to construct ordered locale list.
// Consider creating a separate ILocaleResolver
// interface to do this work.
List locales = new ArrayList();
// Add highest priority locales first
addToLocaleList(locales, sessionLocales);
addToLocaleList(locales, userLocales);
// We will ignore browser locales until we know how to
// translate them into proper java.util.Locales
//addToLocaleList(locales, browserLocales);
addToLocaleList(locales, portalLocales);
addToLocaleList(locales, new Locale[] { jvmLocale });
return (Locale[])locales.toArray(new Locale[0]);
}
/**
* Add locales to the locale list if they aren't in there already
*/
private void addToLocaleList(List localeList, Locale[] locales) {
if (locales != null) {
for (int i = 0; i < locales.length; i++) {
if (!localeList.contains(locales[i]))
localeList.add(locales[i]);
}
}
}
/**
* Helper method to produce a <code>java.util.Locale</code> array from
* a comma-delimited locale string list, e.g. "en_US,ja_JP"
* @param localeStringList the locales to parse
* @return an array of locales representing the locale string list
*/
public static Locale[] parseLocales(String localeStringList) {
Locale[] locales = null;
if (localeStringList != null) {
StringTokenizer st = new StringTokenizer(localeStringList, ",");
locales = new Locale[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++) {
String localeString = st.nextToken().trim();
locales[i] = parseLocale(localeString);
}
}
return locales;
}
/**
* Helper method to produce a <code>java.util.Locale</code> object from
* a locale string such as en_US or ja_JP.
* @param localeString a locale string such as en_US
* @return a java.util.Locale object representing the locale string
*/
public static Locale parseLocale(String localeString) {
String language = null;
String country = null;
String variant = null;
// Sometimes people specify "en-US" instead of "en_US", so
// we'll try to clean that up.
localeString = CommonUtils.replaceText(localeString, "-", "_");
StringTokenizer st = new StringTokenizer(localeString, "_");
if (st.hasMoreTokens()) {
language = st.nextToken();
}
if (st.hasMoreTokens()) {
country = st.nextToken();
}
if (st.hasMoreTokens()) {
variant = st.nextToken();
}
Locale locale = null;
if (variant != null) {
locale = new Locale(language, country, variant);
} else if (country != null) {
locale = new Locale(language, country);
} else if (language != null) {
// Uncomment the following line
// when we can count on JDK 1.4!
//locale = new Locale(language);
locale = new Locale(language, "");
}
return locale;
}
/**
* Constructs a comma-delimited list of locales
* that could be parsed back into a Locale
* array with parseLocales(String localeStringList).
* @param locales the list of locales
* @return a string representing the list of locales
*/
public static String stringValueOf(Locale[] locales) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < locales.length; i++) {
Locale locale = locales[i];
sb.append(locale.toString());
if (i < locales.length - 1) {
sb.append(",");
}
}
return sb.toString();
}
/**
* Stores the user locales persistantly.
* @param userLocales the user locales preference
* @throws Exception
*/
public void persistUserLocales(Locale[] userLocales) throws Exception {
setUserLocales(userLocales);
LocaleStoreFactory.getLocaleStoreImpl().updateUserLocales(person, userLocales);
}
/**
* Creates an XML representation of a list of locales.
* @param locales the locale list
* @return the locale list as XML
*/
public static Document xmlValueOf(Locale[] locales) {
return xmlValueOf(locales, null);
}
/**
* Creates an XML representation of a list of locales.
* If a selected locale is supplied, the XML element representing
* the selected locale will have an attribute of selected with value
* of true. This is helpful when constructing user interfaces that
* indicate which locale is selected.
* @param locales the locale list
* @param selectedLocale a locale that should be selected if it is in the list
* @return the locale list as XML
*/
public static Document xmlValueOf(Locale[] locales, Locale selectedLocale) {
Document doc = DocumentFactory.getNewDocument();
// <locales>
Element localesE = doc.createElement("locales");
for (int i = 0; i < locales.length; i++) {
Element locE = doc.createElement("locale");
locE.setAttribute("displayName", locales[i].getDisplayName(locales[0]));
locE.setAttribute("code", locales[i].toString());
// Mark which locale is the user's preference
if (selectedLocale != null && selectedLocale.equals(locales[i])) {
locE.setAttribute("selected", "true");
}
// <language iso2="..." iso3="..." displayName="..."/>
Element languageE = doc.createElement("language");
languageE.setAttribute("iso2", locales[i].getLanguage());
try {
languageE.setAttribute("iso3", locales[i].getISO3Language());
} catch (Exception e) {
// Do nothing
}
languageE.setAttribute("displayName", locales[i].getDisplayLanguage(locales[0]));
locE.appendChild(languageE);
// <country iso2="..." iso3="..." displayName="..."/>
Element countryE = doc.createElement("country");
countryE.setAttribute("iso2", locales[i].getCountry());
try {
countryE.setAttribute("iso3", locales[i].getISO3Country());
} catch (Exception e) {
// Do nothing
}
countryE.setAttribute("displayName", locales[i].getDisplayCountry(locales[0]));
locE.appendChild(countryE);
// <variant code="..." displayName="..."/>
Element variantE = doc.createElement("variant");
variantE.setAttribute("code", locales[i].getVariant());
variantE.setAttribute("displayName", locales[i].getDisplayVariant(locales[0]));
locE.appendChild(variantE);
localesE.appendChild(locE);
}
doc.appendChild(localesE);
return doc;
}
public String toString() {
StringBuffer sb = new StringBuffer(1024);
sb.append("LocaleManager's locales").append("\n");
sb.append("
sb.append("Session locales: ");
if (sessionLocales != null) {
sb.append(stringValueOf(sessionLocales));
}
sb.append("\n");
sb.append("User locales: ");
if (userLocales != null) {
sb.append(stringValueOf(userLocales));
}
sb.append("\n");
sb.append("Browser locales: ");
if (browserLocales != null) {
sb.append(stringValueOf(browserLocales));
}
sb.append("\n");
sb.append("Portal locales: ");
if (portalLocales != null) {
sb.append(stringValueOf(portalLocales));
}
sb.append("\n");
sb.append("JVM locale: ");
if (jvmLocale != null) {
sb.append(jvmLocale.toString());
}
sb.append("\n");
sb.append("Sorted locales: ");
Locale[] sortedLocales = getLocales();
if (sortedLocales != null) {
sb.append(stringValueOf(sortedLocales));
}
sb.append("\n");
return sb.toString();
}
}
|
package com.moeyinc.formulamorph;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.concurrent.LinkedBlockingDeque;
import javax.swing.SwingUtilities;
public class PhidgetInterface implements Parameter.ActivationStateListener
{
String host;
int port;
Socket socket;
LinkedBlockingDeque< String > outDeque = new LinkedBlockingDeque< String >();
PhidgetReaderClient phidgetReaderClient;
PhidgetWriterClient phidgetWriterClient;
private boolean shutdown = false;
static int heartbeat_ms = 1000;
public PhidgetInterface( String host, int port )
{
this.host = host;
this.port = port;
this.socket = new Socket();
try { reconnect(); } catch( IOException ioe ) { /* do nothing since PhidgetWriter will try to reconnect broken connections anyway */ }
phidgetReaderClient = new PhidgetReaderClient();
phidgetWriterClient = new PhidgetWriterClient();
for( Parameter p : Parameter.values() )
p.addActivationStateListener( this );
new Thread( new HeartBeat(), "PhidgetHeartBeat" ).start();
new Thread( phidgetReaderClient, "PhidgetReaderClient" ).start();
new Thread( phidgetWriterClient, "PhidgetWriterClient" ).start();
}
private synchronized void reconnect()
throws IOException, UnknownHostException
{
if( ! shutdown )
{
try
{
socket.close();
socket = new Socket( host, port );
socket.setKeepAlive( true );
socket.setSoTimeout( heartbeat_ms * 5 );
if( !socket.isConnected() || socket.isClosed() )
throw new IOException( "PhidgetInterface: no connection to " + host + ":" + port );
}
catch( IOException e )
{
// block for 1s to avoid calling this method
try { Thread.sleep( 1000 ); } catch( InterruptedException ie ) {}
throw e;
}
}
}
public void shutdown() throws IOException
{
shutdown = true;
try { socket.close(); } catch( IOException ioe ) {}
}
public void stateChanged( Parameter p )
{
setLEDEnabled( p, p.isActive() );
}
public void setLEDEnabled( Parameter p, boolean enabled )
{
int LED_id = -1;
switch( p )
{
case F_a: LED_id = 1; break;
case F_b: LED_id = 2; break;
case F_c: LED_id = 3; break;
case F_d: LED_id = 4; break;
case F_e: LED_id = 5; break;
case F_f: LED_id = 6; break;
case M_t: return; // do nothing
case G_a: LED_id = 7; break;
case G_b: LED_id = 8; break;
case G_c: LED_id = 9; break;
case G_d: LED_id = 10; break;
case G_e: LED_id = 11; break;
case G_f: LED_id = 12; break;
}
String cmd = "LD," + LED_id + "," + ( enabled ? '1' : '0' );
boolean done = false;
do
{
try
{
outDeque.put( cmd );
done = true;
}
catch( Exception e )
{
// retry
}
}
while( !done );
}
class PhidgetReaderClient implements Runnable
{
public void run()
{
//final Integer[] easterEggSequence_tmp = { 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1 }; // alternating Fibonacci sequence code (1, -1, 2, -3, 5, -8)
Integer[] easterEggSequence_tmp = { 1, -1, 1, 1, -1, -1, -1 }; // alternating Fibonacci sequence code (1, -1, 2, -3)
List< Integer > easterEggSequencePos = new ArrayList< Integer >( Arrays.asList( easterEggSequence_tmp ) );
// second sequence is the negative version of the first one
for( int i = 0; i < easterEggSequence_tmp.length; ++i )
easterEggSequence_tmp[ i ] = -easterEggSequence_tmp[ i ];
List< Integer > easterEggSequenceNeg = new ArrayList< Integer >( Arrays.asList( easterEggSequence_tmp ) );
final EnumMap< Surface, LinkedList< Integer > > currentEasterEggSequences = new EnumMap< Surface, LinkedList< Integer > >( Surface.class );
currentEasterEggSequences.put( Surface.F, new LinkedList< Integer >( Arrays.asList( easterEggSequence_tmp ) ) );
currentEasterEggSequences.put( Surface.G, new LinkedList< Integer >( Arrays.asList( easterEggSequence_tmp ) ) );
// receive input
while( !PhidgetInterface.this.shutdown )
{
try
{
BufferedReader in = new BufferedReader( new InputStreamReader( PhidgetInterface.this.socket.getInputStream() ) );
String cmd;
boolean[] digital_switch = { false, false, false }; // element 0 is invalid
while( ( cmd = in.readLine() ) != null )
{
cmd = cmd.replaceAll( "#.*$", "" ); // strip comments (everything from # to the end of the command)
cmd = cmd.replaceAll( "\\s", "" ); // strip whitespace
if( cmd.isEmpty() )
continue; // heart beat
boolean unknown_command = false;
try
{
String[] parts = cmd.split(",");
String dev = parts[ 0 ];
final int id = Integer.parseInt( parts[ 1 ] );
String[] values = Arrays.copyOfRange( parts, 2, parts.length );
if( dev.equals( "FS" ) )
{ // formula selector
if( id == 1 || id == 2 )
{
final int offset = Integer.parseInt( values[ 0 ] );
final Surface surface = id == 1 ? Surface.F : Surface.G;
// insert offset into easter egg sequence
for( int i = 0; i < Math.abs( offset ); ++i )
{
currentEasterEggSequences.get( surface ).poll();
currentEasterEggSequences.get( surface ).offer( offset > 0 ? +1 : -1 );
System.out.println(currentEasterEggSequences.toString());
}
// test if easter egg sequences is complete
if( currentEasterEggSequences.get( surface ).equals( easterEggSequencePos ) || currentEasterEggSequences.get( surface ).equals( easterEggSequenceNeg ) )
{
// launch easter egg
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
Main.gui().selectEasterEggSurface( surface );
}
} );
}
else
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
Main.gui().nextSurface( surface, offset );
}
} );
}
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "RE" ) )
{ // rotary encoder
final int relative_angle = Integer.parseInt( values[ 0 ] );
if( id > 0 && id <= 12 )
{
final Parameter[] params = {
Parameter.F_a, Parameter.F_b, Parameter.F_c, Parameter.F_d, Parameter.F_e, Parameter.F_f,
Parameter.G_a, Parameter.G_b, Parameter.G_c, Parameter.G_d, Parameter.G_e, Parameter.G_f };
final Parameter param = params[ id - 1 ];
if( param.isActive() )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
param.setValue( param.getValue() + ( relative_angle / param.getSpeed() ) * param.getRange() );
}
} );
}
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "JW" ) )
{ // jog wheel
final int relative_angle = Integer.parseInt( values[ 0 ] );
if( id > 0 && id <= 1 )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
Main.gui().stepPath( relative_angle );
}
} );
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "JS" ) )
{ // joystick
if( id == 1 )
{
final double js_value = Double.parseDouble( values[ 0 ] );
SwingUtilities.invokeLater( new Runnable() { public void run() { Parameter.M_t.setValue( js_value ); } } );
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "SW" ) )
{ // digital switch
if( id == 1 || id == 2 )
{
boolean on = Integer.parseInt( values[ 0 ] ) == 1;
if( !digital_switch[ id ] && on )
{ // was off, now is on
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
if( id == 1 )
Main.gui().saveScreenShotLeft();
else if( id == 2 )
Main.gui().saveScreenShotRight();
}
} );
}
digital_switch[ id ] = on;
}
else
{
unknown_command = true;
}
}
else
{
unknown_command = true;
}
}
catch( ArrayIndexOutOfBoundsException aioobe ) { unknown_command = true; }
catch( NullPointerException npe ) { unknown_command = true; }
catch( NumberFormatException nfe ) { unknown_command = true; }
if( unknown_command )
;//System.err.println( "PhidgetReader: Unknown command \"" + cmd + "\"" );
else
Main.robot().holdBack();
}
}
catch( IOException ioe )
{
System.err.println( "PhidgetReader: no I/O connection to " + PhidgetInterface.this.host + ":" + PhidgetInterface.this.port );
try { Thread.sleep( 1000 ); } catch( InterruptedException ie ) {}
}
}
}
}
class PhidgetWriterClient implements Runnable
{
public void run()
{
boolean reconnect = false;
while( !PhidgetInterface.this.shutdown )
{
try
{
if( !PhidgetInterface.this.socket.isConnected() || PhidgetInterface.this.socket.isClosed() || reconnect )
{
PhidgetInterface.this.reconnect();
reconnect = false;
}
OutputStreamWriter out = new OutputStreamWriter( PhidgetInterface.this.socket.getOutputStream() );
String cmd = null;
while( true )
{
try
{
if( cmd == null )
cmd = outDeque.take();
try
{
out.write( cmd );
out.write( "#FM\n" );
out.flush();
cmd = null;
}
catch( IOException ioe )
{
// put cmd back into queue and retry
outDeque.putFirst( cmd );
throw ioe;
}
}
catch( InterruptedException ie )
{
// retry
}
}
}
catch( IOException ioe )
{
System.err.println( "PhidgetWriter: no I/O connection to " + PhidgetInterface.this.host + ":" + PhidgetInterface.this.port );
reconnect = true;
}
}
}
}
class HeartBeat implements Runnable
{
public void run()
{
while( !PhidgetInterface.this.shutdown )
{
try
{
Thread.sleep( heartbeat_ms );
if( outDeque.size() < 10 ) // don't send anything if there is still something in the buffer
outDeque.put( "" ); // use empty command as heart beat
}
catch( Exception ie )
{
// just repeat
}
}
}
}
}
|
package com.tinkerpop.gremlin.tinkergraph.structure;
import com.tinkerpop.gremlin.AbstractGremlinTest;
import com.tinkerpop.gremlin.process.T;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.graph.GraphTraversal;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Operator;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.io.GraphReader;
import com.tinkerpop.gremlin.structure.io.graphml.GraphMLWriter;
import com.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
import com.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
import com.tinkerpop.gremlin.structure.io.kryo.KryoReader;
import com.tinkerpop.gremlin.structure.io.kryo.KryoWriter;
import com.tinkerpop.gremlin.structure.strategy.PartitionStrategy;
import com.tinkerpop.gremlin.util.StreamFactory;
import org.apache.commons.io.FileUtils;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import static com.tinkerpop.gremlin.process.graph.AnonymousGraphTraversal.Tokens.__;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TinkerGraphTest {
private static String tempPath;
static {
final String temp = System.getProperty("java.io.tmpdir", File.separator + "tmp").trim();
if (!temp.endsWith(File.separator))
tempPath = temp + File.separator;
else
tempPath = temp;
tempPath = tempPath + "tinkerpop-io/";
}
@BeforeClass
public static void before() throws IOException {
final File tempDir = new File(tempPath);
FileUtils.deleteDirectory(tempDir);
if (!tempDir.mkdirs()) throw new IOException(String.format("Could not create %s", tempDir));
}
@Test
@Ignore
public void testPlay() {
Graph g = TinkerGraph.open();
Vertex v1 = g.addVertex(T.id, "1", "animal", "males");
Vertex v2 = g.addVertex(T.id, "2", "animal", "puppy");
Vertex v3 = g.addVertex(T.id, "3", "animal", "mama");
Vertex v4 = g.addVertex(T.id, "4", "animal", "puppy");
Vertex v5 = g.addVertex(T.id, "5", "animal", "chelsea");
Vertex v6 = g.addVertex(T.id, "6", "animal", "low");
Vertex v7 = g.addVertex(T.id, "7", "animal", "mama");
Vertex v8 = g.addVertex(T.id, "8", "animal", "puppy");
Vertex v9 = g.addVertex(T.id, "9", "animal", "chula");
v1.addEdge("link", v2, "weight", 2f);
v2.addEdge("link", v3, "weight", 3f);
v2.addEdge("link", v4, "weight", 4f);
v2.addEdge("link", v5, "weight", 5f);
v3.addEdge("link", v6, "weight", 1f);
v4.addEdge("link", v6, "weight", 2f);
v5.addEdge("link", v6, "weight", 3f);
v6.addEdge("link", v7, "weight", 2f);
v6.addEdge("link", v8, "weight", 3f);
v7.addEdge("link", v9, "weight", 1f);
v8.addEdge("link", v9, "weight", 7f);
v1.withSack(() -> Float.MIN_VALUE).repeat(__.outE().sack(Operator.max, "weight").inV()).times(5).sack().submit(g.compute()).forEachRemaining(System.out::println);
}
@Test
public void testTraversalDSL() throws Exception {
Graph g = TinkerFactory.createClassic();
assertEquals(2, g.of(TinkerFactory.SocialTraversal.class).people("marko").knows().name().toList().size());
g.of(TinkerFactory.SocialTraversal.class).people("marko").knows().name().forEachRemaining(name -> assertTrue(name.equals("josh") || name.equals("vadas")));
assertEquals(1, g.of(TinkerFactory.SocialTraversal.class).people("marko").created().name().toList().size());
g.of(TinkerFactory.SocialTraversal.class).people("marko").created().name().forEachRemaining(name -> assertEquals("lop", name));
}
@Test
@Ignore
public void benchmarkStandardTraversals() throws Exception {
Graph g = TinkerGraph.open();
g.io().readGraphML("/Users/marko/software/tinkerpop/tinkerpop3/data/grateful-dead.xml");
final List<Supplier<Traversal>> traversals = Arrays.asList(
() -> g.V().outE().inV().outE().inV().outE().inV(),
() -> g.V().out().out().out(),
() -> g.V().out().out().out().path(),
() -> g.V().repeat(__.out()).times(2),
() -> g.V().repeat(__.out()).times(3),
() -> g.V().map(v -> v.get().out().out().values("name").toList()),
() -> g.V().out().map(v -> v.get().out().out().values("name").toList())
);
traversals.forEach(traversal -> {
System.out.println("\nTESTING: " + traversal.get());
for (int i = 0; i < 7; i++) {
final long t = System.currentTimeMillis();
traversal.get().iterate();
System.out.print(" " + (System.currentTimeMillis() - t));
}
});
}
@Test
@Ignore
public void testPlay3() throws Exception {
Graph g = TinkerFactory.createModern();
g = g.strategy(PartitionStrategy.build().partitionKey("name").create());
GraphTraversal t = g.V().out();
System.out.println(t.toString());
t.iterate();
System.out.println(t.toString());
}
@Test
@Ignore
public void testPlay4() throws Exception {
Graph g = TinkerFactory.createModern();
Traversal t = g.V().choose(v -> v.label().equals("person"),
__.union(__.out().<String>values("lang"), __.out().<String>values("name")),
__.in().label()).groupCount();
t.submit(g.compute()).forEachRemaining(System.out::println);
System.out.println(t);
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicGraphAsKryo() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic.gio");
KryoWriter.build().create().writeGraph(os, TinkerFactory.createClassic());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernGraphAsKryo() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern.gio");
KryoWriter.build().create().writeGraph(os, TinkerFactory.createModern());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteCrewGraphAsKryo() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-crew.gio");
KryoWriter.build().create().writeGraph(os, TinkerFactory.createTheCrew());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicVerticesAsKryo() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic-vertices.gio");
KryoWriter.build().create().writeVertices(os, TinkerFactory.createClassic().V(), Direction.BOTH);
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicVerticesAsGraphSON() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic-vertices.ldjson");
GraphSONWriter.build().create().writeVertices(os, TinkerFactory.createClassic().V(), Direction.BOTH);
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernVerticesAsKryo() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern-vertices.gio");
KryoWriter.build().create().writeVertices(os, TinkerFactory.createModern().V(), Direction.BOTH);
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernVerticesAsGraphSON() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern-vertices.ldjson");
GraphSONWriter.build().create().writeVertices(os, TinkerFactory.createModern().V(), Direction.BOTH);
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteCrewVerticesAsKryo() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-crew-vertices.gio");
KryoWriter.build().create().writeVertices(os, TinkerFactory.createTheCrew().V(), Direction.BOTH);
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicGraphAsGraphML() throws IOException {
try (final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic.xml")) {
GraphMLWriter.build().create().writeGraph(os, TinkerFactory.createClassic());
}
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernGraphAsGraphML() throws IOException {
try (final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern.xml")) {
GraphMLWriter.build().create().writeGraph(os, TinkerFactory.createModern());
}
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicGraphAsGraphSONNoTypes() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic.json");
GraphSONWriter.build().create().writeGraph(os, TinkerFactory.createClassic());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernGraphAsGraphSONNoTypes() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern.json");
GraphSONWriter.build().create().writeGraph(os, TinkerFactory.createModern());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteCrewGraphAsGraphSONNoTypes() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-crew.json");
GraphSONWriter.build().create().writeGraph(os, TinkerFactory.createTheCrew());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicGraphNormalizedAsGraphSON() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic-normalized.json");
GraphSONWriter.build().mapper(GraphSONMapper.build().normalize(true).create()).create().writeGraph(os, TinkerFactory.createClassic());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernGraphNormalizedAsGraphSON() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern-normalized.json");
GraphSONWriter.build().mapper(GraphSONMapper.build().normalize(true).create()).create().writeGraph(os, TinkerFactory.createModern());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteClassicGraphAsGraphSONWithTypes() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-classic-typed.json");
GraphSONWriter.build().mapper(GraphSONMapper.build().embedTypes(true).create())
.create().writeGraph(os, TinkerFactory.createClassic());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteModernGraphAsGraphSONWithTypes() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-modern-typed.json");
GraphSONWriter.build().mapper(GraphSONMapper.build().embedTypes(true).create())
.create().writeGraph(os, TinkerFactory.createModern());
os.close();
}
/**
* No assertions. Just write out the graph for convenience.
*/
@Test
public void shouldWriteCrewGraphAsGraphSONWithTypes() throws IOException {
final OutputStream os = new FileOutputStream(tempPath + "tinkerpop-crew-typed.json");
GraphSONWriter.build().mapper(GraphSONMapper.build().embedTypes(true).create())
.create().writeGraph(os, TinkerFactory.createTheCrew());
os.close();
}
@Test
public void shouldManageIndices() {
final TinkerGraph g = TinkerGraph.open();
Set<String> keys = g.getIndexedKeys(Vertex.class);
assertEquals(0, keys.size());
keys = g.getIndexedKeys(Edge.class);
assertEquals(0, keys.size());
g.createIndex("name1", Vertex.class);
g.createIndex("name2", Vertex.class);
g.createIndex("oid1", Edge.class);
g.createIndex("oid2", Edge.class);
// add the same one twice to check idempotance
g.createIndex("name1", Vertex.class);
keys = g.getIndexedKeys(Vertex.class);
assertEquals(2, keys.size());
for (String k : keys) {
assertTrue(k.equals("name1") || k.equals("name2"));
}
keys = g.getIndexedKeys(Edge.class);
assertEquals(2, keys.size());
for (String k : keys) {
assertTrue(k.equals("oid1") || k.equals("oid2"));
}
g.dropIndex("name2", Vertex.class);
keys = g.getIndexedKeys(Vertex.class);
assertEquals(1, keys.size());
assertEquals("name1", keys.iterator().next());
g.dropIndex("name1", Vertex.class);
keys = g.getIndexedKeys(Vertex.class);
assertEquals(0, keys.size());
g.dropIndex("oid1", Edge.class);
keys = g.getIndexedKeys(Edge.class);
assertEquals(1, keys.size());
assertEquals("oid2", keys.iterator().next());
g.dropIndex("oid2", Edge.class);
keys = g.getIndexedKeys(Edge.class);
assertEquals(0, keys.size());
g.dropIndex("better-not-error-index-key-does-not-exist", Vertex.class);
g.dropIndex("better-not-error-index-key-does-not-exist", Edge.class);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotCreateVertexIndexWithNullKey() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex(null, Vertex.class);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotCreateEdgeIndexWithNullKey() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex(null, Edge.class);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotCreateVertexIndexWithEmptyKey() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex("", Vertex.class);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotCreateEdgeIndexWithEmptyKey() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex("", Edge.class);
}
@Ignore
@Test
public void shouldUpdateVertexIndicesInNewGraph() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex("name", Vertex.class);
g.addVertex("name", "marko", "age", 29);
g.addVertex("name", "stephen", "age", 35);
// a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
// to get into the Pipeline and evaluate what's going through it. in this case, we know that at index
// is used because only "stephen" ages should pass through the pipeline due to the inclusion of the
// key index lookup on "name". If there's an age of something other than 35 in the pipeline being evaluated
// then something is wrong.
assertEquals(1, StreamFactory.stream(g.V().has("age", (t, u) -> {
assertEquals(35, t);
return true;
}, 35).has("name", "stephen")).count());
}
@Ignore
@Test
public void shouldRemoveAVertexFromAnIndex() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex("name", Vertex.class);
g.addVertex("name", "marko", "age", 29);
g.addVertex("name", "stephen", "age", 35);
final Vertex v = g.addVertex("name", "stephen", "age", 35);
// a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
// to get into the Pipeline and evaluate what's going through it. in this case, we know that at index
// is used because only "stephen" ages should pass through the pipeline due to the inclusion of the
// key index lookup on "name". If there's an age of something other than 35 in the pipeline being evaluated
// then something is wrong.
assertEquals(2, StreamFactory.stream(g.V().has("age", (t, u) -> {
assertEquals(35, t);
return true;
}, 35).has("name", "stephen")).count());
v.remove();
assertEquals(1, StreamFactory.stream(g.V().has("age", (t, u) -> {
assertEquals(35, t);
return true;
}, 35).has("name", "stephen")).count());
}
@Ignore
@Test
public void shouldUpdateVertexIndicesInExistingGraph() {
final TinkerGraph g = TinkerGraph.open();
g.addVertex("name", "marko", "age", 29);
g.addVertex("name", "stephen", "age", 35);
// a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
// to get into the Pipeline and evaluate what's going through it. in this case, we know that at index
// is not used because "stephen" and "marko" ages both pass through the pipeline.
assertEquals(1, StreamFactory.stream(g.V().has("age", (t, u) -> {
assertTrue(t.equals(35) || t.equals(29));
return true;
}, 35).has("name", "stephen")).count());
g.createIndex("name", Vertex.class);
// another spy into the pipeline for index check. in this case, we know that at index
// is used because only "stephen" ages should pass through the pipeline due to the inclusion of the
// key index lookup on "name". If there's an age of something other than 35 in the pipeline being evaluated
// then something is wrong.
assertEquals(1, StreamFactory.stream(g.V().has("age", (t, u) -> {
assertEquals(35, t);
return true;
}, 35).has("name", "stephen")).count());
}
@Ignore
@Test
public void shouldUpdateEdgeIndicesInNewGraph() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex("oid", Edge.class);
final Vertex v = g.addVertex();
v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
v.addEdge("friend", v, "oid", "2", "weight", 0.6f);
// a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
// to get into the Pipeline and evaluate what's going through it. in this case, we know that at index
// is used because only oid 1 should pass through the pipeline due to the inclusion of the
// key index lookup on "oid". If there's an weight of something other than 0.5f in the pipeline being
// evaluated then something is wrong.
assertEquals(1, StreamFactory.stream(g.E().has("weight", (t, u) -> {
assertEquals(0.5f, t);
return true;
}, 0.5).has("oid", "1")).count());
}
@Ignore
@Test
public void shouldRemoveEdgeFromAnIndex() {
final TinkerGraph g = TinkerGraph.open();
g.createIndex("oid", Edge.class);
final Vertex v = g.addVertex();
v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
final Edge e = v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
v.addEdge("friend", v, "oid", "2", "weight", 0.6f);
// a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
// to get into the Pipeline and evaluate what's going through it. in this case, we know that at index
// is used because only oid 1 should pass through the pipeline due to the inclusion of the
// key index lookup on "oid". If there's an weight of something other than 0.5f in the pipeline being
// evaluated then something is wrong.
assertEquals(2, StreamFactory.stream(g.E().has("weight", (t, u) -> {
assertEquals(0.5f, t);
return true;
}, 0.5).has("oid", "1")).count());
e.remove();
assertEquals(1, StreamFactory.stream(g.E().has("weight", (t, u) -> {
assertEquals(0.5f, t);
return true;
}, 0.5).has("oid", "1")).count());
}
@Ignore
@Test
public void shouldUpdateEdgeIndicesInExistingGraph() {
final TinkerGraph g = TinkerGraph.open();
final Vertex v = g.addVertex();
v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
v.addEdge("friend", v, "oid", "2", "weight", 0.6f);
// a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
// to get into the Pipeline and evaluate what's going through it. in this case, we know that at index
// is not used because "1" and "2" weights both pass through the pipeline.
assertEquals(1, StreamFactory.stream(g.E().has("weight", (t, u) -> {
assertTrue(t.equals(0.5f) || t.equals(0.6f));
return true;
}, 0.5).has("oid", "1")).count());
g.createIndex("oid", Edge.class);
// another spy into the pipeline for index check. in this case, we know that at index
// is used because only oid 1 should pass through the pipeline due to the inclusion of the
// key index lookup on "oid". If there's an weight of something other than 0.5f in the pipeline being
// evaluated then something is wrong.
assertEquals(1, StreamFactory.stream(g.E().has("weight", (t, u) -> {
assertEquals(0.5f, t);
return true;
}, 0.5).has("oid", "1")).count());
}
/**
* This test helps with data conversions on Grateful Dead. No Assertions...run as needed. Never read from the
* GraphML source as it will always use a String identifier.
*/
@Test
public void shouldWriteGratefulDead() throws IOException {
final Graph g = TinkerGraph.open();
final GraphReader reader = KryoReader.build().create();
try (final InputStream stream = AbstractGremlinTest.class.getResourceAsStream("/com/tinkerpop/gremlin/structure/io/kryo/grateful-dead.gio")) {
reader.readGraph(stream, g);
}
/* keep this hanging around because changes to kryo format will need grateful dead generated from json so you can generate the gio
final GraphReader reader = GraphSONReader.build().embedTypes(true).create();
try (final InputStream stream = AbstractGremlinTest.class.getResourceAsStream("/com/tinkerpop/gremlin/structure/io/graphson/grateful-dead.json")) {
reader.readGraph(stream, g);
}
*/
final Graph ng = TinkerGraph.open();
g.V().sideEffect(ov -> {
final Vertex v = ov.get();
if (v.label().equals("song"))
ng.addVertex(T.id, Integer.parseInt(v.id().toString()), T.label, "song", "name", v.value("name"), "performances", v.property("performances").orElse(0), "songType", v.property("songType").orElse(""));
else if (v.label().equals("artist"))
ng.addVertex(T.id, Integer.parseInt(v.id().toString()), T.label, "artist", "name", v.value("name"));
else
throw new RuntimeException("damn");
}).iterate();
g.E().sideEffect(oe -> {
final Edge e = oe.get();
final Vertex v2 = ng.V(Integer.parseInt(e.inV().next().id().toString())).next();
final Vertex v1 = ng.V(Integer.parseInt(e.outV().next().id().toString())).next();
if (e.label().equals("followedBy"))
v1.addEdge("followedBy", v2, T.id, Integer.parseInt(e.id().toString()), "weight", e.value("weight"));
else if (e.label().equals("sungBy"))
v1.addEdge("sungBy", v2, T.id, Integer.parseInt(e.id().toString()));
else if (e.label().equals("writtenBy"))
v1.addEdge("writtenBy", v2, T.id, Integer.parseInt(e.id().toString()));
else
throw new RuntimeException("bah");
}).iterate();
final OutputStream os = new FileOutputStream(tempPath + "grateful-dead.gio");
KryoWriter.build().create().writeGraph(os, ng);
os.close();
final OutputStream os2 = new FileOutputStream(tempPath + "grateful-dead.json");
GraphSONWriter.build().mapper(GraphSONMapper.build().embedTypes(true).create()).create().writeGraph(os2, g);
os2.close();
final OutputStream os3 = new FileOutputStream(tempPath + "grateful-dead.xml");
GraphMLWriter.build().create().writeGraph(os3, g);
os3.close();
final OutputStream os4 = new FileOutputStream(tempPath + "grateful-dead-vertices.gio");
KryoWriter.build().create().writeVertices(os4, g.V(), Direction.BOTH);
os.close();
final OutputStream os5 = new FileOutputStream(tempPath + "grateful-dead-vertices.ldjson");
GraphSONWriter.build().create().writeVertices(os5, g.V(), Direction.BOTH);
os.close();
}
protected void deleteFile(final String path) throws IOException {
final File file = new File(path);
if (file.exists()) {
file.delete();
}
}
}
|
package authoring_environment;
import java.util.ArrayList;
import java.util.List;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
/**
* Workspace TabPane for having multiple
* workspaces in the authoring environment
*
* @author Jennie Ju
*
*/
public class WorkspaceView extends TabPane {
private List<ShapeGrid> myGrids;
private int myCurrentTabIdx;
public WorkspaceView() {
myGrids = new ArrayList<>();
}
/**
* Adds a new tab to the workspace
* and gives it a new name based on the
* number of tabs that have been made
* @param tab
*/
/*
* TODO: This only works when you close the most recent workspace (rightmost one).
* Closing any other workspace does not automatically select the next one (the
* workspaces ahead of the closed one shift left one - for some goddamn reason
* JavaFX does not detect this as a change in index. Actually what the hell.
*
* Also when you close the last tab, then make a new one. Creating that new tab is
* not recognized as a selection switch.
*
* @Mike Zhu
*/
public void addNextTab(Tab tab, String name) {
tab.setText(name);
super.getTabs().add(tab);
getSelectionModel().select(tab);
tab.setOnClosed(new EventHandler<Event>() {
@Override
public void handle(Event closed) {
int idx = getSelectionModel().getSelectedIndex();
if(idx>=0){
myGrids.remove(idx);
}
if(idx==-1){
myGrids.remove(0);
}
}
});
}
public ShapeGrid getActiveGrid(){
SingleSelectionModel<Tab> selectionModel = getSelectionModel();
int idx = selectionModel.getSelectedIndex();
if(idx==-1 || idx>=myGrids.size()){
return myGrids.get(0);
}
return myGrids.get(idx);
}
public void addGrid(ShapeGrid grid){
myGrids.add(grid);
}
}
|
package org.search.nibrs.validation;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.search.nibrs.model.GroupAIncidentReport;
import org.search.nibrs.model.Offense;
/**
* Class that manages a set of "edits" to baseline incidents. These edits create "exemplars" of NIBRS rules violations that can be used to
* unit test the validation logic in the precert tool.
*
*/
public class RuleViolationExemplarFactory {
private static final RuleViolationExemplarFactory INSTANCE = new RuleViolationExemplarFactory();
@SuppressWarnings("unused")
private static final Logger LOG = LogManager.getLogger(RuleViolationExemplarFactory.class);
private Map<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>> groupATweakerMap;
private RuleViolationExemplarFactory() {
groupATweakerMap = new HashMap<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>>();
populateGroupAExemplarMap();
}
/**
* Get an instance of the factory.
* @return the instance
*/
public static final RuleViolationExemplarFactory getInstance() {
return INSTANCE;
}
/**
* Get an Incident that violates the specified rule. For rules and their numbers, reference the NIBRS Technical Specification, Section 5.
* @param ruleNumber the rule number
* @return an incident that exemplifies violation of the rule
*/
public List<GroupAIncidentReport> getGroupAIncidentsThatViolateRule(Integer ruleNumber) {
return groupATweakerMap.get(ruleNumber).apply(BaselineIncidentFactory.getBaselineIncident());
}
private void populateGroupAExemplarMap() {
groupATweakerMap.put(59, incident -> {
//First two positions must be the code of the state (e.g., SC, MD) in which the incident occurred.
//non-federal participants, every record must have the same code.
GroupAIncidentReport ret = incident.deepCopy();
ret.setOri("ZZ123456789");
return Collections.singletonList(ret);
});
groupATweakerMap.put(101, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 1 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
GroupAIncidentReport copy7 = copy.deepCopy();
copy7.setExceptionalClearanceDate(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
return incidents;
});
groupATweakerMap.put(104, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 1 must be valid.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(1054);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(14);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri("WA1234");
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber("12345");
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(Date.from(LocalDateTime.of(1054, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode("X");
GroupAIncidentReport copy7 = copy.deepCopy();
copy7.setCityIndicator("ZZ12");
//ReportDateIndicator should be set to "R" if unknown.
GroupAIncidentReport copy8 = copy.deepCopy();
copy8.setIncidentDate(null);
copy8.setReportDateIndicator("S");
GroupAIncidentReport copy9 = copy.deepCopy();
copy9.setExceptionalClearanceDate(Date.from(LocalDateTime.of(2016, 13, 12, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
incidents.add(copy8);
incidents.add(copy9);
return incidents;
});
groupATweakerMap.put(105, incident -> {
//The data element in error contains a date that is not entered correctly.
//Each component of the date must be valid; that is, months must be 01 through 12,
//days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx).
//In addition, days cannot exceed maximum for the month (e.g., June cannot have 31days).
//Also, the date cannot exceed the current date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(0120);
copy.setMonthOfTape(5);
GroupAIncidentReport copy2 = copy.deepCopy();
copy.setYearOfTape(2016);
copy.setMonthOfTape(13);
GroupAIncidentReport copy3 = copy.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2016, 6, 31, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
GroupAIncidentReport copy4 = copy.deepCopy();
copy.setExceptionalClearanceDate(Date.from(LocalDateTime.of(3016, 13, 12, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy4);
return incidents;
});
groupATweakerMap.put(115, incident -> {
//(Incident Number) Must be blank right-fill if under 12 characters in length.
//Cannot have embedded blanks between the first and last characters entered.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentNumber("1234 5678");
return Collections.singletonList(ret);
});
groupATweakerMap.put(116, incident -> {
//(Incident Number) must be left-justified with blank right-fill.
//Since the number is less than 12 characters, it must begin in position 1.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentNumber(" 12345678");
return Collections.singletonList(ret);
});
groupATweakerMap.put(117, incident -> {
//(Incident Number) can only have character combinations of A through Z, 0 through 9,
//hyphens, and/or blanks. For example, 89-123-SC is valid, but 89+123*SC is invalid.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentNumber("89+123*SC");
return Collections.singletonList(ret);
});
groupATweakerMap.put(119, incident -> {
//Data Element 2A (Cargo Theft) must be populated with a valid data value when
//Data Element 6 (UCR Offense Code) contains a Cargo Theft-related offense.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setCargoTheftIndicator(true);
GroupAIncidentReport copy2 = copy.deepCopy();
copy.getOffenses().get(0).setUcrOffenseCode("13B");
incidents.add(copy);
incidents.add(copy2);
return incidents;
});
groupATweakerMap.put(151, incident -> {
//This field must be blank if the incident date is known. If the incident date is unknown,
//then the report date would be entered instead and must be indicated with an R in the Report
//Indicator field within the Administrative Segment. The "R" in this case is invalid.
GroupAIncidentReport ret = incident.deepCopy();
ret.setReportDateIndicator("R");
return Collections.singletonList(ret);
});
groupATweakerMap.put(152, incident -> {
//If Hour is entered within Data Element 3 (Incident Date/Hour), it must be 00 through 23.
//If 00=Midnight is entered, be careful that the Incident Date is entered as if the time was
//1 minute past midnight.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentDate(Date.from(LocalDateTime.of(2016, 5, 12, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
return Collections.singletonList(ret);
});
groupATweakerMap.put(153, incident -> {
//Data Element 4 ((Cleared Exceptionally) Cannot be N=Not Applicable if Data Element 5 (Exceptional Clearance Date) is entered.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setExceptionalClearanceCode("N");
copy.setExceptionalClearanceDate(Date.from(LocalDateTime.of(2016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(155, incident -> {
//Data Element 5 (Exceptional Clearance Date) is earlier than Data Element 3 (Incident Date/Hour).
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
copy.setExceptionalClearanceDate(Date.from(LocalDateTime.of(2015, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(156, incident -> {
//Data Element 5 (Exceptional Clearance Date) must be present if the case was cleared exceptionally.
//Data Element 4 (Cleared Exceptionally) has an entry of A through E; therefore, the date must also be entered.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setExceptionalClearanceCode("A");
copy.setExceptionalClearanceDate(null);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(170, incident -> {
//Data Element 3 (Incident Date) The date cannot be later than the year and month the electronic submission represents.
//For example, the May 1999 electronic submission cannot contain incidents happening after this date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(3016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(171, incident -> {
//A Group A Incident Report was submitted with a date entered into Data Element 3 (Incident Date/Hour)
//that is earlier than January 1 of the previous year, using the Month of Tape and Year of Tape as a reference point,
//e.g., if the Month of Tape and Year of Tape contain a value of 01/1999, but the incident date is 12/25/1997, the incident will be rejected.
//Volume 2, section I, provides specifications concerning the FBIs 2-year database.
//For example, the May 1999 electronic submission cannot contain incidents happening after this date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2000, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(172, incident -> {
//(Incident Date) cannot be earlier than 01/01/1991. This edit will preclude dates that are obviously
//incorrect since the FBI began accepting NIBRS data on this date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(1990, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(173, incident -> {
//Data Element 5 (Exceptional Clearance Date) cannot contain a date earlier than the date the LEA began submitting data via the NIBRS.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(1990, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
GroupAIncidentReport copy1 = incident.deepCopy();
copy1.setExceptionalClearanceDate(Date.from(LocalDateTime.of(1016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
incidents.add(copy1);
return incidents;
});
groupATweakerMap.put(201, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 2 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
GroupAIncidentReport copy7 = copy.deepCopy();
Offense ucrOffense = new Offense();
ucrOffense.setUcrOffenseCode(null);
GroupAIncidentReport copy8 = copy.deepCopy();
Offense attemptedOffense = new Offense();
attemptedOffense.setOffenseAttemptedCompleted(null);
GroupAIncidentReport copy9 = copy.deepCopy();
Offense biasOffense = new Offense();
biasOffense.setBiasMotivation(0, null);
GroupAIncidentReport copy10 = copy.deepCopy();
Offense offenderSuspectedOfUsing = new Offense();
offenderSuspectedOfUsing.setOffendersSuspectedOfUsing(0, null);
GroupAIncidentReport copy11 = copy.deepCopy();
Offense offenseLocation = new Offense();
offenseLocation.setLocationType(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
incidents.add(copy8);
incidents.add(copy9);
incidents.add(copy10);
incidents.add(copy11);
return incidents;
});
groupATweakerMap.put(204, incident -> {
//The referenced data element in a Group A Incident Report Segment 2 must
//be populated with a valid data value.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setOri("1234567890123");
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setOri("ZZ123456789");
GroupAIncidentReport copy3 = copy.deepCopy();
Offense firstOffense = new Offense();
firstOffense.setUcrOffenseCode("XXX");
GroupAIncidentReport copy4 = copy.deepCopy();
Offense biasOffense = new Offense();
biasOffense.setBiasMotivation(0, "10");
GroupAIncidentReport copy5 = copy.deepCopy();
Offense offenseLocation = new Offense();
offenseLocation.setLocationType("99");
GroupAIncidentReport copy6 = copy.deepCopy();
Offense numberOfPremisesEntered = new Offense();
numberOfPremisesEntered.setNumberOfPremisesEntered(100);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(206, incident -> {
// The referenced data element in error is one that contains multiple
// data values. When more than one code is entered, none can be duplicate codes.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffendersSuspectedOfUsing = new Offense();
firstOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "A");
Offense secondOffendersSuspectedOfUsing = new Offense();
secondOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "C");
Offense thirdOffendersSuspectedOfUsing = new Offense();
thirdOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "C");
GroupAIncidentReport copy2 = incident.deepCopy();
Offense firstBiasMotivationOffense = new Offense();
firstBiasMotivationOffense.setBiasMotivation(0,"15");
Offense secondBiasMotivationOffense = new Offense ();
secondBiasMotivationOffense.setBiasMotivation(0, "26");
Offense thirdBiasMotivationOffense = new Offense ();
thirdBiasMotivationOffense.setBiasMotivation (0, "26");
incidents.add(copy);
incidents.add(copy2);
return incidents;
});
groupATweakerMap.put(207, incident -> {
// The referenced data element in error is one that contains multiple
// data values. However "N" is mutually exclusive with other codes.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffendersSuspectedOfUsing = new Offense();
firstOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "A");
Offense secondOffendersSuspectedOfUsing = new Offense();
secondOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "N");
GroupAIncidentReport copy2 = incident.deepCopy();
Offense firstBiasMotivationOffense = new Offense();
firstBiasMotivationOffense.setBiasMotivation(0,"15");
Offense secondBiasMotivationOffense = new Offense ();
secondBiasMotivationOffense.setBiasMotivation(0, "88");
incidents.add(copy);
incidents.add(copy2);
return incidents;
});
groupATweakerMap.put(251, incident -> {
// (Offense Attempted/Completed) Must be a valid code of A=Attempted or C=Completed.
GroupAIncidentReport ret = incident.deepCopy();
ret.getOffenses().get(0).setOffenseAttemptedCompleted("X");
return Collections.singletonList(ret);
});
groupATweakerMap.put(252, incident -> {
// When number of premises is entered location type must be 14 or 19
// and UCR Offense Code must be Burglary.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
// todo: implement this for real
GroupAIncidentReport copy = incident.deepCopy();
Offense offense = new Offense();
offense.setNumberOfPremisesEntered(2);
offense.setLocationType("14");
incident.addOffense(offense);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(256, incident -> {
//Offense Attempted/Completed, Data Element 7, must be a valid code of A=Attempted or C=Completed if UCR code is Homicide
// Assault.
GroupAIncidentReport ret = incident.deepCopy();
ret.getOffenses().get(0).setUcrOffenseCode("09A");
ret.getOffenses().get(0).setOffenseAttemptedCompleted("X");
return Collections.singletonList(ret);
});
groupATweakerMap.put(262, incident -> {
//When a Group A Incident Report is submitted, the individual segments
//comprising the incident cannot contain duplicates.
//In this case, two Offense Segments were submitted having the same
//offense in Data Element 6 (UCR Offense Code).
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense secondOffense = new Offense();
secondOffense.setUcrOffenseCode("13B");
copy.addOffense(secondOffense);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(263, incident -> {
//Can be submitted only 10 times for each Group A Incident Report;
//10 offense codes are allowed for each incident.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffense = new Offense();
firstOffense.setUcrOffenseCode("13A");
Offense secondOffense = new Offense();
secondOffense.setUcrOffenseCode("13B");
Offense thirdOffense = new Offense();
thirdOffense.setUcrOffenseCode("13C");
Offense fourthOffense = new Offense();
fourthOffense.setUcrOffenseCode("13D");
Offense fifthOffense = new Offense();
fifthOffense.setUcrOffenseCode("13E");
Offense sixthOffense = new Offense();
sixthOffense.setUcrOffenseCode("13F");
Offense seventhOffense = new Offense();
seventhOffense.setUcrOffenseCode("13G");
Offense eighthOffense = new Offense();
eighthOffense.setUcrOffenseCode("13H");
Offense ninthOffense = new Offense();
ninthOffense.setUcrOffenseCode("13I");
Offense tenthOffense = new Offense();
tenthOffense.setUcrOffenseCode("13J");
Offense eleventhOffense = new Offense();
eleventhOffense.setUcrOffenseCode("13K");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(264, incident -> {
//Group A Offense code cannot contain a Group B Offense
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffense = new Offense();
firstOffense.setUcrOffenseCode("90A");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(266, incident -> {
//When a Justifiable Homicide is reported, no other offense may be
//reported in the Group A Incident Report. These should be submitted on another
//Group A Incident Report.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense JustifiableHomicideOffense = new Offense();
JustifiableHomicideOffense.setUcrOffenseCode("09C");
Offense secondOffense = new Offense();
secondOffense.setUcrOffenseCode("13B");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(267, incident -> {
//If a homicide offense is submitted, Data Element 13 (Type Weapon/Force Involved)
//cannot have 99=None. Some type of weapon/force must be used in a homicide offense.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense homicideOffense = new Offense();
homicideOffense.setUcrOffenseCode("09A");
homicideOffense.setTypeOfWeaponForceInvolved(0, null);
GroupAIncidentReport copy2 = incident.deepCopy();
Offense homicideOffense2 = new Offense();
homicideOffense2.setUcrOffenseCode("09A");
homicideOffense2.setTypeOfWeaponForceInvolved(0, "99");
incidents.add(copy);
incidents.add(copy2);
return incidents;
});
groupATweakerMap.put(270, incident -> {
//If a justifiable homicide offense is submitted, Data Element 8A (Bias motivation) must be 88.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense JustifiableHomicideOffense = new Offense();
JustifiableHomicideOffense.setUcrOffenseCode("09C");
JustifiableHomicideOffense.setBiasMotivation(0, "11");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(301, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 3 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(401, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 4 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(501, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 5 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(601, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 6 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
}
}
|
package com.pantherman594.librarysignup;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
class Scheduler implements EventHandler<ActionEvent> {
private TextField email;
private TextField password;
private Text title;
private Button submit;
private Set<ComboBox> comboBoxes;
private Map<Long, String> holidays;
private Map<Integer, Integer> studies;
Scheduler(TextField email, PasswordField password, Text title, Button submit, Map<Integer, Integer> studies, Set<ComboBox> comboBoxes) {
this.email = email;
this.password = password;
this.title = title;
this.submit = submit;
this.studies = studies;
this.comboBoxes = comboBoxes;
holidays = new HashMap<>();
addHolidays();
}
@Override
public void handle(ActionEvent event) {
if (email.getText() == null || email.getText().isEmpty() || password.getText() == null || password.getText().isEmpty()) {
title.setText("\tError: Invalid email/password.");
return;
}
title.setText("\tLibrary Sign Up is running... (minimize this)");
LibrarySignUp.getInstance().hide();
for (ComboBox comboBox : comboBoxes) {
comboBox.setDisable(true);
}
email.setDisable(true);
password.setDisable(true);
submit.setText("Quit");
submit.setOnAction(ev -> LibrarySignUp.getInstance().exit(0));
new Thread(() -> {
while (LibrarySignUp.getInstance().shouldRunScheduler()) {
Calendar date = Calendar.getInstance();
date.add(Calendar.DAY_OF_MONTH, 1);
date.set(Calendar.HOUR_OF_DAY, 18);
date.set(Calendar.MINUTE, 59);
date.set(Calendar.SECOND, 45);
date.set(Calendar.MILLISECOND, 0);
final long endTime = date.getTimeInMillis();
while (System.currentTimeMillis() < endTime) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
long tomorrow = LocalDate.now().toEpochDay() + 1;
int sixDay = getSixDay(getSchoolDays(tomorrow));
if (isSchoolDay(tomorrow) && studies.keySet().contains(sixDay)) {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
int control = KeyEvent.VK_CONTROL;
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
control = KeyEvent.VK_META;
}
Keyboard k = null;
try {
k = new Keyboard();
} catch (AWTException ignored) {
title.setText("Error: Unable to initialize keyboard robot.");
return;
}
try {
Desktop.getDesktop().browse(new URI("https://pickatime.com/client?logout=on&ven=11607876"));
Thread.sleep(1000);
k.doType(control, KeyEvent.VK_W);
Desktop.getDesktop().browse(new URI("https://pickatime.com/client?ven=11607876&email=" + email.getText()));
Thread.sleep(5000);
k.doType(control, KeyEvent.VK_F);
Thread.sleep(1000);
k.type("onal pass");
Thread.sleep(1000);
k.doType(KeyEvent.VK_ESCAPE);
k.type("\t");
k.type(password.getText());
k.type("\n");
Thread.sleep(5000);
k.doType(control, KeyEvent.VK_F);
Thread.sleep(1000);
k.type("st");
k.doType(KeyEvent.VK_ESCAPE);
k.type("\n");
Thread.sleep(5000);
k.doType(control, KeyEvent.VK_F);
Thread.sleep(1000);
String idNum = "55 ";
switch(studies.get(sixDay)) {
case 2: idNum = "59 "; break;
case 3: idNum = "48 "; break;
case 4: idNum = "37 "; break;
case 6: idNum = "42 "; break;
case 7: idNum = "30 "; break;
}
k.type(idNum);
Thread.sleep(1000);
k.type("\n");
Thread.sleep(1000);
k.doType(KeyEvent.VK_ESCAPE);
k.type("\n");
Thread.sleep(5000);
k.doType(control, KeyEvent.VK_F);
Thread.sleep(1000);
k.type("cr");
k.doType(KeyEvent.VK_ESCAPE);
k.type("\n");
k.doType(control, KeyEvent.VK_W);
Desktop.getDesktop().browse(new URI("https://pickatime.com/client?logout=on&ven=11607876"));
Thread.sleep(1000);
k.doType(control, KeyEvent.VK_W);
} catch (IOException | URISyntaxException | InterruptedException ignored) {}
System.exit(0);
} else {
title.setText("Error: Unable to open browser.");
}
}
}
}).start();
}
private int getSchoolDays(long date) {
int schoolDays = 1;
for (long i = LocalDate.of(2016, 9, 8).toEpochDay(); i < date; i++) {
if (isSchoolDay(i)) {
schoolDays++;
}
}
return schoolDays;
}
private boolean isSchoolDay(long date) {
return date % 7 != 2 && date % 7 != 3 && !holidays.keySet().contains(date);
}
private int getSixDay(int schoolDays) {
return schoolDays % 6 == 0 ? 6 : schoolDays % 6;
}
private void addHolidays() {
addHoliday(2016, 10, 10, "Columbus Day");
addHoliday(2016, 11, 11, "Veterans' Day");
addHoliday(2016, 11, 24, "Thanksgiving Recess");
addHoliday(2016, 11, 25, "Thanksgiving Recess");
addHoliday(2016, 12, 23, "Winter Recess");
addHoliday(2016, 12, 26, "Winter Recess");
addHoliday(2016, 12, 27, "Winter Recess");
addHoliday(2016, 12, 28, "Winter Recess");
addHoliday(2016, 12, 29, "Winter Recess");
addHoliday(2016, 12, 30, "Winter Recess");
addHoliday(2017, 1, 2, "Winter Recess");
addHoliday(2017, 1, 3, "Winter Recess");
addHoliday(2017, 1, 16, "M. L. King Jr. Day");
addHoliday(2017, 2, 20, "Presidents' Day");
addHoliday(2017, 2, 21, "February Recess");
addHoliday(2017, 2, 22, "February Recess");
addHoliday(2017, 2, 23, "February Recess");
addHoliday(2017, 2, 24, "February Recess");
addHoliday(2017, 4, 14, "Good Friday");
addHoliday(2017, 4, 17, "Patriots' Day");
addHoliday(2017, 4, 18, "Spring Recess");
addHoliday(2017, 4, 19, "Spring Recess");
addHoliday(2017, 4, 20, "Spring Recess");
addHoliday(2017, 4, 21, "Spring Recess");
addHoliday(2017, 5, 29, "Memorial Day");
}
private void addHoliday(int year, int month, int day, String name) {
holidays.put(LocalDate.of(year, month, day).toEpochDay(), name);
}
}
|
package org.search.nibrs.validation;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.search.nibrs.model.GroupAIncidentReport;
import org.search.nibrs.model.Offense;
/**
* Class that manages a set of "edits" to baseline incidents. These edits create "exemplars" of NIBRS rules violations that can be used to
* unit test the validation logic in the precert tool.
*
*/
public class RuleViolationExemplarFactory {
private static final RuleViolationExemplarFactory INSTANCE = new RuleViolationExemplarFactory();
@SuppressWarnings("unused")
private static final Logger LOG = LogManager.getLogger(RuleViolationExemplarFactory.class);
private Map<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>> groupATweakerMap;
private RuleViolationExemplarFactory() {
groupATweakerMap = new HashMap<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>>();
populateGroupAExemplarMap();
}
/**
* Get an instance of the factory.
* @return the instance
*/
public static final RuleViolationExemplarFactory getInstance() {
return INSTANCE;
}
/**
* Get an Incident that violates the specified rule. For rules and their numbers, reference the NIBRS Technical Specification, Section 5.
* @param ruleNumber the rule number
* @return an incident that exemplifies violation of the rule
*/
public List<GroupAIncidentReport> getGroupAIncidentsThatViolateRule(Integer ruleNumber) {
return groupATweakerMap.get(ruleNumber).apply(BaselineIncidentFactory.getBaselineIncident());
}
private void populateGroupAExemplarMap() {
groupATweakerMap.put(59, incident -> {
//First two positions must be the code of the state (e.g., SC, MD) in which the incident occurred.
//non-federal participants, every record must have the same code.
GroupAIncidentReport ret = incident.deepCopy();
ret.setOri("ZZ123456789");
return Collections.singletonList(ret);
});
groupATweakerMap.put(101, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 1 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
GroupAIncidentReport copy7 = copy.deepCopy();
copy7.setExceptionalClearanceDate(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
return incidents;
});
groupATweakerMap.put(104, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 1 must be valid.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(1054);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(14);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri("WA1234");
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber("12345");
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(Date.from(LocalDateTime.of(1054, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode("X");
GroupAIncidentReport copy7 = copy.deepCopy();
copy7.setCityIndicator("ZZ12");
//ReportDateIndicator should be set to "R" if unknown.
GroupAIncidentReport copy8 = copy.deepCopy();
copy8.setIncidentDate(null);
copy8.setReportDateIndicator("S");
GroupAIncidentReport copy9 = copy.deepCopy();
//(Incident Hour) The referenced data element must contain a valid data value when it is entered.
copy9.setIncidentDate(Date.from(LocalDateTime.of(2016, 13, 12, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
//(Incident Hour)) The referenced data element must contain a valid data value when it is entered.
GroupAIncidentReport copy10 = copy.deepCopy();
copy10.setExceptionalClearanceDate(Date.from(LocalDateTime.of(2016, 13, 12, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
incidents.add(copy8);
incidents.add(copy9);
incidents.add(copy10);
return incidents;
});
groupATweakerMap.put(105, incident -> {
//The data element in error contains a date that is not entered correctly.
//Each component of the date must be valid; that is, months must be 01 through 12,
//days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx).
//In addition, days cannot exceed maximum for the month (e.g., June cannot have 31days).
//Also, the date cannot exceed the current date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(0120);
copy.setMonthOfTape(5);
GroupAIncidentReport copy2 = copy.deepCopy();
copy.setYearOfTape(2016);
copy.setMonthOfTape(13);
GroupAIncidentReport copy3 = copy.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2016, 6, 31, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
GroupAIncidentReport copy4 = copy.deepCopy();
copy.setExceptionalClearanceDate(Date.from(LocalDateTime.of(3016, 13, 12, 30, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy4);
return incidents;
});
groupATweakerMap.put(115, incident -> {
//(Incident Number) Must be blank right-fill if under 12 characters in length.
//Cannot have embedded blanks between the first and last characters entered.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentNumber("1234 5678");
return Collections.singletonList(ret);
});
groupATweakerMap.put(116, incident -> {
//(Incident Number) must be left-justified with blank right-fill.
//Since the number is less than 12 characters, it must begin in position 1.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentNumber(" 12345678");
return Collections.singletonList(ret);
});
groupATweakerMap.put(117, incident -> {
//(Incident Number) can only have character combinations of A through Z, 0 through 9,
//hyphens, and/or blanks. For example, 89-123-SC is valid, but 89+123*SC is invalid.
GroupAIncidentReport ret = incident.deepCopy();
ret.setIncidentNumber("89+123*SC");
return Collections.singletonList(ret);
});
groupATweakerMap.put(119, incident -> {
//Data Element 2A (Cargo Theft) must be populated with a valid data value when
//Data Element 6 (UCR Offense Code) contains a Cargo Theft-related offense.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setCargoTheftIndicator(true);
GroupAIncidentReport copy2 = copy.deepCopy();
copy.getOffenses().get(0).setUcrOffenseCode("13B");
incidents.add(copy);
incidents.add(copy2);
return incidents;
});
groupATweakerMap.put(151, incident -> {
//This field must be blank if the incident date is known. If the incident date is unknown,
//then the report date would be entered instead and must be indicated with an "R" in the Report
//Indicator field within the Administrative Segment. The "R" in this case is invalid.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setReportDateIndicator("R");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(152, incident -> {
//If Hour is entered within Data Element 3 (Incident Date/Hour), it must be 00 through 23.
//If 00=Midnight is entered, be careful that the Incident Date is entered as if the time was
//1 minute past midnight.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2016, 5, 12, 00, 0, 00).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(153, incident -> {
//Data Element 4 ((Cleared Exceptionally) Cannot be N=Not Applicable if Data Element 5 (Exceptional Clearance Date) is entered.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setExceptionalClearanceCode("N");
copy.setExceptionalClearanceDate(Date.from(LocalDateTime.of(2016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(155, incident -> {
//Data Element 5 (Exceptional Clearance Date) is earlier than Data Element 3 (Incident Date/Hour).
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
copy.setExceptionalClearanceDate(Date.from(LocalDateTime.of(2015, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(156, incident -> {
//Data Element 5 (Exceptional Clearance Date) must be present if the case was cleared exceptionally.
//Data Element 4 (Cleared Exceptionally) has an entry of A through E; therefore, the date must also be entered.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setExceptionalClearanceCode("A");
copy.setExceptionalClearanceDate(null);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(170, incident -> {
//Data Element 3 (Incident Date) The date cannot be later than the year and month the electronic submission represents.
//For example, the May 1999 electronic submission cannot contain incidents happening after this date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(3016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(171, incident -> {
//A Group A Incident Report was submitted with a date entered into Data Element 3 (Incident Date/Hour)
//that is earlier than January 1 of the previous year, using the Month of Tape and Year of Tape as a reference point,
//e.g., if the Month of Tape and Year of Tape contain a value of 01/1999, but the incident date is 12/25/1997, the incident will be rejected.
//Volume 2, section I, provides specifications concerning the FBIs 2-year database.
//For example, the May 1999 electronic submission cannot contain incidents happening after this date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(2000, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(172, incident -> {
//(Incident Date) cannot be earlier than 01/01/1991. This edit will preclude dates that are obviously
//incorrect since the FBI began accepting NIBRS data on this date.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(1990, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(173, incident -> {
//Data Element 5 (Exceptional Clearance Date) cannot contain a date earlier than the date the LEA began submitting data via the NIBRS.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setIncidentDate(Date.from(LocalDateTime.of(1990, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
GroupAIncidentReport copy1 = incident.deepCopy();
copy1.setExceptionalClearanceDate(Date.from(LocalDateTime.of(1016, 5, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant()));
incidents.add(copy);
incidents.add(copy1);
return incidents;
});
groupATweakerMap.put(201, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 2 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
GroupAIncidentReport copy7 = copy.deepCopy();
Offense ucrOffense = new Offense();
ucrOffense.setUcrOffenseCode(null);
GroupAIncidentReport copy8 = copy.deepCopy();
Offense attemptedOffense = new Offense();
attemptedOffense.setOffenseAttemptedCompleted(null);
GroupAIncidentReport copy9 = copy.deepCopy();
Offense biasOffense = new Offense();
biasOffense.setBiasMotivation(0, null);
GroupAIncidentReport copy10 = copy.deepCopy();
Offense offenderSuspectedOfUsing = new Offense();
offenderSuspectedOfUsing.setOffendersSuspectedOfUsing(0, null);
GroupAIncidentReport copy11 = copy.deepCopy();
Offense offenseLocation = new Offense();
offenseLocation.setLocationType(null);
GroupAIncidentReport copy12 = copy.deepCopy();
Offense weaponForceInvolved = new Offense();
weaponForceInvolved.setTypeOfWeaponForceInvolved(0, null);
GroupAIncidentReport copy13 = copy.deepCopy();
Offense automaticWeaponIndicator = new Offense();
automaticWeaponIndicator.setAutomaticWeaponIndicator(0, null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
incidents.add(copy8);
incidents.add(copy9);
incidents.add(copy10);
incidents.add(copy11);
incidents.add(copy12);
incidents.add(copy13);
return incidents;
});
groupATweakerMap.put(204, incident -> {
//The referenced data element in a Group A Incident Report Segment 2 must
//be populated with a valid data value.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setOri("1234567890123");
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setOri("ZZ123456789");
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setCityIndicator("ZZ12");
GroupAIncidentReport copy4 = copy.deepCopy();
Offense firstOffense = new Offense();
firstOffense.setUcrOffenseCode("XXX");
GroupAIncidentReport copy5 = copy.deepCopy();
Offense biasOffense = new Offense();
biasOffense.setBiasMotivation(0, "10");
GroupAIncidentReport copy6 = copy.deepCopy();
Offense offenseLocation = new Offense();
offenseLocation.setLocationType("99");
GroupAIncidentReport copy7 = copy.deepCopy();
Offense numberOfPremisesEntered = new Offense();
numberOfPremisesEntered.setNumberOfPremisesEntered(100);
GroupAIncidentReport copy8 = copy.deepCopy();
Offense methodOfEntry = new Offense();
methodOfEntry.setMethodOfEntry(null);
GroupAIncidentReport copy9 = copy.deepCopy();
Offense criminalActivity = new Offense();
criminalActivity.setTypeOfCriminalActivity(0, null);
GroupAIncidentReport copy10 = copy.deepCopy();
Offense weaponForceInvolved = new Offense();
weaponForceInvolved.setTypeOfWeaponForceInvolved(0, "10");
GroupAIncidentReport copy11 = copy.deepCopy();
Offense automaticWeaponIndicator = new Offense();
automaticWeaponIndicator.setAutomaticWeaponIndicator(0, "B");
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
incidents.add(copy8);
incidents.add(copy9);
incidents.add(copy10);
incidents.add(copy11);
return incidents;
});
groupATweakerMap.put(206, incident -> {
// The referenced data element in error is one that contains multiple
// data values. When more than one code is entered, none can be duplicate codes.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffendersSuspectedOfUsing = new Offense();
firstOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "A");
Offense secondOffendersSuspectedOfUsing = new Offense();
secondOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "C");
Offense thirdOffendersSuspectedOfUsing = new Offense();
thirdOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "C");
GroupAIncidentReport copy2 = incident.deepCopy();
Offense firstBiasMotivationOffense = new Offense();
firstBiasMotivationOffense.setBiasMotivation(0,"15");
Offense secondBiasMotivationOffense = new Offense ();
secondBiasMotivationOffense.setBiasMotivation(0, "26");
Offense thirdBiasMotivationOffense = new Offense ();
thirdBiasMotivationOffense.setBiasMotivation (0, "26");
GroupAIncidentReport copy3 = incident.deepCopy();
Offense firstTypeOfCriminalActivity = new Offense();
firstTypeOfCriminalActivity.setTypeOfCriminalActivity(0,"J");
Offense secondTypeOfCriminalActivity = new Offense();
secondTypeOfCriminalActivity.setTypeOfCriminalActivity(0,"J");
GroupAIncidentReport copy4 = incident.deepCopy();
Offense typeOfWeaponForceInvolved = new Offense();
typeOfWeaponForceInvolved.setTypeOfCriminalActivity(0,"11");
Offense secondtypeOfWeaponForceInvolved = new Offense();
secondTypeOfCriminalActivity.setTypeOfCriminalActivity(0,"11");
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
return incidents;
});
groupATweakerMap.put(207, incident -> {
// The referenced data element in error is one that contains multiple
// data values. However "N" is mutually exclusive with other codes.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffendersSuspectedOfUsing = new Offense();
firstOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "A");
Offense secondOffendersSuspectedOfUsing = new Offense();
secondOffendersSuspectedOfUsing.setOffendersSuspectedOfUsing(0, "N");
GroupAIncidentReport copy2 = incident.deepCopy();
Offense firstBiasMotivationOffense = new Offense();
firstBiasMotivationOffense.setBiasMotivation(0,"15");
Offense secondBiasMotivationOffense = new Offense ();
secondBiasMotivationOffense.setBiasMotivation(0, "88");
GroupAIncidentReport copy3 = incident.deepCopy();
Offense firstTypeOfCriminalActivity = new Offense();
firstTypeOfCriminalActivity.setTypeOfCriminalActivity(0, "N");
Offense secondTypeOfCriminalActivity = new Offense ();
secondTypeOfCriminalActivity.setTypeOfCriminalActivity(0,"J");
GroupAIncidentReport copy4 = incident.deepCopy();
Offense firstTypeOfWeaponForceInvolve = new Offense();
firstTypeOfWeaponForceInvolve.setTypeOfWeaponForceInvolved(0, "11");
Offense secondTypeOfWeaponForceInvolved = new Offense ();
secondTypeOfWeaponForceInvolved.setTypeOfWeaponForceInvolved(0,"99");
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
return incidents;
});
groupATweakerMap.put(220, incident -> {
//Data Element 12 (Type Criminal Activity/Gang Information) Must be populated with a valid data value and cannot be blank when Data Element 6 (UCR Offense Code) is:
// 250=Counterfeiting/Forgery
// 280=Stolen Property Offenses
// 35A=Drug/Narcotic Violations
// 35B=Drug Equipment Violations
// 39C=Gambling Equipment Violations
// 370=Pornography/Obscene Material
// 520=Weapon Law Violations
// 720=Animal Cruelty
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstCriminalActivity = new Offense();
firstCriminalActivity.setTypeOfCriminalActivity(0, null);
firstCriminalActivity.setUcrOffenseCode("250");
GroupAIncidentReport copy1 = incident.deepCopy();
Offense secondCriminalActivity = new Offense();
secondCriminalActivity.setTypeOfCriminalActivity(0, null);
secondCriminalActivity.setUcrOffenseCode("280");
GroupAIncidentReport copy2 = incident.deepCopy();
Offense thirdCriminalActivity = new Offense();
thirdCriminalActivity.setTypeOfCriminalActivity(0, null);
thirdCriminalActivity.setUcrOffenseCode("35A");
GroupAIncidentReport copy3 = incident.deepCopy();
Offense fourthCriminalActivity = new Offense();
fourthCriminalActivity.setTypeOfCriminalActivity(0, null);
fourthCriminalActivity.setUcrOffenseCode("35B");
GroupAIncidentReport copy4 = incident.deepCopy();
Offense fifthCriminalActivity = new Offense();
fifthCriminalActivity.setTypeOfCriminalActivity(0, null);
fifthCriminalActivity.setUcrOffenseCode("39C");
GroupAIncidentReport copy5 = incident.deepCopy();
Offense sixthCriminalActivity = new Offense();
sixthCriminalActivity.setTypeOfCriminalActivity(0, null);
sixthCriminalActivity.setUcrOffenseCode("370");
GroupAIncidentReport copy6 = incident.deepCopy();
Offense seventhCriminalActivity = new Offense();
seventhCriminalActivity.setTypeOfCriminalActivity(0, null);
seventhCriminalActivity.setUcrOffenseCode("520");
GroupAIncidentReport copy7 = incident.deepCopy();
Offense eigthCriminalActivity1 = new Offense();
eigthCriminalActivity1.setTypeOfCriminalActivity(0, null);
eigthCriminalActivity1.setUcrOffenseCode("720");
incidents.add(copy);
incidents.add(copy1);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
incidents.add(copy7);
return incidents;
});
groupATweakerMap.put(251, incident -> {
// (Offense Attempted/Completed) Must be a valid code of A=Attempted or C=Completed.
GroupAIncidentReport ret = incident.deepCopy();
ret.getOffenses().get(0).setOffenseAttemptedCompleted("X");
return Collections.singletonList(ret);
});
groupATweakerMap.put(252, incident -> {
// When number of premises is entered location type must be 14 or 19
// and UCR Offense Code must be Burglary (220).
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense offense = new Offense();
offense.setNumberOfPremisesEntered(2);
offense.setLocationType("14");
offense.setUcrOffenseCode("120");
GroupAIncidentReport copy1 = incident.deepCopy();
Offense offense1 = new Offense();
offense1.setNumberOfPremisesEntered(2);
offense1.setLocationType("19");
offense1.setUcrOffenseCode("120");
incident.addOffense(offense);
incidents.add(copy);
incidents.add(copy1);
return incidents;
});
groupATweakerMap.put(253, incident -> {
//(Method of Entry) Data Element was not entered; it must be entered
//when UCR Offense Code of 220=Burglary has been entered.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense offense = new Offense();
offense.setMethodOfEntry(null);
offense.setUcrOffenseCode("220");
incident.addOffense(offense);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(254, incident -> {
//(Method of Entry) Data Element only applies to UCR Offense Code of 220=Burglary.
//Since a burglary offense was not entered, the Method of Entry should not have been entered.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense offense = new Offense();
offense.setMethodOfEntry("F");
offense.setUcrOffenseCode("13A");
incident.addOffense(offense);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(255, incident -> {
//((Automatic Weapon Indicator) Must be A=Automatic or blank=Not Automatic
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense automaticWeaponIndicator = new Offense();
automaticWeaponIndicator.setAutomaticWeaponIndicator(0, "F");
incident.addOffense(automaticWeaponIndicator);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(256, incident -> {
//Offense Attempted/Completed, Data Element 7, must be a valid code of A=Attempted or C=Completed if UCR code is Homicide
// Assault.
GroupAIncidentReport ret = incident.deepCopy();
ret.getOffenses().get(0).setUcrOffenseCode("09A");
ret.getOffenses().get(0).setOffenseAttemptedCompleted("X");
return Collections.singletonList(ret);
});
groupATweakerMap.put(257, incident -> {
// (Number of Premises Entered) Must be entered if offense code is 220 (Burglary)
//and if Data Element 9 (Location Type) contains 14=Hotel/Motel/Etc. or 19=Rental Storage Facility.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense offense = new Offense();
offense.setLocationType("14");
offense.setUcrOffenseCode("220");
GroupAIncidentReport copy1 = incident.deepCopy();
Offense offense1 = new Offense();
offense1.setLocationType("19");
offense1.setUcrOffenseCode("220");
incident.addOffense(offense);
incidents.add(copy);
incidents.add(copy1);
return incidents;
});
groupATweakerMap.put(258, incident -> {
//(Automatic Weapon Indicator) In Data Element 13 (Type of Weapon/Force Involved), A=Automatic is the third character of code. It is valid only with the following codes:
// 11=Firearm (Type Not Stated)
// 12=Handgun
// 13=Rifle
// 15=Other Firearm
// A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense automaticWeaponIndicator = new Offense();
automaticWeaponIndicator.setAutomaticWeaponIndicator(0, "A");
automaticWeaponIndicator.setTypeOfWeaponForceInvolved(0, "20");
incident.addOffense(automaticWeaponIndicator);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(262, incident -> {
//When a Group A Incident Report is submitted, the individual segments
//comprising the incident cannot contain duplicates.
//In this case, two Offense Segments were submitted having the same
//offense in Data Element 6 (UCR Offense Code).
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense secondOffense = new Offense();
secondOffense.setUcrOffenseCode("13B");
copy.addOffense(secondOffense);
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(263, incident -> {
//Can be submitted only 10 times for each Group A Incident Report;
//10 offense codes are allowed for each incident.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffense = new Offense();
firstOffense.setUcrOffenseCode("13A");
Offense secondOffense = new Offense();
secondOffense.setUcrOffenseCode("13B");
Offense thirdOffense = new Offense();
thirdOffense.setUcrOffenseCode("13C");
Offense fourthOffense = new Offense();
fourthOffense.setUcrOffenseCode("13D");
Offense fifthOffense = new Offense();
fifthOffense.setUcrOffenseCode("13E");
Offense sixthOffense = new Offense();
sixthOffense.setUcrOffenseCode("13F");
Offense seventhOffense = new Offense();
seventhOffense.setUcrOffenseCode("13G");
Offense eighthOffense = new Offense();
eighthOffense.setUcrOffenseCode("13H");
Offense ninthOffense = new Offense();
ninthOffense.setUcrOffenseCode("13I");
Offense tenthOffense = new Offense();
tenthOffense.setUcrOffenseCode("13J");
Offense eleventhOffense = new Offense();
eleventhOffense.setUcrOffenseCode("13K");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(264, incident -> {
//Group A Offense code cannot contain a Group B Offense
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense firstOffense = new Offense();
firstOffense.setUcrOffenseCode("90A");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(266, incident -> {
//When a Justifiable Homicide is reported, no other offense may be
//reported in the Group A Incident Report. These should be submitted on another
//Group A Incident Report.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense JustifiableHomicideOffense = new Offense();
JustifiableHomicideOffense.setUcrOffenseCode("09C");
Offense secondOffense = new Offense();
secondOffense.setUcrOffenseCode("13B");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(267, incident -> {
//If a homicide offense is submitted, Data Element 13 (Type Weapon/Force Involved)
//cannot have 99=None. Some type of weapon/force must be used in a homicide offense.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense homicideOffense = new Offense();
homicideOffense.setUcrOffenseCode("09A");
homicideOffense.setTypeOfWeaponForceInvolved(0, null);
GroupAIncidentReport copy2 = incident.deepCopy();
Offense homicideOffense2 = new Offense();
homicideOffense2.setUcrOffenseCode("09A");
homicideOffense2.setTypeOfWeaponForceInvolved(0, "99");
incidents.add(copy);
incidents.add(copy2);
return incidents;
});
groupATweakerMap.put(270, incident -> {
//If a justifiable homicide offense is submitted, Data Element 8A (Bias motivation) must be 88.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
Offense JustifiableHomicideOffense = new Offense();
JustifiableHomicideOffense.setUcrOffenseCode("09C");
JustifiableHomicideOffense.setBiasMotivation(0, "11");
incidents.add(copy);
return incidents;
});
groupATweakerMap.put(301, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 3 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(401, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 4 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(501, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 5 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
groupATweakerMap.put(601, incident -> {
//The referenced data element in a Group A Incident Report
//Segment 6 is mandatory & must be present.
List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>();
GroupAIncidentReport copy = incident.deepCopy();
copy.setYearOfTape(null);
GroupAIncidentReport copy2 = copy.deepCopy();
copy2.setMonthOfTape(null);
GroupAIncidentReport copy3 = copy.deepCopy();
copy3.setOri(null);
GroupAIncidentReport copy4 = copy.deepCopy();
copy4.setIncidentNumber(null);
GroupAIncidentReport copy5 = copy.deepCopy();
copy5.setIncidentDate(null);
GroupAIncidentReport copy6 = copy.deepCopy();
copy6.setExceptionalClearanceCode(null);
incidents.add(copy);
incidents.add(copy2);
incidents.add(copy3);
incidents.add(copy4);
incidents.add(copy5);
incidents.add(copy6);
return incidents;
});
}
}
|
package com.parnswir.unmp.media;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import android.database.sqlite.SQLiteDatabase;
import com.parnswir.unmp.core.ProgressObservable;
import com.parnswir.unmp.core.ProjectResources;
public abstract class FileCrawlerThread extends Thread {
public static final Set<String> SUPPORTED_FILETYPES = new HashSet<String>(Arrays.asList(
new String[] {"mp3", "wpl"}
));
protected SQLiteDatabase db;
private List<String> folders;
private List<String> files;
protected boolean stop = false;
public ProgressObservable callback = new ProgressObservable();
public FileCrawlerThread(SQLiteDatabase db, String folder) {
ArrayList<String> wrapper = new ArrayList<String>();
wrapper.add(folder);
init(db, wrapper);
}
public FileCrawlerThread(SQLiteDatabase db, List<String> folders) {
init(db, folders);
}
private void init(SQLiteDatabase db, List<String> folders) {
this.folders = folders;
this.db = db;
files = new ArrayList<String>();
}
public void run() {
files.clear();
for (String folderRoot : folders) {
File root = new File(folderRoot);
searchForFilesIn(root);
}
processFiles();
}
private void searchForFilesIn(File file) {
if (stop) return;
if (file.canRead()) {
if (file.isDirectory()) {
searchForFilesInDirectory(file);
} else {
addToFileListIfSuitable(file);
}
}
}
private void searchForFilesInDirectory(File file) {
setProgress("Looking for files in " + file.getAbsolutePath(), -1, -1);
for (File child : file.listFiles()) {
searchForFilesIn(child);
}
}
private void addToFileListIfSuitable(File file) {
if (isSuitable(file)) {
files.add(file.getAbsolutePath());
}
}
private boolean isSuitable(File file) {
String extension = getFileExt(file.getName());
return (SUPPORTED_FILETYPES.contains(extension)) && !stop;
}
public static String getFileExt(String fileName) {
return fileName.toLowerCase(Locale.ENGLISH).substring((fileName.lastIndexOf(".") + 1), fileName.length());
}
private void setProgress(String text, float value, float count) {
callback.change(new ProjectResources.ProgressItem(text, value, count));
}
private void processFiles() {
for (String filePath : files) {
File current = new File(filePath);
if (current != null) {
setProgress(filePath, files.indexOf(filePath), files.size());
handleFile(current);
}
}
setProgress("Done.", files.size(), files.size());
}
abstract void handleFile(File file);
public void kill() {
stop = true;
}
}
|
package br.com.caelum.vraptor.ioc.cdi;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.CDI;
import org.apache.deltaspike.cdise.api.CdiContainer;
import org.apache.deltaspike.cdise.api.CdiContainerLoader;
import org.apache.deltaspike.cdise.weld.ContextController;
import org.hamcrest.MatcherAssert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import br.com.caelum.cdi.component.CDIControllerComponent;
import br.com.caelum.cdi.component.CDISessionComponent;
import br.com.caelum.vraptor.core.BaseComponents;
import br.com.caelum.vraptor.core.RequestInfo;
import br.com.caelum.vraptor.ioc.Container;
import br.com.caelum.vraptor.ioc.ContainerProvider;
import br.com.caelum.vraptor.ioc.WhatToDo;
import br.com.caelum.vraptor.ioc.fixture.ComponentFactoryInTheClasspath;
import br.com.caelum.vraptor.ioc.fixture.CustomComponentWithLifecycleInTheClasspath;
import br.com.caelum.vraptor.validator.MessageInterpolatorFactory;
import br.com.caelum.vraptor.validator.MethodValidatorFactoryCreator;
import br.com.caelum.vraptor.validator.ValidatorCreator;
import br.com.caelum.vraptor.validator.ValidatorFactoryCreator;
import br.com.caelum.vraptor.view.PathResolver;
import br.com.caelum.vraptor4.ioc.cdi.BeanManagerUtil;
public class CDIProviderRegisteringComponentsTest extends
AbstractProviderRegisteringComponentsTest {
private static CdiContainer cdiContainer;
private final ServletContainerFactory servletContainerFactory = new ServletContainerFactory();
@BeforeClass
public static void startCDIContainer(){
cdiContainer = CdiContainerLoader.getCdiContainer();
cdiContainer.boot();
}
@AfterClass
public static void shutdownCDIContainer() {
cdiContainer.shutdown();
}
public void startContexts() {
cdiContainer.getContextControl().startContexts();
}
public Map<String,Object> getRequestMap(){
try{
Field contextControl = cdiContainer.getContextControl().getClass().getDeclaredField("contextController");
contextControl.setAccessible(true);
ContextController contextController = (ContextController) contextControl.get(cdiContainer.getContextControl());
Field fieldRequestMap = contextController.getClass().getDeclaredField("requestMap");
fieldRequestMap.setAccessible(true);
Map<String, Object> requestMap = (Map<String, Object>) fieldRequestMap.get(contextController);
return requestMap;
}catch(Exception e){
throw new RuntimeException(e);
}
}
public void stopContexts() {
cdiContainer.getContextControl().stopContexts();
}
public void start(Class<? extends Annotation> scope) {
cdiContainer.getContextControl().startContext(scope);
}
public void stop(Class<? extends Annotation> scope) {
cdiContainer.getContextControl().stopContext(scope);
}
@Override
protected ContainerProvider getProvider() {
return CDI.current().select(CDIProvider.class).get();
}
@Override
protected <T> T executeInsideRequest(final WhatToDo<T> execution) {
Callable<T> task = new Callable<T>() {
@Override
public T call() throws Exception {
start(RequestScoped.class);
start(SessionScoped.class);
RequestInfo request = new RequestInfo(context, null,
servletContainerFactory.getRequest(),
servletContainerFactory.getResponse());
T result = execution.execute(request, counter);
stop(SessionScoped.class);
stop(RequestScoped.class);
return result;
}
};
try {
T call = task.call();
return call;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Object actualInstance(Object instance) {
try {
//sorry, but i have to initialize the weld proxy
initializeProxy(instance);
java.lang.reflect.Field field = instance.getClass()
.getDeclaredField("BEAN_INSTANCE_CACHE");
field.setAccessible(true);
ThreadLocal mapa = (ThreadLocal) field.get(instance);
return mapa.get();
} catch (Exception exception) {
return instance;
}
}
@Override
protected <T> T instanceFor(final Class<T> component,
Container container) {
T maybeAWeldProxy = container.instanceFor(component);
return (T)actualInstance(maybeAWeldProxy);
}
@Override
protected void checkSimilarity(Class<?> component, boolean shouldBeTheSame,
Object firstInstance, Object secondInstance) {
if (shouldBeTheSame) {
MatcherAssert.assertThat("Should be the same instance for "
+ component.getName(), actualInstance(firstInstance),
is(equalTo(actualInstance(secondInstance))));
} else {
MatcherAssert.assertThat("Should not be the same instance for "
+ component.getName(), actualInstance(firstInstance),
is(not(equalTo(actualInstance(secondInstance)))));
}
}
@Override
@Test
public void callsPredestroyExactlyOneTime() throws Exception {
MyAppComponentWithLifecycle component = registerAndGetFromContainer(MyAppComponentWithLifecycle.class,
MyAppComponentWithLifecycle.class);
assertThat(component.getCalls(), is(0));
shutdownCDIContainer();
assertThat(component.getCalls(), is(1));
startCDIContainer();
}
@Override
@Test
public void shoudCallPredestroyExactlyOneTimeForComponentsScannedFromTheClasspath() {
CustomComponentWithLifecycleInTheClasspath component = getFromContainer(CustomComponentWithLifecycleInTheClasspath.class);
assertThat(component.getCallsToPreDestroy(), is(equalTo(0)));
shutdownCDIContainer();
assertThat(component.getCallsToPreDestroy(), is(equalTo(1)));
startCDIContainer();
}
@Override
@Test
public void shoudCallPredestroyExactlyOneTimeForComponentFactoriesScannedFromTheClasspath() {
ComponentFactoryInTheClasspath componentFactory = getFromContainer(ComponentFactoryInTheClasspath.class);
assertThat(componentFactory.getCallsToPreDestroy(), is(equalTo(0)));
shutdownCDIContainer();
assertThat(componentFactory.getCallsToPreDestroy(), is(equalTo(1)));
startCDIContainer();
}
@Override
@Ignore
public void setsAnAttributeOnRequestWithTheObjectTypeName() throws Exception {
}
@Override
@Ignore
public void setsAnAttributeOnSessionWithTheObjectTypeName() throws Exception {
}
@Test
public void shouldUseComponentFactoryAsProducer() {
ComponentToBeProduced component = getFromContainer(ComponentToBeProduced.class);
initializeProxy(component);
assertNotNull(component);
}
private void initializeProxy(Object component) {
component.toString();
}
@Test
public void shouldNotAddRequestScopeForComponentWithScope(){
Bean<?> bean = cdiContainer.getBeanManager().getBeans(CDISessionComponent.class).iterator().next();
assertTrue(bean.getScope().equals(SessionScoped.class));
}
@Test
public void shouldStereotypeResourceWithRequestAndNamed(){
Bean<?> bean = cdiContainer.getBeanManager().getBeans(CDIControllerComponent.class).iterator().next();
assertTrue(bean.getScope().equals(RequestScoped.class));
}
@Override
@Test
public void canProvideAllApplicationScopedComponents() {
Set<Class<?>> components = new HashSet<Class<?>>(BaseComponents.getApplicationScoped().keySet());
components.remove(ValidatorFactoryCreator.class);
components.remove(ValidatorCreator.class);
components.remove(MessageInterpolatorFactory.class);
components.remove(MethodValidatorFactoryCreator.class);
checkAvailabilityFor(true, components);
}
@Override
protected void configureExpectations() {
super.configureExpectations();
}
}
|
package crazypants.enderio.base.capacitor;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import crazypants.enderio.api.capacitor.CapabilityCapacitorData;
import crazypants.enderio.api.capacitor.ICapacitorData;
import crazypants.enderio.api.capacitor.ICapacitorKey;
import crazypants.enderio.util.Prep;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagFloat;
public class CapacitorHelper {
private CapacitorHelper() {
}
public static @Nullable ICapacitorData getCapacitorDataFromItemStack(@Nonnull ItemStack stack) {
if (Prep.isInvalid(stack)) {
return null;
}
final ICapacitorData capData = getNBTCapacitorDataFromItemStack(stack);
if (capData != null) {
return capData;
}
return stack.getCapability(CapabilityCapacitorData.getCapNN(), null);
}
public static boolean isValidUpgrade(@Nonnull ItemStack stack) {
if (Prep.isInvalid(stack)) {
return false;
}
final ICapacitorData capData = getNBTCapacitorDataFromItemStack(stack);
if (capData != null) {
return true;
}
return stack.hasCapability(CapabilityCapacitorData.getCapNN(), null);
}
protected static @Nullable ICapacitorData getNBTCapacitorDataFromItemStack(@Nonnull ItemStack stack) {
final NBTTagCompound nbtRoot = stack.getTagCompound();
if (nbtRoot == null) {
return null;
}
if (!nbtRoot.hasKey("eiocap", (new NBTTagCompound()).getId())) {
return null;
}
final NBTTagCompound nbtTag = nbtRoot.getCompoundTag("eiocap");
if (!nbtTag.hasKey("level", (new NBTTagFloat(0)).getId())) {
return null;
}
final float capLevel = nbtTag.getFloat("level");
if (capLevel < 0 || capLevel >= 10) {
return null;
}
return new NBTCapacitorData(stack.getItem().getUnlocalizedName(stack), capLevel, nbtTag);
}
public static enum SetType {
LEVEL,
NAME,
OWNER_TYPE,
TYPE;
}
public static @Nonnull ItemStack addCapData(@Nonnull ItemStack stack, @Nonnull SetType setType, @Nullable ICapacitorKey key, float value) {
NBTTagCompound root = stack.getTagCompound();
if (root == null) {
root = new NBTTagCompound();
stack.setTagCompound(root);
}
NBTTagCompound tag = root.getCompoundTag("eiocap");
root.setTag("eiocap", tag);
if (key == null) {
addCapData(tag, setType, value);
} else {
addCapData(tag, setType, key, value);
}
return stack;
}
private static void addCapData(@Nonnull NBTTagCompound tag, @Nonnull SetType setType, float value) {
switch (setType) {
case LEVEL:
tag.setFloat("level", value);
break;
default:
throw new IllegalArgumentException();
}
}
private static void addCapData(@Nonnull NBTTagCompound tag, @Nonnull SetType setType, @Nonnull ICapacitorKey key, float value) {
switch (setType) {
case NAME:
tag.setFloat(key.getRegistryName().toString(), value);
break;
case OWNER_TYPE:
NBTTagCompound subtag = tag.getCompoundTag(key.getOwner().getUnlocalisedName());
subtag.setFloat(key.getValueType().getName(), value);
tag.setTag(key.getOwner().getUnlocalisedName(), subtag);
break;
case TYPE:
tag.setFloat(key.getValueType().getName(), value);
break;
default:
throw new IllegalArgumentException();
}
}
public static List<Pair<String, Float>> getCapDataRaw(@Nonnull ItemStack stack) {
NBTTagCompound tag = stack.getSubCompound("eiocap");
if (tag == null) {
return null;
}
List<Pair<String, Float>> result = new ArrayList<Pair<String, Float>>();
for (String key : tag.getKeySet()) {
if (key != null && !"level".equals(key) && tag.hasKey(key, (new NBTTagFloat(0)).getId())) {
result.add(Pair.of(key, tag.getFloat(key)));
}
}
return result;
}
public static float getCapLevelRaw(@Nonnull ItemStack stack) {
NBTTagCompound tag = stack.getSubCompound("eiocap");
if (tag == null) {
return 1;
}
return tag.getFloat("level");
}
public static @Nonnull ICapacitorData increaseCapacitorLevel(@Nonnull ICapacitorData data, float level) {
if (data == DefaultCapacitorData.NONE) {
return data;
}
return new ICapacitorData() {
@Override
public float getUnscaledValue(@Nonnull ICapacitorKey key) {
return data.getUnscaledValue(key) > 0 ? data.getUnscaledValue(key) + level : 0;
}
@Nonnull
@Override
public String getUnlocalizedName() {
return data.getUnlocalizedName();
}
@Nonnull
@Override
public String getLocalizedName() {
return data.getUnlocalizedName();
}
};
}
}
|
package com.poguico.palmabici;
import java.util.Calendar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.Toast;
public class StationListActivity extends ActionBarActivity {
private static final long update_time = 600000;
ProgressDialog dialog;
Synchronizer synchronizer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
synchronizer = Synchronizer.getInstance();
StationList station_list = new StationList(this, NetworkInformation.getNetwork());
LinearLayout main_layout_panel = (LinearLayout) findViewById(R.id.main_layout_panel);
main_layout_panel.addView(station_list);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
// Calling super after populating the menu is necessary here to ensure that the
// action bar helpers have a chance to handle this event.
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
break;
case R.id.menu_refresh:
dialog = ProgressDialog.show(this, "", getString(R.string.refresh_ongoing), true);
synchronizer.new SynchronizeTask(this).execute((Void [])null);
break;
case R.id.menu_credits:
new CreditsDialog(this).show();
break;
case R.id.menu_preferences:
Intent preferences_activity = new Intent(this, PreferencesActivity.class);
this.startActivity(preferences_activity);
break;
case R.id.menu_report:
Intent issue_intent = new Intent(Intent.ACTION_VIEW);
issue_intent.setData(Uri.parse("https://github.com/SeGarVi/PalmaBici/issues/new"));
startActivity(issue_intent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onRestart() {
super.onRestart();
SharedPreferences conf=PreferenceManager
.getDefaultSharedPreferences(this);
long now = Calendar.getInstance().getTimeInMillis();
if (conf.getBoolean("autoupdate", true) &&
(now - synchronizer.getLastUpdate()) > update_time) {
dialog = ProgressDialog.show(this, "",getString(R.string.refresh_ongoing), true);
synchronizer.new SynchronizeTask(this).execute((Void [])null);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
DatabaseManager.saveFavouriteStations(NetworkInformation.getNetwork());
}
@Override
public void successfulSynchronization() {
if (dialog != null)
dialog.hide();
Toast.makeText(this, R.string.refresh_succesful, Toast.LENGTH_SHORT).show();
StationList station_list = new StationList(this, NetworkInformation.getNetwork());
LinearLayout main_layout_panel = (LinearLayout) findViewById(R.id.main_layout_panel);
main_layout_panel.addView(station_list);
}
@Override
public void unsuccessfulSynchronization() {
Toast.makeText(this, R.string.connectivity_error, Toast.LENGTH_SHORT).show();
}
}
|
package com.jme3.scene.plugins.blender.helpers.v249;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.asset.TextureKey;
import com.jme3.math.FastMath;
import com.jme3.scene.plugins.blender.data.FileBlockHeader;
import com.jme3.scene.plugins.blender.data.Structure;
import com.jme3.scene.plugins.blender.exception.BlenderFileException;
import com.jme3.scene.plugins.blender.helpers.NoiseHelper;
import com.jme3.scene.plugins.blender.utils.AbstractBlenderHelper;
import com.jme3.scene.plugins.blender.utils.BlenderInputStream;
import com.jme3.scene.plugins.blender.utils.DataRepository;
import com.jme3.scene.plugins.blender.utils.DataRepository.LoadedFeatureDataType;
import com.jme3.scene.plugins.blender.utils.DynamicArray;
import com.jme3.scene.plugins.blender.utils.Pointer;
import com.jme3.texture.Image;
import com.jme3.texture.Image.Format;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.texture.Texture2D;
import com.jme3.texture.plugins.AWTLoader;
import com.jme3.texture.plugins.DDSLoader;
import com.jme3.texture.plugins.TGALoader;
import com.jme3.util.BufferUtils;
/**
* A class that is used in texture calculations.
*
* @author Marcin Roguski
*/
public class TextureHelper extends AbstractBlenderHelper {
private static final Logger LOGGER = Logger.getLogger(TextureHelper.class.getName());
// texture types
public static final int TEX_NONE = 0;
public static final int TEX_CLOUDS = 1;
public static final int TEX_WOOD = 2;
public static final int TEX_MARBLE = 3;
public static final int TEX_MAGIC = 4;
public static final int TEX_BLEND = 5;
public static final int TEX_STUCCI = 6;
public static final int TEX_NOISE = 7;
public static final int TEX_IMAGE = 8;
public static final int TEX_PLUGIN = 9;
public static final int TEX_ENVMAP = 10;
public static final int TEX_MUSGRAVE = 11;
public static final int TEX_VORONOI = 12;
public static final int TEX_DISTNOISE = 13;
// mapto
public static final int MAP_COL = 1;
public static final int MAP_NORM = 2;
public static final int MAP_COLSPEC = 4;
public static final int MAP_COLMIR = 8;
public static final int MAP_VARS = 0xFFF0;
public static final int MAP_REF = 16;
public static final int MAP_SPEC = 32;
public static final int MAP_EMIT = 64;
public static final int MAP_ALPHA = 128;
public static final int MAP_HAR = 256;
public static final int MAP_RAYMIRR = 512;
public static final int MAP_TRANSLU = 1024;
public static final int MAP_AMB = 2048;
public static final int MAP_DISPLACE = 4096;
public static final int MAP_WARP = 8192;
public static final int MAP_LAYER = 16384;
// blendtypes
public static final int MTEX_BLEND = 0;
public static final int MTEX_MUL = 1;
public static final int MTEX_ADD = 2;
public static final int MTEX_SUB = 3;
public static final int MTEX_DIV = 4;
public static final int MTEX_DARK = 5;
public static final int MTEX_DIFF = 6;
public static final int MTEX_LIGHT = 7;
public static final int MTEX_SCREEN = 8;
public static final int MTEX_OVERLAY = 9;
public static final int MTEX_BLEND_HUE = 10;
public static final int MTEX_BLEND_SAT = 11;
public static final int MTEX_BLEND_VAL = 12;
public static final int MTEX_BLEND_COLOR = 13;
public static final int MTEX_NUM_BLENDTYPES = 14;
// variables used in rampBlend method
public static final int MA_RAMP_BLEND = 0;
public static final int MA_RAMP_ADD = 1;
public static final int MA_RAMP_MULT = 2;
public static final int MA_RAMP_SUB = 3;
public static final int MA_RAMP_SCREEN = 4;
public static final int MA_RAMP_DIV = 5;
public static final int MA_RAMP_DIFF = 6;
public static final int MA_RAMP_DARK = 7;
public static final int MA_RAMP_LIGHT = 8;
public static final int MA_RAMP_OVERLAY = 9;
public static final int MA_RAMP_DODGE = 10;
public static final int MA_RAMP_BURN = 11;
public static final int MA_RAMP_HUE = 12;
public static final int MA_RAMP_SAT = 13;
public static final int MA_RAMP_VAL = 14;
public static final int MA_RAMP_COLOR = 15;
/**
* This constructor parses the given blender version and stores the result. Some functionalities may differ in different blender
* versions.
*
* @param blenderVersion
* the version read from the blend file
*/
public TextureHelper(String blenderVersion) {
super(blenderVersion);
}
/**
* This class returns a texture read from the file or from packed blender data. The returned texture has the name set to the value of
* its blender type.
*
* @param tex
* texture structure filled with data
* @param dataRepository
* the data repository
* @return the texture that can be used by JME engine
* @throws BlenderFileException
* this exception is thrown when the blend file structure is somehow invalid or corrupted
*/
public Texture getTexture(Structure tex, DataRepository dataRepository) throws BlenderFileException {
Texture result = (Texture) dataRepository.getLoadedFeature(tex.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE);
if (result != null) {
return result;
}
int type = ((Number) tex.getFieldValue("type")).intValue();
int width = dataRepository.getBlenderKey().getGeneratedTextureWidth();
int height = dataRepository.getBlenderKey().getGeneratedTextureHeight();
switch (type) {
case TEX_NONE:// No texture, do nothing
break;
case TEX_IMAGE:// (it is first because probably this will be most commonly used)
Pointer pImage = (Pointer) tex.getFieldValue("ima");
Structure image = pImage.fetchData(dataRepository.getInputStream()).get(0);
result = this.getTextureFromImage(image, dataRepository);
break;
case TEX_CLOUDS:
result = this.clouds(tex, width, height, dataRepository);
break;
case TEX_WOOD:
result = this.wood(tex, width, height, dataRepository);
break;
case TEX_MARBLE:
result = this.marble(tex, width, height, dataRepository);
break;
case TEX_MAGIC:
result = this.magic(tex, width, height, dataRepository);
break;
case TEX_BLEND:
result = this.blend(tex, width, height, dataRepository);
break;
case TEX_STUCCI:
result = this.stucci(tex, width, height, dataRepository);
break;
case TEX_NOISE:
result = this.texnoise(tex, width, height, dataRepository);
break;
case TEX_MUSGRAVE:
result = this.musgrave(tex, width, height, dataRepository);
break;
case TEX_VORONOI:
result = this.voronoi(tex, width, height, dataRepository);
break;
case TEX_DISTNOISE:
result = this.distnoise(tex, width, height, dataRepository);
break;
case TEX_PLUGIN:
case TEX_ENVMAP:// TODO: implement envmap texture
LOGGER.log(Level.WARNING, "Unsupported texture type: " + type + " for texture: " + tex.getName());
break;
default:
throw new BlenderFileException("Unknown texture type: " + type + " for texture: " + tex.getName());
}
if (result != null) {
result.setName(tex.getName());
result.setWrap(WrapMode.Repeat);
}
return result;
}
/**
* This method generates the clouds texture. The result is one pixel.
*
* @param tex
* the texture structure
* @param width
* the width of texture (in pixels)
* @param height
* the height of texture (in pixels)
* @param dataRepository
* the data repository
* @return generated texture
*/
protected Texture clouds(Structure tex, int width, int height, DataRepository dataRepository) {
// preparing the proper data
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float wDelta = 1.0f / width, hDelta = 1.0f / height;
float[] texvec = new float[] { 0, 0, 0 };
TexResult texres = new TexResult();
// reading the data from the texture structure
float noisesize = ((Number) tex.getFieldValue("noisesize")).floatValue();
int noiseDepth = ((Number) tex.getFieldValue("noisedepth")).intValue();
int noiseBasis = ((Number) tex.getFieldValue("noisebasis")).intValue();
int noiseType = ((Number) tex.getFieldValue("noisetype")).intValue();
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float bright = ((Number) tex.getFieldValue("bright")).floatValue();
boolean isHard = noiseType != com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_NOISESOFT;
int sType = ((Number) tex.getFieldValue("stype")).intValue();
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = sType == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_COLOR || colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = sType == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_COLOR || colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j;// y (z is always = 0)
texres.tin = noiseHelper.bliGTurbulence(noisesize, texvec[0], texvec[1], texvec[2], noiseDepth, isHard, noiseBasis);
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
if (texres.nor != null) {
float nabla = ((Number) tex.getFieldValue("nabla")).floatValue();
// calculate bumpnormal
texres.nor[0] = noiseHelper.bliGTurbulence(noisesize, texvec[0] + nabla, texvec[1], texvec[2], noiseDepth, isHard, noiseBasis);
texres.nor[1] = noiseHelper.bliGTurbulence(noisesize, texvec[0], texvec[1] + nabla, texvec[2], noiseDepth, isHard, noiseBasis);
texres.nor[2] = noiseHelper.bliGTurbulence(noisesize, texvec[0], texvec[1], texvec[2] + nabla, noiseDepth, isHard, noiseBasis);
noiseHelper.texNormalDerivate(colorBand, texres, dataRepository);
}
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else if (sType == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_COLOR) {
// in this case, int. value should really be computed from color,
// and bumpnormal from that, would be too slow, looks ok as is
texres.tr = texres.tin;
texres.tg = noiseHelper.bliGTurbulence(noisesize, texvec[1], texvec[0], texvec[2], noiseDepth, isHard, noiseBasis);
texres.tb = noiseHelper.bliGTurbulence(noisesize, texvec[1], texvec[2], texvec[0], noiseDepth, isHard, noiseBasis);
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, bright);
data.put((byte) (texres.tin * 255));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the wood texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture wood(Structure tex, int width, int height, DataRepository dataRepository) {
// preparing the proper data
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float bright = ((Number) tex.getFieldValue("bright")).floatValue();
float nabla = ((Number) tex.getFieldValue("nabla")).floatValue();
float wDelta = 1.0f / width, hDelta = 1.0f / height;
float[] texvec = new float[] { 0, 0, 0 };
TexResult texres = new TexResult();
int halfW = width;
int halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j;
texres.tin = noiseHelper.woodInt(tex, texvec[0], texvec[1], texvec[2], dataRepository);
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
if (texres.nor != null) {// calculate bumpnormal
texres.nor[0] = noiseHelper.woodInt(tex, texvec[0] + nabla, texvec[1], texvec[2], dataRepository);
texres.nor[1] = noiseHelper.woodInt(tex, texvec[0], texvec[1] + nabla, texvec[2], dataRepository);
texres.nor[2] = noiseHelper.woodInt(tex, texvec[0], texvec[1], texvec[2] + nabla, dataRepository);
noiseHelper.texNormalDerivate(colorBand, texres, dataRepository);
}
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, bright);
data.put((byte) (texres.tin * 255));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the marble texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture marble(Structure tex, int width, int height, DataRepository dataRepository) {
// preparing the proper data
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float bright = ((Number) tex.getFieldValue("bright")).floatValue();
float nabla = ((Number) tex.getFieldValue("nabla")).floatValue();
float wDelta = 1.0f / width, hDelta = 1.0f / height;
float[] texvec = new float[] { 0, 0, 0 };
TexResult texres = new TexResult();
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j;
texres.tin = noiseHelper.marbleInt(tex, texvec[0], texvec[1], texvec[2], dataRepository);
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
if (texres.nor != null) {// calculate bumpnormal
texres.nor[0] = noiseHelper.marbleInt(tex, texvec[0] + nabla, texvec[1], texvec[2], dataRepository);
texres.nor[1] = noiseHelper.marbleInt(tex, texvec[0], texvec[1] + nabla, texvec[2], dataRepository);
texres.nor[2] = noiseHelper.marbleInt(tex, texvec[0], texvec[1], texvec[2] + nabla, dataRepository);
noiseHelper.texNormalDerivate(colorBand, texres, dataRepository);
}
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, bright);
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the magic texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture magic(Structure tex, int width, int height, DataRepository dataRepository) {
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float x, y, z, turb;
int noisedepth = ((Number) tex.getFieldValue("noisedepth")).intValue();
float turbul = ((Number) tex.getFieldValue("turbul")).floatValue() / 5.0f;
float[] texvec = new float[] { 0, 0, 0 };
TexResult texres = new TexResult();
float wDelta = 1.0f / width, hDelta = 1.0f / height;
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
ByteBuffer data = BufferUtils.createByteBuffer(width * height * 4);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i;
for (int j = -halfH; j < halfH; ++j) {
turb = turbul;
texvec[1] = hDelta * j;
x = (float) Math.sin((texvec[0] + texvec[1]) * 5.0f);// in blender: Math.sin((texvec[0] + texvec[1] + texvec[2]) * 5.0f);
y = (float) Math.cos((-texvec[0] + texvec[1]) * 5.0f);// in blender: Math.cos((-texvec[0] + texvec[1] - texvec[2]) * 5.0f);
z = -(float) Math.cos((-texvec[0] - texvec[1]) * 5.0f);// in blender: Math.cos((-texvec[0] - texvec[1] + texvec[2]) * 5.0f);
if (colorBand != null) {
texres.tin = 0.3333f * (x + y + z);
noiseHelper.doColorband(colorBand, texres, dataRepository);
} else {
if (noisedepth > 0) {
x *= turb;
y *= turb;
z *= turb;
y = -(float) Math.cos(x - y + z) * turb;
if (noisedepth > 1) {
x = (float) Math.cos(x - y - z) * turb;
if (noisedepth > 2) {
z = (float) Math.sin(-x - y - z) * turb;
if (noisedepth > 3) {
x = -(float) Math.cos(-x + y - z) * turb;
if (noisedepth > 4) {
y = -(float) Math.sin(-x + y + z) * turb;
if (noisedepth > 5) {
y = -(float) Math.cos(-x + y + z) * turb;
if (noisedepth > 6) {
x = (float) Math.cos(x + y + z) * turb;
if (noisedepth > 7) {
z = (float) Math.sin(x + y - z) * turb;
if (noisedepth > 8) {
x = -(float) Math.cos(-x - y + z) * turb;
if (noisedepth > 9) {
y = -(float) Math.sin(x - y + z) * turb;
}
}
}
}
}
}
}
}
}
}
if (turb != 0.0f) {
turb *= 2.0f;
x /= turb;
y /= turb;
z /= turb;
}
texres.tr = 0.5f - x;
texres.tg = 0.5f - y;
texres.tb = 0.5f - z;
}
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tin * 255));
data.put((byte) (texres.tb * 255));
data.put((byte) (texres.tg * 255));
data.put((byte) (texres.tr * 255));
}
}
return new Texture2D(new Image(Format.ABGR8, width, height, data));
}
/**
* This method generates the blend texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture blend(Structure tex, int width, int height, DataRepository dataRepository) {
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
int flag = ((Number) tex.getFieldValue("flag")).intValue();
int stype = ((Number) tex.getFieldValue("stype")).intValue();
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float brightness = ((Number) tex.getFieldValue("bright")).floatValue();
float wDelta = 1.0f / width, hDelta = 1.0f / height, x, y, t;
float[] texvec = new float[] { 0, 0, 0 };
TexResult texres = new TexResult();
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j;
if ((flag & com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_FLIPBLEND) != 0) {
x = texvec[1];
y = texvec[0];
} else {
x = texvec[0];
y = texvec[1];
}
if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_LIN) { /* lin */
texres.tin = (1.0f + x) / 2.0f;
} else if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_QUAD) { /* quad */
texres.tin = (1.0f + x) / 2.0f;
if (texres.tin < 0.0f) {
texres.tin = 0.0f;
} else {
texres.tin *= texres.tin;
}
} else if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_EASE) { /* ease */
texres.tin = (1.0f + x) / 2.0f;
if (texres.tin <= 0.0f) {
texres.tin = 0.0f;
} else if (texres.tin >= 1.0f) {
texres.tin = 1.0f;
} else {
t = texres.tin * texres.tin;
texres.tin = 3.0f * t - 2.0f * t * texres.tin;
}
} else if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_DIAG) { /* diag */
texres.tin = (2.0f + x + y) / 4.0f;
} else if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_RAD) { /* radial */
texres.tin = (float) Math.atan2(y, x) / FastMath.TWO_PI + 0.5f;
} else { /* sphere TEX_SPHERE */
texres.tin = 1.0f - (float) Math.sqrt(x * x + y * y + texvec[2] * texvec[2]);
if (texres.tin < 0.0f) {
texres.tin = 0.0f;
}
if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_HALO) {
texres.tin *= texres.tin;
} /* halo */
}
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, brightness);
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the stucci texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture stucci(Structure tex, int width, int height, DataRepository dataRepository) {
float noisesize = ((Number) tex.getFieldValue("noisesize")).floatValue();
int noisebasis = ((Number) tex.getFieldValue("noisebasis")).intValue();
int noisetype = ((Number) tex.getFieldValue("noisetype")).intValue();
float turbul = ((Number) tex.getFieldValue("turbul")).floatValue();
boolean isHard = noisetype != com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_NOISESOFT;
int stype = ((Number) tex.getFieldValue("stype")).intValue();
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float[] texvec = new float[] { 0, 0, 0 };
TexResult texres = new TexResult();
float wDelta = 1.0f / width, hDelta = 1.0f / height, b2, ofs;
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j;// y (z is always = 0)
b2 = noiseHelper.bliGNoise(noisesize, texvec[0], texvec[1], texvec[2], isHard, noisebasis);
ofs = turbul / 200.0f;
if (stype != 0) {
ofs *= b2 * b2;
}
texres.tin = noiseHelper.bliGNoise(noisesize, texvec[0], texvec[1], texvec[2] + ofs, isHard, noisebasis);// ==nor[2]
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
if (texres.nor != null) {
texres.nor[0] = noiseHelper.bliGNoise(noisesize, texvec[0] + ofs, texvec[1], texvec[2], isHard, noisebasis);
texres.nor[1] = noiseHelper.bliGNoise(noisesize, texvec[0], texvec[1] + ofs, texvec[2], isHard, noisebasis);
texres.nor[2] = texres.tin;
noiseHelper.texNormalDerivate(colorBand, texres, dataRepository);
if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_WALLOUT) {
texres.nor[0] = -texres.nor[0];
texres.nor[1] = -texres.nor[1];
texres.nor[2] = -texres.nor[2];
}
}
}
if (stype == com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_WALLOUT) {
texres.tin = 1.0f - texres.tin;
}
if (texres.tin < 0.0f) {
texres.tin = 0.0f;
}
if (colorBand != null) {
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the noise texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
// TODO: correct this one, so it looks more like the texture generated by blender
protected Texture texnoise(Structure tex, int width, int height, DataRepository dataRepository) {
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float div = 3.0f;
int val, ran, loop;
int noisedepth = ((Number) tex.getFieldValue("noisedepth")).intValue();
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float brightness = ((Number) tex.getFieldValue("bright")).floatValue();
TexResult texres = new TexResult();
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
for (int j = -halfH; j < halfH; ++j) {
ran = FastMath.rand.nextInt();// BLI_rand();
val = ran & 3;
loop = noisedepth;
while (loop
ran = ran >> 2;
val *= ran & 3;
div *= 3.0f;
}
texres.tin = val;// / div;
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, brightness);
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the musgrave texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture musgrave(Structure tex, int width, int height, DataRepository dataRepository) {
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
int stype = ((Number) tex.getFieldValue("stype")).intValue();
float noisesize = ((Number) tex.getFieldValue("noisesize")).floatValue();
TexResult texres = new TexResult();
float[] texvec = new float[] { 0, 0, 0 };
float wDelta = 1.0f / width, hDelta = 1.0f / height;
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i / noisesize;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j / noisesize;
switch (stype) {
case com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_MFRACTAL:
case com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_FBM:
noiseHelper.mgMFractalOrfBmTex(tex, texvec, colorBand, texres, dataRepository);
break;
case com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_RIDGEDMF:
case com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_HYBRIDMF:
noiseHelper.mgRidgedOrHybridMFTex(tex, texvec, colorBand, texres, dataRepository);
break;
case com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_HTERRAIN:
noiseHelper.mgHTerrainTex(tex, texvec, colorBand, texres, dataRepository);
break;
default:
throw new IllegalStateException("Unknown type of musgrave texture: " + stype);
}
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the voronoi texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture voronoi(Structure tex, int width, int height, DataRepository dataRepository) {
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float vn_w1 = ((Number) tex.getFieldValue("vn_w1")).floatValue();
float vn_w2 = ((Number) tex.getFieldValue("vn_w2")).floatValue();
float vn_w3 = ((Number) tex.getFieldValue("vn_w3")).floatValue();
float vn_w4 = ((Number) tex.getFieldValue("vn_w4")).floatValue();
float noisesize = ((Number) tex.getFieldValue("noisesize")).floatValue();
float nabla = ((Number) tex.getFieldValue("nabla")).floatValue();
float ns_outscale = ((Number) tex.getFieldValue("ns_outscale")).floatValue();
float vn_mexp = ((Number) tex.getFieldValue("vn_mexp")).floatValue();
int vn_distm = ((Number) tex.getFieldValue("vn_distm")).intValue();
int vn_coltype = ((Number) tex.getFieldValue("vn_coltype")).intValue();
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float brightness = ((Number) tex.getFieldValue("bright")).floatValue();
TexResult texres = new TexResult();
float[] texvec = new float[] { 0, 0, 0 };
float wDelta = 1.0f / width, hDelta = 1.0f / height;
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = vn_coltype != 0 || colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = vn_coltype != 0 || colorBand != null ? 3 : 1;
float[] da = new float[4], pa = new float[12]; /* distance and point coordinate arrays of 4 nearest neighbours */
float[] ca = vn_coltype != 0 ? new float[3] : null; // cell color
float aw1 = FastMath.abs(vn_w1);
float aw2 = FastMath.abs(vn_w2);
float aw3 = FastMath.abs(vn_w3);
float aw4 = FastMath.abs(vn_w4);
float sc = aw1 + aw2 + aw3 + aw4;
if (sc != 0.f) {
sc = ns_outscale / sc;
}
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i / noisesize;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j / noisesize;
noiseHelper.voronoi(texvec[0], texvec[1], texvec[2], da, pa, vn_mexp, vn_distm);
texres.tin = sc * FastMath.abs(vn_w1 * da[0] + vn_w2 * da[1] + vn_w3 * da[2] + vn_w4 * da[3]);
if (vn_coltype != 0) {
noiseHelper.cellNoiseV(pa[0], pa[1], pa[2], ca);
texres.tr = aw1 * ca[0];
texres.tg = aw1 * ca[1];
texres.tb = aw1 * ca[2];
noiseHelper.cellNoiseV(pa[3], pa[4], pa[5], ca);
texres.tr += aw2 * ca[0];
texres.tg += aw2 * ca[1];
texres.tb += aw2 * ca[2];
noiseHelper.cellNoiseV(pa[6], pa[7], pa[8], ca);
texres.tr += aw3 * ca[0];
texres.tg += aw3 * ca[1];
texres.tb += aw3 * ca[2];
noiseHelper.cellNoiseV(pa[9], pa[10], pa[11], ca);
texres.tr += aw4 * ca[0];
texres.tg += aw4 * ca[1];
texres.tb += aw4 * ca[2];
if (vn_coltype >= 2) {
float t1 = (da[1] - da[0]) * 10.0f;
if (t1 > 1) {
t1 = 1.0f;
}
if (vn_coltype == 3) {
t1 *= texres.tin;
} else {
t1 *= sc;
}
texres.tr *= t1;
texres.tg *= t1;
texres.tb *= t1;
} else {
texres.tr *= sc;
texres.tg *= sc;
texres.tb *= sc;
}
}
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
if (texres.nor != null) {
float offs = nabla / noisesize; // also scaling of texvec
// calculate bumpnormal
noiseHelper.voronoi(texvec[0] + offs, texvec[1], texvec[2], da, pa, vn_mexp, vn_distm);
texres.nor[0] = sc * FastMath.abs(vn_w1 * da[0] + vn_w2 * da[1] + vn_w3 * da[2] + vn_w4 * da[3]);
noiseHelper.voronoi(texvec[0], texvec[1] + offs, texvec[2], da, pa, vn_mexp, vn_distm);
texres.nor[1] = sc * FastMath.abs(vn_w1 * da[0] + vn_w2 * da[1] + vn_w3 * da[2] + vn_w4 * da[3]);
noiseHelper.voronoi(texvec[0], texvec[1], texvec[2] + offs, da, pa, vn_mexp, vn_distm);
texres.nor[2] = sc * FastMath.abs(vn_w1 * da[0] + vn_w2 * da[1] + vn_w3 * da[2] + vn_w4 * da[3]);
noiseHelper.texNormalDerivate(colorBand, texres, dataRepository);
}
}
if (vn_coltype != 0 || colorBand != null) {
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));// tin or tr??
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, brightness);
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method generates the distorted noise texture.
*
* @param tex
* the texture structure
* @param width
* the width of the texture
* @param height
* the height of the texture
* @param dataRepository
* the data repository
* @return the generated texture
*/
protected Texture distnoise(Structure tex, int width, int height, DataRepository dataRepository) {
NoiseHelper noiseHelper = dataRepository.getHelper(NoiseHelper.class);
float noisesize = ((Number) tex.getFieldValue("noisesize")).floatValue();
float nabla = ((Number) tex.getFieldValue("nabla")).floatValue();
float distAmount = ((Number) tex.getFieldValue("dist_amount")).floatValue();
int noisebasis = ((Number) tex.getFieldValue("noisebasis")).intValue();
int noisebasis2 = ((Number) tex.getFieldValue("noisebasis2")).intValue();
float contrast = ((Number) tex.getFieldValue("contrast")).floatValue();
float brightness = ((Number) tex.getFieldValue("bright")).floatValue();
TexResult texres = new TexResult();
float[] texvec = new float[] { 0, 0, 0 };
float wDelta = 1.0f / width, hDelta = 1.0f / height;
int halfW = width, halfH = height;
width <<= 1;
height <<= 1;
ColorBand colorBand = this.readColorband(tex, dataRepository);
Format format = colorBand != null ? Format.RGB8 : Format.Luminance8;
int bytesPerPixel = colorBand != null ? 3 : 1;
ByteBuffer data = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
for (int i = -halfW; i < halfW; ++i) {
texvec[0] = wDelta * i / noisesize;
for (int j = -halfH; j < halfH; ++j) {
texvec[1] = hDelta * j / noisesize;
texres.tin = noiseHelper.mgVLNoise(texvec[0], texvec[1], texvec[2], distAmount, noisebasis, noisebasis2);
if (colorBand != null) {
noiseHelper.doColorband(colorBand, texres, dataRepository);
if (texres.nor != null) {
float offs = nabla / noisesize; // also scaling of texvec
/* calculate bumpnormal */
texres.nor[0] = noiseHelper.mgVLNoise(texvec[0] + offs, texvec[1], texvec[2], distAmount, noisebasis, noisebasis2);
texres.nor[1] = noiseHelper.mgVLNoise(texvec[0], texvec[1] + offs, texvec[2], distAmount, noisebasis, noisebasis2);
texres.nor[2] = noiseHelper.mgVLNoise(texvec[0], texvec[1], texvec[2] + offs, distAmount, noisebasis, noisebasis2);
noiseHelper.texNormalDerivate(colorBand, texres, dataRepository);
}
noiseHelper.brightnesAndContrastRGB(tex, texres);
data.put((byte) (texres.tr * 255.0f));
data.put((byte) (texres.tg * 255.0f));
data.put((byte) (texres.tb * 255.0f));
} else {
noiseHelper.brightnesAndContrast(texres, contrast, brightness);
data.put((byte) (texres.tin * 255.0f));
}
}
}
return new Texture2D(new Image(format, width, height, data));
}
/**
* This method reads the colorband data from the given texture structure.
*
* @param tex
* the texture structure
* @param dataRepository
* the data repository
* @return read colorband or null if not present
*/
protected ColorBand readColorband(Structure tex, DataRepository dataRepository) {
ColorBand result = null;
int flag = ((Number) tex.getFieldValue("flag")).intValue();
if ((flag & com.jme3.scene.plugins.blender.helpers.v249.NoiseHelper.TEX_COLORBAND) != 0) {
Pointer pColorband = (Pointer) tex.getFieldValue("coba");
Structure colorbandStructure;
try {
colorbandStructure = pColorband.fetchData(dataRepository.getInputStream()).get(0);
result = new ColorBand(colorbandStructure);
} catch (BlenderFileException e) {
LOGGER.warning("Cannot fetch the colorband structure. The reason: " + e.getLocalizedMessage());
// TODO: throw an exception here ???
}
}
return result;
}
/**
* This method blends the given texture with material color and the defined color in 'map to' panel. As a result of this method a new
* texture is created. The input texture is NOT.
*
* @param materialColor
* the material diffuse color
* @param texture
* the texture we use in blending
* @param color
* the color defined for the texture
* @param affectFactor
* the factor that the color affects the texture (value form 0.0 to 1.0)
* @param blendType
* the blending type
* @param dataRepository
* the data repository
* @return new texture that was created after the blending
*/
public Texture blendTexture(float[] materialColor, Texture texture, float[] color, float affectFactor, int blendType, boolean neg, DataRepository dataRepository) {
float[] materialColorClone = materialColor.clone();//this array may change, so we copy it
Format format = texture.getImage().getFormat();
ByteBuffer data = texture.getImage().getData(0);
data.rewind();
int width = texture.getImage().getWidth();
int height = texture.getImage().getHeight();
ByteBuffer newData = BufferUtils.createByteBuffer(width * height * 3);
float[] resultPixel = new float[3];
int dataIndex = 0;
while (data.hasRemaining()) {
float tin = this.setupMaterialColor(data, format, neg, materialColorClone);
this.blendPixel(resultPixel, materialColorClone, color, tin, affectFactor, blendType, dataRepository);
newData.put(dataIndex++, (byte) (resultPixel[0] * 255.0f));
newData.put(dataIndex++, (byte) (resultPixel[1] * 255.0f));
newData.put(dataIndex++, (byte) (resultPixel[2] * 255.0f));
}
return new Texture2D(new Image(Format.RGB8, width, height, newData));
}
/**
* This method alters the material color in a way dependent on the type of the image.
* For example the color remains untouched if the texture is of Luminance type.
* The luminance defines the interaction between the material color and color defined
* for texture blending.
* If the type has 3 or more color channels then the material color is replaces with the texture's
* color and later blended with the defined blend color.
* All alpha values (if present) are ignored and not used during blending.
* @param data
* the image data
* @param imageFormat
* the format of the image
* @param neg
* defines it the result color should be nagated
* @param materialColor
* the material's color (value may be changed)
* @return texture intensity for the current pixel
*/
protected float setupMaterialColor(ByteBuffer data, Format imageFormat, boolean neg, float[] materialColor) {
// at least one byte is always taken :)
float tin = 0.0f;
byte pixelValue = data.get();
float firstPixelValue = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
switch (imageFormat) {
case ABGR8:
pixelValue = data.get();
materialColor[2] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
pixelValue = data.get();
materialColor[1] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
pixelValue = data.get();
materialColor[0] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
break;
case BGR8:
materialColor[2] = firstPixelValue;
pixelValue = data.get();
materialColor[1] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
pixelValue = data.get();
materialColor[0] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
break;
case RGB8:
materialColor[0] = firstPixelValue;
pixelValue = data.get();
materialColor[1] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
pixelValue = data.get();
materialColor[2] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
break;
case RGBA8:
materialColor[0] = firstPixelValue;
pixelValue = data.get();
materialColor[1] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
pixelValue = data.get();
materialColor[2] = pixelValue >= 0 ? 1.0f - pixelValue / 255.0f : (~pixelValue + 1) / 255.0f;
data.get(); // ignore alpha
break;
case Luminance8:
tin = neg ? 1.0f - firstPixelValue : firstPixelValue;
neg = false;//do not negate the materialColor, it must be unchanged
break;
case Luminance8Alpha8:
tin = neg ? 1.0f - firstPixelValue : firstPixelValue;
neg = false;//do not negate the materialColor, it must be unchanged
data.get(); // ignore alpha
break;
case Luminance16:
case Luminance16Alpha16:
case Alpha16:
case Alpha8:
case ARGB4444:
case Depth:
case Depth16:
case Depth24:
case Depth32:
case Depth32F:
case DXT1:
case DXT1A:
case DXT3:
case DXT5:
case Intensity16:
case Intensity8:
case LATC:
case LTC:
case Luminance16F:
case Luminance16FAlpha16F:
case Luminance32F:
case RGB10:
case RGB111110F:
case RGB16:
case RGB16F:
case RGB16F_to_RGB111110F:
case RGB16F_to_RGB9E5:
case RGB32F:
case RGB565:
case RGB5A1:
case RGB9E5:
case RGBA16:
case RGBA16F:
case RGBA32F:
LOGGER.warning("Image type not yet supported for blending: " + imageFormat);
break;
default:
throw new IllegalStateException("Unknown image format type: " + imageFormat);
}
if (neg) {
materialColor[0] = 1.0f - materialColor[0];
materialColor[1] = 1.0f - materialColor[1];
materialColor[2] = 1.0f - materialColor[2];
}
return tin;
}
/**
* This method blends the texture with an appropriate color.
*
* @param result
* the result color (variable 'in' in blender source code)
* @param materialColor
* the texture color (variable 'out' in blender source coude)
* @param color
* the previous color (variable 'tex' in blender source code)
* @param textureIntensity
* texture intensity (variable 'fact' in blender source code)
* @param textureFactor
* texture affection factor (variable 'facg' in blender source code)
* @param blendtype
* the blend type
* @param dataRepository
* the data repository
*/
public void blendPixel(float[] result, float[] materialColor, float[] color, float textureIntensity, float textureFactor, int blendtype, DataRepository dataRepository) {
float facm, col;
switch (blendtype) {
case MTEX_BLEND:
textureIntensity *= textureFactor;
facm = 1.0f - textureIntensity;
result[0] = textureIntensity * color[0] + facm * materialColor[0];
result[1] = textureIntensity * color[1] + facm * materialColor[1];
result[2] = textureIntensity * color[2] + facm * materialColor[2];
break;
case MTEX_MUL:
textureIntensity *= textureFactor;
facm = 1.0f - textureFactor;
result[0] = (facm + textureIntensity * materialColor[0]) * color[0];
result[1] = (facm + textureIntensity * materialColor[1]) * color[1];
result[2] = (facm + textureIntensity * materialColor[2]) * color[2];
break;
case MTEX_DIV:
textureIntensity *= textureFactor;
facm = 1.0f - textureIntensity;
if (color[0] != 0.0) {
result[0] = (facm * materialColor[0] + textureIntensity * materialColor[0] / color[0]) * 0.5f;
}
if (color[1] != 0.0) {
result[1] = (facm * materialColor[1] + textureIntensity * materialColor[1] / color[1]) * 0.5f;
}
if (color[2] != 0.0) {
result[2] = (facm * materialColor[2] + textureIntensity * materialColor[2] / color[2]) * 0.5f;
}
break;
case MTEX_SCREEN:
textureIntensity *= textureFactor;
facm = 1.0f - textureFactor;
result[0] = 1.0f - (facm + textureIntensity * (1.0f - materialColor[0])) * (1.0f - color[0]);
result[1] = 1.0f - (facm + textureIntensity * (1.0f - materialColor[1])) * (1.0f - color[1]);
result[2] = 1.0f - (facm + textureIntensity * (1.0f - materialColor[2])) * (1.0f - color[2]);
break;
case MTEX_OVERLAY:
textureIntensity *= textureFactor;
facm = 1.0f - textureFactor;
if (materialColor[0] < 0.5f) {
result[0] = color[0] * (facm + 2.0f * textureIntensity * materialColor[0]);
} else {
result[0] = 1.0f - (facm + 2.0f * textureIntensity * (1.0f - materialColor[0])) * (1.0f - color[0]);
}
if (materialColor[1] < 0.5f) {
result[1] = color[1] * (facm + 2.0f * textureIntensity * materialColor[1]);
} else {
result[1] = 1.0f - (facm + 2.0f * textureIntensity * (1.0f - materialColor[1])) * (1.0f - color[1]);
}
if (materialColor[2] < 0.5f) {
result[2] = color[2] * (facm + 2.0f * textureIntensity * materialColor[2]);
} else {
result[2] = 1.0f - (facm + 2.0f * textureIntensity * (1.0f - materialColor[2])) * (1.0f - color[2]);
}
break;
case MTEX_SUB:
textureIntensity *= textureFactor;
result[0] = materialColor[0] - textureIntensity * color[0];
result[1] = materialColor[1] - textureIntensity * color[1];
result[2] = materialColor[2] - textureIntensity * color[2];
result[0] = FastMath.clamp(result[0], 0.0f, 1.0f);
result[1] = FastMath.clamp(result[1], 0.0f, 1.0f);
result[2] = FastMath.clamp(result[2], 0.0f, 1.0f);
break;
case MTEX_ADD:
textureIntensity *= textureFactor;
result[0] = (textureIntensity * color[0] + materialColor[0]) * 0.5f;
result[1] = (textureIntensity * color[1] + materialColor[1]) * 0.5f;
result[2] = (textureIntensity * color[2] + materialColor[2]) * 0.5f;
break;
case MTEX_DIFF:
textureIntensity *= textureFactor;
facm = 1.0f - textureIntensity;
result[0] = facm * color[0] + textureIntensity * Math.abs(materialColor[0] - color[0]);
result[1] = facm * color[1] + textureIntensity * Math.abs(materialColor[1] - color[1]);
result[2] = facm * color[2] + textureIntensity * Math.abs(materialColor[2] - color[2]);
break;
case MTEX_DARK:
textureIntensity *= textureFactor;
col = textureIntensity * color[0];
result[0] = col < materialColor[0] ? col : materialColor[0];
col = textureIntensity * color[1];
result[1] = col < materialColor[1] ? col : materialColor[1];
col = textureIntensity * color[2];
result[2] = col < materialColor[2] ? col : materialColor[2];
break;
case MTEX_LIGHT:
textureIntensity *= textureFactor;
col = textureIntensity * color[0];
result[0] = col > materialColor[0] ? col : materialColor[0];
col = textureIntensity * color[1];
result[1] = col > materialColor[1] ? col : materialColor[1];
col = textureIntensity * color[2];
result[2] = col > materialColor[2] ? col : materialColor[2];
break;
case MTEX_BLEND_HUE:
textureIntensity *= textureFactor;
System.arraycopy(materialColor, 0, result, 0, 3);
this.rampBlend(MA_RAMP_HUE, result, textureIntensity, color, dataRepository);
break;
case MTEX_BLEND_SAT:
textureIntensity *= textureFactor;
System.arraycopy(materialColor, 0, result, 0, 3);
this.rampBlend(MA_RAMP_SAT, result, textureIntensity, color, dataRepository);
break;
case MTEX_BLEND_VAL:
textureIntensity *= textureFactor;
System.arraycopy(materialColor, 0, result, 0, 3);
this.rampBlend(MA_RAMP_VAL, result, textureIntensity, color, dataRepository);
break;
case MTEX_BLEND_COLOR:
textureIntensity *= textureFactor;
System.arraycopy(materialColor, 0, result, 0, 3);
this.rampBlend(MA_RAMP_COLOR, result, textureIntensity, color, dataRepository);
break;
default:
throw new IllegalStateException("Unknown blend type: " + blendtype);
}
}
/**
* The method that performs the ramp blending (whatever it is :P - copied from blender sources).
*
* @param type
* the ramp type
* @param rgb
* the rgb value where the result is stored
* @param fac
* color affection factor
* @param col
* the texture color
* @param dataRepository
* the data repository
*/
public void rampBlend(int type, float[] rgb, float fac, float[] col, DataRepository dataRepository) {
float tmp, facm = 1.0f - fac;
MaterialHelper materialHelper = dataRepository.getHelper(MaterialHelper.class);
switch (type) {
case MA_RAMP_HUE:
if (rgb.length == 3) {
float[] colorTransformResult = new float[3];
materialHelper.rgbToHsv(col[0], col[1], col[2], colorTransformResult);
if (colorTransformResult[1] != 0.0f) {
float colH = colorTransformResult[0];
materialHelper.rgbToHsv(rgb[0], rgb[1], rgb[2], colorTransformResult);
materialHelper.hsvToRgb(colH, colorTransformResult[1], colorTransformResult[2], colorTransformResult);
rgb[0] = facm * rgb[0] + fac * colorTransformResult[0];
rgb[1] = facm * rgb[1] + fac * colorTransformResult[1];
rgb[2] = facm * rgb[2] + fac * colorTransformResult[2];
}
}
break;
case MA_RAMP_SAT:
if (rgb.length == 3) {
float[] colorTransformResult = new float[3];
materialHelper.rgbToHsv(rgb[0], rgb[1], rgb[2], colorTransformResult);
float rH = colorTransformResult[0];
float rS = colorTransformResult[1];
float rV = colorTransformResult[2];
if (rS != 0) {
materialHelper.rgbToHsv(col[0], col[1], col[2], colorTransformResult);
materialHelper.hsvToRgb(rH, (facm * rS + fac * colorTransformResult[1]), rV, rgb);
}
}
break;
case MA_RAMP_VAL:
if (rgb.length == 3) {
float[] rgbToHsv = new float[3];
float[] colToHsv = new float[3];
materialHelper.rgbToHsv(rgb[0], rgb[1], rgb[2], rgbToHsv);
materialHelper.rgbToHsv(col[0], col[1], col[2], colToHsv);
materialHelper.hsvToRgb(rgbToHsv[0], rgbToHsv[1], (facm * rgbToHsv[2] + fac * colToHsv[2]), rgb);
}
break;
case MA_RAMP_COLOR:
if (rgb.length == 3) {
float[] rgbToHsv = new float[3];
float[] colToHsv = new float[3];
materialHelper.rgbToHsv(col[0], col[1], col[2], colToHsv);
if (colToHsv[2] != 0) {
materialHelper.rgbToHsv(rgb[0], rgb[1], rgb[2], rgbToHsv);
materialHelper.hsvToRgb(colToHsv[0], colToHsv[1], rgbToHsv[2], rgbToHsv);
rgb[0] = facm * rgb[0] + fac * rgbToHsv[0];
rgb[1] = facm * rgb[1] + fac * rgbToHsv[1];
rgb[2] = facm * rgb[2] + fac * rgbToHsv[2];
}
}
break;
case MA_RAMP_BLEND:
rgb[0] = facm * rgb[0] + fac * col[0];
if (rgb.length == 3) {
rgb[1] = facm * rgb[1] + fac * col[1];
rgb[2] = facm * rgb[2] + fac * col[2];
}
break;
case MA_RAMP_ADD:
rgb[0] += fac * col[0];
if (rgb.length == 3) {
rgb[1] += fac * col[1];
rgb[2] += fac * col[2];
}
break;
case MA_RAMP_MULT:
rgb[0] *= facm + fac * col[0];
if (rgb.length == 3) {
rgb[1] *= facm + fac * col[1];
rgb[2] *= facm + fac * col[2];
}
break;
case MA_RAMP_SCREEN:
rgb[0] = 1.0f - (facm + fac * (1.0f - col[0])) * (1.0f - rgb[0]);
if (rgb.length == 3) {
rgb[1] = 1.0f - (facm + fac * (1.0f - col[1])) * (1.0f - rgb[1]);
rgb[2] = 1.0f - (facm + fac * (1.0f - col[2])) * (1.0f - rgb[2]);
}
break;
case MA_RAMP_OVERLAY:
if (rgb[0] < 0.5f) {
rgb[0] *= facm + 2.0f * fac * col[0];
} else {
rgb[0] = 1.0f - (facm + 2.0f * fac * (1.0f - col[0])) * (1.0f - rgb[0]);
}
if (rgb.length == 3) {
if (rgb[1] < 0.5f) {
rgb[1] *= facm + 2.0f * fac * col[1];
} else {
rgb[1] = 1.0f - (facm + 2.0f * fac * (1.0f - col[1])) * (1.0f - rgb[1]);
}
if (rgb[2] < 0.5f) {
rgb[2] *= facm + 2.0f * fac * col[2];
} else {
rgb[2] = 1.0f - (facm + 2.0f * fac * (1.0f - col[2])) * (1.0f - rgb[2]);
}
}
break;
case MA_RAMP_SUB:
rgb[0] -= fac * col[0];
if (rgb.length == 3) {
rgb[1] -= fac * col[1];
rgb[2] -= fac * col[2];
}
break;
case MA_RAMP_DIV:
if (col[0] != 0.0) {
rgb[0] = facm * rgb[0] + fac * rgb[0] / col[0];
}
if (rgb.length == 3) {
if (col[1] != 0.0) {
rgb[1] = facm * rgb[1] + fac * rgb[1] / col[1];
}
if (col[2] != 0.0) {
rgb[2] = facm * rgb[2] + fac * rgb[2] / col[2];
}
}
break;
case MA_RAMP_DIFF:
rgb[0] = facm * rgb[0] + fac * Math.abs(rgb[0] - col[0]);
if (rgb.length == 3) {
rgb[1] = facm * rgb[1] + fac * Math.abs(rgb[1] - col[1]);
rgb[2] = facm * rgb[2] + fac * Math.abs(rgb[2] - col[2]);
}
break;
case MA_RAMP_DARK:
tmp = fac * col[0];
if (tmp < rgb[0]) {
rgb[0] = tmp;
}
if (rgb.length == 3) {
tmp = fac * col[1];
if (tmp < rgb[1]) {
rgb[1] = tmp;
}
tmp = fac * col[2];
if (tmp < rgb[2]) {
rgb[2] = tmp;
}
}
break;
case MA_RAMP_LIGHT:
tmp = fac * col[0];
if (tmp > rgb[0]) {
rgb[0] = tmp;
}
if (rgb.length == 3) {
tmp = fac * col[1];
if (tmp > rgb[1]) {
rgb[1] = tmp;
}
tmp = fac * col[2];
if (tmp > rgb[2]) {
rgb[2] = tmp;
}
}
break;
case MA_RAMP_DODGE:
if (rgb[0] != 0.0) {
tmp = 1.0f - fac * col[0];
if (tmp <= 0.0) {
rgb[0] = 1.0f;
} else if ((tmp = rgb[0] / tmp) > 1.0) {
rgb[0] = 1.0f;
} else {
rgb[0] = tmp;
}
}
if (rgb.length == 3) {
if (rgb[1] != 0.0) {
tmp = 1.0f - fac * col[1];
if (tmp <= 0.0) {
rgb[1] = 1.0f;
} else if ((tmp = rgb[1] / tmp) > 1.0) {
rgb[1] = 1.0f;
} else {
rgb[1] = tmp;
}
}
if (rgb[2] != 0.0) {
tmp = 1.0f - fac * col[2];
if (tmp <= 0.0) {
rgb[2] = 1.0f;
} else if ((tmp = rgb[2] / tmp) > 1.0) {
rgb[2] = 1.0f;
} else {
rgb[2] = tmp;
}
}
}
break;
case MA_RAMP_BURN:
tmp = facm + fac * col[0];
if (tmp <= 0.0) {
rgb[0] = 0.0f;
} else if ((tmp = 1.0f - (1.0f - rgb[0]) / tmp) < 0.0) {
rgb[0] = 0.0f;
} else if (tmp > 1.0) {
rgb[0] = 1.0f;
} else {
rgb[0] = tmp;
}
if (rgb.length == 3) {
tmp = facm + fac * col[1];
if (tmp <= 0.0) {
rgb[1] = 0.0f;
} else if ((tmp = 1.0f - (1.0f - rgb[1]) / tmp) < 0.0) {
rgb[1] = 0.0f;
} else if (tmp > 1.0) {
rgb[1] = 1.0f;
} else {
rgb[1] = tmp;
}
tmp = facm + fac * col[2];
if (tmp <= 0.0) {
rgb[2] = 0.0f;
} else if ((tmp = 1.0f - (1.0f - rgb[2]) / tmp) < 0.0) {
rgb[2] = 0.0f;
} else if (tmp > 1.0) {
rgb[2] = 1.0f;
} else {
rgb[2] = tmp;
}
}
break;
default:
throw new IllegalStateException("Unknown ramp type: " + type);
}
}
/**
* This class returns a texture read from the file or from packed blender data.
*
* @param image
* image structure filled with data
* @param dataRepository
* the data repository
* @return the texture that can be used by JME engine
* @throws BlenderFileException
* this exception is thrown when the blend file structure is somehow invalid or corrupted
*/
public Texture getTextureFromImage(Structure image, DataRepository dataRepository) throws BlenderFileException {
Texture result = (Texture) dataRepository.getLoadedFeature(image.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE);
if (result == null) {
Pointer pPackedFile = (Pointer) image.getFieldValue("packedfile");
if (pPackedFile.isNull()) {
LOGGER.info("Reading texture from file!");
String imagePath = image.getFieldValue("name").toString();
result = this.loadTextureFromFile(imagePath, dataRepository);
} else {
LOGGER.info("Packed texture. Reading directly from the blend file!");
Structure packedFile = pPackedFile.fetchData(dataRepository.getInputStream()).get(0);
Pointer pData = (Pointer) packedFile.getFieldValue("data");
FileBlockHeader dataFileBlock = dataRepository.getFileBlock(pData.getOldMemoryAddress());
dataRepository.getInputStream().setPosition(dataFileBlock.getBlockPosition());
ImageLoader imageLoader = new ImageLoader();
// Should the texture be flipped? It works for sinbad ..
Image im = imageLoader.loadImage(dataRepository.getInputStream(), dataFileBlock.getBlockPosition(), true);
if (im != null) {
result = new Texture2D(im);
}
}
if (result != null) {
result.setWrap(Texture.WrapMode.Repeat);
dataRepository.addLoadedFeatures(image.getOldMemoryAddress(), image.getName(), image, result);
}
}
return result;
}
/**
* This method loads the textre from outside the blend file.
*
* @param name
* the path to the image
* @param dataRepository
* the data repository
* @return the loaded image or null if the image cannot be found
*/
protected Texture loadTextureFromFile(String name, DataRepository dataRepository) {
Image image = null;
ImageLoader imageLoader = new ImageLoader();
FileInputStream fis = null;
ImageType[] imageTypes = ImageType.values();
// TODO: would be nice to have the model asset key here to getthe models older in the assetmanager
if (name.startsWith("
File modelFolder = new File(dataRepository.getBlenderKey().getName());
File textureFolder = modelFolder.getParentFile();
if (textureFolder != null) {
name = textureFolder.getPath() + "/." + name.substring(1); // replace the // that means "relative" for blender (hopefully)
// with
} else {
name = name.substring(1);
}
TextureKey texKey = new TextureKey(name, false);
try {
Texture tex = dataRepository.getAssetManager().loadTexture(texKey);
image = tex.getImage();
} catch (AssetNotFoundException e) {
LOGGER.warning("Asset nof found: " + e.getLocalizedMessage());
}
}
// 2. Try using the direct path from the blender file
if (image == null) {
File textureFile = new File(name);
if (textureFile.exists() && textureFile.isFile()) {
LOGGER.log(Level.INFO, "Trying with: {0}", name);
try {
for (int i = 0; i < imageTypes.length && image == null; ++i) {
fis = new FileInputStream(textureFile);
image = imageLoader.loadImage(fis, imageTypes[i], false);
this.closeStream(fis);
}
} catch (FileNotFoundException e) {
assert false : e;// this should NEVER happen
} finally {
this.closeStream(fis);
}
}
}
// 3. if 2 failed we start including the parent folder(s) to see if the texture
// can be found
if (image == null) {
String baseName = File.separatorChar != '/' ? name.replace(File.separatorChar, '/') : name;
int idx = baseName.lastIndexOf('/');
while (idx != -1 && image == null) {
String texName = baseName.substring(idx + 1);
File textureFile = new File(texName);
if (textureFile.exists() && textureFile.isFile()) {
LOGGER.info("Trying with: " + texName);
try {
for (int i = 0; i < imageTypes.length && image == null; ++i) {
fis = new FileInputStream(textureFile);
image = imageLoader.loadImage(fis, imageTypes[i], false);
}
} catch (FileNotFoundException e) {
assert false : e;// this should NEVER happen
} finally {
this.closeStream(fis);
}
}
if (idx > 1) {
idx = baseName.lastIndexOf('/', idx - 1);
} else {
idx = -1;
}
}
}
return image == null ? null : new Texture2D(image);
}
/**
* This method closes the given stream.
*
* @param is
* the input stream that is to be closed
*/
protected void closeStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
}
/**
* An image loader class. It uses three loaders (AWTLoader, TGALoader and DDSLoader) in an attempt to load the image from the given
* input stream.
*
* @author Marcin Roguski (Kaelthas)
*/
protected static class ImageLoader extends AWTLoader {
private static final Logger LOGGER = Logger.getLogger(ImageLoader.class.getName());
protected DDSLoader ddsLoader = new DDSLoader(); // DirectX image loader
/**
* This method loads the image from the blender file itself. It tries each loader to load the image.
*
* @param inputStream
* blender input stream
* @param startPosition
* position in the stream where the image data starts
* @param flipY
* if the image should be flipped (does not work with DirectX image)
* @return loaded image or null if it could not be loaded
*/
public Image loadImage(BlenderInputStream inputStream, int startPosition, boolean flipY) {
// loading using AWT loader
inputStream.setPosition(startPosition);
Image result = this.loadImage(inputStream, ImageType.AWT, flipY);
// loading using TGA loader
if (result == null) {
inputStream.setPosition(startPosition);
result = this.loadImage(inputStream, ImageType.TGA, flipY);
}
// loading using DDS loader
if (result == null) {
inputStream.setPosition(startPosition);
result = this.loadImage(inputStream, ImageType.DDS, flipY);
}
if (result == null) {
LOGGER.warning("Image could not be loaded by none of available loaders!");
}
return result;
}
/**
* This method loads an image of a specified type from the given input stream.
*
* @param inputStream
* the input stream we read the image from
* @param imageType
* the type of the image {@link ImageType}
* @param flipY
* if the image should be flipped (does not work with DirectX image)
* @return loaded image or null if it could not be loaded
*/
public Image loadImage(InputStream inputStream, ImageType imageType, boolean flipY) {
Image result = null;
switch (imageType) {
case AWT:
try {
result = this.load(inputStream, flipY);
} catch (Exception e) {
LOGGER.info("Unable to load image using AWT loader!");
}
break;
case DDS:
try {
result = ddsLoader.load(inputStream);
} catch (Exception e) {
LOGGER.info("Unable to load image using DDS loader!");
}
break;
case TGA:
try {
result = TGALoader.load(inputStream, flipY);
} catch (Exception e) {
LOGGER.info("Unable to load image using TGA loader!");
}
break;
default:
throw new IllegalStateException("Unknown image type: " + imageType);
}
return result;
}
}
/**
* Image types that can be loaded. AWT: png, jpg, jped or bmp TGA: tga DDS: DirectX image files
*
* @author Marcin Roguski (Kaelthas)
*/
public static enum ImageType {
AWT, TGA, DDS;
}
/**
* The result pixel of generated texture computations;
*
* @author Marcin Roguski (Kaelthas)
*/
protected static class TexResult implements Cloneable {
public float tin, tr, tg, tb, ta;
public int talpha;
public float[] nor;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/**
* A class constaining the colorband data.
*
* @author Marcin Roguski (Kaelthas)
*/
protected static class ColorBand {
public int flag, tot, cur, ipotype;
public CBData[] data = new CBData[32];
/**
* Constructor. Loads the data from the given structure.
*
* @param cbdataStructure
* the colorband structure
*/
@SuppressWarnings("unchecked")
public ColorBand(Structure colorbandStructure) {
this.flag = ((Number) colorbandStructure.getFieldValue("flag")).intValue();
this.tot = ((Number) colorbandStructure.getFieldValue("tot")).intValue();
this.cur = ((Number) colorbandStructure.getFieldValue("cur")).intValue();
this.ipotype = ((Number) colorbandStructure.getFieldValue("ipotype")).intValue();
DynamicArray<Structure> data = (DynamicArray<Structure>) colorbandStructure.getFieldValue("data");
for (int i = 0; i < data.getTotalSize(); ++i) {
this.data[i] = new CBData(data.get(i));
}
}
}
/**
* Class to store the single colorband unit data.
*
* @author Marcin Roguski (Kaelthas)
*/
protected static class CBData implements Cloneable {
public float r, g, b, a, pos;
public int cur;
/**
* Constructor. Loads the data from the given structure.
*
* @param cbdataStructure
* the structure containing the CBData object
*/
public CBData(Structure cbdataStructure) {
this.r = ((Number) cbdataStructure.getFieldValue("r")).floatValue();
this.g = ((Number) cbdataStructure.getFieldValue("g")).floatValue();
this.b = ((Number) cbdataStructure.getFieldValue("b")).floatValue();
this.a = ((Number) cbdataStructure.getFieldValue("a")).floatValue();
this.pos = ((Number) cbdataStructure.getFieldValue("pos")).floatValue();
this.cur = ((Number) cbdataStructure.getFieldValue("cur")).intValue();
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static class GeneratedTextureData {
public ByteBuffer luminanceData;
public ByteBuffer rgbData;
public Format rgbFormat;
public int width;
public int height;
public GeneratedTextureData(ByteBuffer luminanceData, ByteBuffer rgbData, Format rgbFormat, int width, int height) {
this.luminanceData = luminanceData;
this.rgbData = rgbData;
this.rgbFormat = rgbFormat;
this.width = width;
this.height = height;
}
}
}
|
package org.kuali.kfs.module.ar.service.impl;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.coa.businessobject.Account;
import org.kuali.kfs.coa.businessobject.AccountingPeriod;
import org.kuali.kfs.coa.businessobject.ObjectType;
import org.kuali.kfs.coa.service.AccountService;
import org.kuali.kfs.coa.service.AccountingPeriodService;
import org.kuali.kfs.gl.businessobject.Balance;
import org.kuali.kfs.integration.ar.AccountsReceivableCustomer;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAgency;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAwardAccount;
import org.kuali.kfs.integration.cg.ContractsAndGrantsModuleBillingService;
import org.kuali.kfs.integration.cg.ContractsAndGrantsOrganization;
import org.kuali.kfs.module.ar.ArConstants;
import org.kuali.kfs.module.ar.ArKeyConstants;
import org.kuali.kfs.module.ar.ArParameterKeyConstants;
import org.kuali.kfs.module.ar.ArPropertyConstants;
import org.kuali.kfs.module.ar.batch.service.VerifyBillingFrequencyService;
import org.kuali.kfs.module.ar.businessobject.AccountsReceivableDocumentHeader;
import org.kuali.kfs.module.ar.businessobject.AwardAccountObjectCodeTotalBilled;
import org.kuali.kfs.module.ar.businessobject.Bill;
import org.kuali.kfs.module.ar.businessobject.ContractsGrantsInvoiceDetail;
import org.kuali.kfs.module.ar.businessobject.ContractsGrantsInvoiceDocumentErrorLog;
import org.kuali.kfs.module.ar.businessobject.ContractsGrantsInvoiceDocumentErrorMessage;
import org.kuali.kfs.module.ar.businessobject.ContractsGrantsLetterOfCreditReviewDetail;
import org.kuali.kfs.module.ar.businessobject.CostCategory;
import org.kuali.kfs.module.ar.businessobject.Customer;
import org.kuali.kfs.module.ar.businessobject.CustomerAddress;
import org.kuali.kfs.module.ar.businessobject.InvoiceAccountDetail;
import org.kuali.kfs.module.ar.businessobject.InvoiceAddressDetail;
import org.kuali.kfs.module.ar.businessobject.InvoiceBill;
import org.kuali.kfs.module.ar.businessobject.InvoiceDetailAccountObjectCode;
import org.kuali.kfs.module.ar.businessobject.InvoiceGeneralDetail;
import org.kuali.kfs.module.ar.businessobject.InvoiceMilestone;
import org.kuali.kfs.module.ar.businessobject.Milestone;
import org.kuali.kfs.module.ar.dataaccess.AwardAccountObjectCodeTotalBilledDao;
import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument;
import org.kuali.kfs.module.ar.document.service.AccountsReceivableDocumentHeaderService;
import org.kuali.kfs.module.ar.document.service.ContractsGrantsBillingAwardVerificationService;
import org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService;
import org.kuali.kfs.module.ar.document.service.CustomerService;
import org.kuali.kfs.module.ar.service.ContractsGrantsBillingUtilityService;
import org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService;
import org.kuali.kfs.module.ar.service.CostCategoryService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.FinancialSystemDocumentHeader;
import org.kuali.kfs.sys.businessobject.SystemOptions;
import org.kuali.kfs.sys.document.service.FinancialSystemDocumentService;
import org.kuali.kfs.sys.document.validation.event.DocumentSystemSaveEvent;
import org.kuali.kfs.sys.service.OptionsService;
import org.kuali.kfs.sys.service.UniversityDateService;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kew.api.document.DocumentStatus;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.KualiModuleService;
import org.kuali.rice.krad.util.ErrorMessage;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;
import org.kuali.rice.krad.workflow.service.WorkflowDocumentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
/**
* This is the default implementation of the ContractsGrantsInvoiceDocumentCreateService interface.
*
* @see org.kuali.kfs.module.ar.batch.service.ContractsGrantsInvoiceDocumentCreateService
*/
@Transactional
public class ContractsGrantsInvoiceCreateDocumentServiceImpl implements ContractsGrantsInvoiceCreateDocumentService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ContractsGrantsInvoiceCreateDocumentServiceImpl.class);
protected AccountService accountService;
protected AccountingPeriodService accountingPeriodService;
protected AccountsReceivableDocumentHeaderService accountsReceivableDocumentHeaderService;
protected AwardAccountObjectCodeTotalBilledDao awardAccountObjectCodeTotalBilledDao;
protected BusinessObjectService businessObjectService;
protected ConfigurationService configurationService;
protected ContractsGrantsBillingAwardVerificationService contractsGrantsBillingAwardVerificationService;
protected ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService;
protected ContractsAndGrantsModuleBillingService contractsAndGrantsModuleBillingService;
protected ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService;
protected CostCategoryService costCategoryService;
protected CustomerService customerService;
protected DateTimeService dateTimeService;
protected DocumentService documentService;
protected FinancialSystemDocumentService financialSystemDocumentService;
protected KualiModuleService kualiModuleService;
protected ParameterService parameterService;
protected VerifyBillingFrequencyService verifyBillingFrequencyService;
protected WorkflowDocumentService workflowDocumentService;
protected UniversityDateService universityDateService;
protected OptionsService optionsService;
public static final String REPORT_LINE_DIVIDER = "
/**
* @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#createCGInvoiceDocumentsByAwards(java.util.Collection, org.kuali.kfs.module.ar.ArConstants.ContractsAndGrantsInvoiceDocumentCreationProcessType)
*/
@Override
public List<ErrorMessage> createCGInvoiceDocumentsByAwards(Collection<ContractsAndGrantsBillingAward> awards, ArConstants.ContractsAndGrantsInvoiceDocumentCreationProcessType creationProcessTypeCode) {
List<ErrorMessage> errorMessages = createInvoices(awards, null, null);
if (!CollectionUtils.isEmpty(errorMessages)) {
storeCreationErrors(errorMessages, creationProcessTypeCode.getCode());
}
return errorMessages;
}
/**
* @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#createCGInvoiceDocumentsByAwards(java.util.Collection, java.util.List, java.lang.String)
*/
@Override
public List<ErrorMessage> createCGInvoiceDocumentsByAwards(Collection<ContractsAndGrantsBillingAward> awards, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
List<ErrorMessage> errorMessages = createInvoices(awards, accountDetails, locCreationType);
if (!CollectionUtils.isEmpty(errorMessages)) {
storeCreationErrors(errorMessages, ArConstants.ContractsAndGrantsInvoiceDocumentCreationProcessType.LOC.getCode());
}
return errorMessages;
}
/**
* This method iterates through awards and create cgInvoice documents
* @param awards used to create cgInvoice documents
* @param accountDetails letter of credit details if we're creating via loc
* @param locCreationType letter of credit creation type if we're creating via loc
* @return List of error messages (if any)
*/
protected List<ErrorMessage> createInvoices(Collection<ContractsAndGrantsBillingAward> awards, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>();
if (ObjectUtils.isNotNull(awards) && awards.size() > 0) {
for (ContractsAndGrantsBillingAward awd : awards) {
String invOpt = awd.getInvoicingOptionCode();
final ContractsAndGrantsOrganization awardOrganization = awd.getPrimaryAwardOrganization();
if (ObjectUtils.isNull(awardOrganization)) {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_ORGANIZATION_ON_AWARD, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
} else {
if (invOpt.equals(ArConstants.INV_ACCOUNT)) { // case 1: create Contracts & Grants Invoice by accounts
createInvoicesByAccounts(awd, errorMessages, accountDetails, locCreationType);
}
else if (invOpt.equals(ArConstants.INV_CONTRACT_CONTROL_ACCOUNT)) { // case 2: create Contracts & Grants Invoices by contractControlAccounts
createInvoicesByContractControlAccounts(awd, errorMessages, accountDetails, locCreationType);
}
// case 3: create Contracts & Grants Invoice by award
else if (invOpt.equals(ArConstants.INV_AWARD)) {
createInvoicesByAward(awd, errorMessages, accountDetails, locCreationType);
}
}
}
} else {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_AWARD);
errorMessages.add(errorMessage);
}
return errorMessages;
}
/**
* Generates and saves a single Contracts & Grants Invoice Document based on the given award
* @param awd the award to generate a Contracts & Grants Invoice Document for
* @param errLines a holder for error messages
* @param accountDetails letter of credit details if we're creating via loc
* @param locCreationType letter of credit creation type if we're creating via loc
*/
protected void createInvoicesByAward(ContractsAndGrantsBillingAward awd, List<ErrorMessage> errorMessages, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
// Check if awardaccounts has the same control account
int accountNum = awd.getActiveAwardAccounts().size();
Collection<Account> controlAccounts = getContractsGrantsInvoiceDocumentService().getContractControlAccounts(awd);
if (controlAccounts == null || controlAccounts.size() < accountNum) {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.BILL_BY_CONTRACT_VALID_ACCOUNTS, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
else {
// check if control accounts of awardaccounts are the same
boolean isValid = true;
if (accountNum != 1) {
Set<Account> distinctAwardAccounts = new HashSet<>();
for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) {
if (!ObjectUtils.isNull(awardAccount.getAccount().getContractControlAccount())) {
distinctAwardAccounts.add(awardAccount.getAccount().getContractControlAccount());
}
}
if (distinctAwardAccounts.size() > 1) {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.DIFFERING_CONTROL_ACCOUNTS, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
isValid = false;
}
}
if (isValid) {
String coaCode = null;
String orgCode = null;
for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) {
Account account = awardAccount.getAccount();
coaCode = awd.getPrimaryAwardOrganization().getChartOfAccountsCode();
orgCode = awd.getPrimaryAwardOrganization().getOrganizationCode();
}
// To get valid award accounts of amounts > zero$ and pass it to the create invoices method
if (!getValidAwardAccounts(awd.getActiveAwardAccounts(), awd).containsAll(awd.getActiveAwardAccounts())) {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NOT_ALL_BILLABLE_ACCOUNTS, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
generateAndSaveContractsAndGrantsInvoiceDocument(awd, getValidAwardAccounts(awd.getActiveAwardAccounts(), awd), coaCode, orgCode, errorMessages, accountDetails, locCreationType);
}
}
}
/**
* Generates and saves Contracts & Grants Invoice Documents based on the given award's contract control accounts
* @param awd the award with contract control accounts to build Contracts & Grants Invoice Documents from
* @param errLines a holder for error messages
* @param accountDetails letter of credit details if we're creating via loc
* @param locCreationType letter of credit creation type if we're creating via loc
*/
protected void createInvoicesByContractControlAccounts(ContractsAndGrantsBillingAward awd, List<ErrorMessage> errorMessages, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
List<ContractsAndGrantsBillingAwardAccount> tmpAcctList = new ArrayList<ContractsAndGrantsBillingAwardAccount>();
List<Account> controlAccounts = getContractsGrantsInvoiceDocumentService().getContractControlAccounts(awd);
List<Account> controlAccountsTemp = getContractsGrantsInvoiceDocumentService().getContractControlAccounts(awd);
if (controlAccounts == null || (controlAccounts.size() != awd.getActiveAwardAccounts().size())) {// to check if the number of contract control accounts is same as the number of accounts
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_CONTROL_ACCOUNT, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
else {
Set<Account> controlAccountSet = new HashSet<Account>();
for (int i = 0; i < controlAccountsTemp.size(); i++) {
if (ObjectUtils.isNotNull(controlAccountsTemp.get(i))) {
for (int j = i + 1; j < controlAccounts.size(); j++) {
if (controlAccountsTemp.get(i).equals(controlAccounts.get(j))) {
controlAccounts.set(j, null);
}
}
}
else {
break;
}
}
for (Account ctrlAcct : controlAccounts) {
if (ObjectUtils.isNotNull(ctrlAcct)) {
controlAccountSet.add(ctrlAcct);
}
}
// control accounts are set correctly for award accounts
if (controlAccountSet.size() != 0) {
for (Account controlAccount : controlAccountSet) {
Account tmpCtrlAcct = null;
tmpAcctList.clear();
for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) {
if (!awardAccount.isFinalBilledIndicator()) {
tmpCtrlAcct = awardAccount.getAccount().getContractControlAccount();
if (tmpCtrlAcct.getChartOfAccountsCode().equals(controlAccount.getChartOfAccountsCode()) && tmpCtrlAcct.getAccountNumber().equals(controlAccount.getAccountNumber())) {
tmpAcctList.add(awardAccount);
}
}
}
// To get valid award accounts of amounts > zero$ and pass it to the create invoices method
if (!getValidAwardAccounts(tmpAcctList, awd).containsAll(tmpAcctList)) {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.CONTROL_ACCOUNT_NON_BILLABLE, controlAccount.getAccountNumber(), awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
generateAndSaveContractsAndGrantsInvoiceDocument(awd, getValidAwardAccounts(tmpAcctList, awd), awd.getPrimaryAwardOrganization().getChartOfAccountsCode(), awd.getPrimaryAwardOrganization().getOrganizationCode(), errorMessages, accountDetails, locCreationType);
}
}
else {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.BILL_BY_CONTRACT_LACKS_CONTROL_ACCOUNT, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
}
}
/**
* Generates and saves Contracts & Grants Invoice Documents based on the award accounts of the passed in award
* @param awd the award to build Contracts & Grants Invoice Documents from the award accounts on
* @param errLines a holder for error messages
* @param accountDetails letter of credit details if we're creating via loc
* @param locCreationType letter of credit creation type if we're creating via loc
*/
protected void createInvoicesByAccounts(ContractsAndGrantsBillingAward awd, List<ErrorMessage> errorMessages, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
List<ContractsAndGrantsBillingAwardAccount> tmpAcctList = new ArrayList<ContractsAndGrantsBillingAwardAccount>();
for (ContractsAndGrantsBillingAwardAccount awardAccount : awd.getActiveAwardAccounts()) {
if (!awardAccount.isFinalBilledIndicator()) {
// only one account is added into the list to create cgin
tmpAcctList.clear();
tmpAcctList.add(awardAccount);
// To get valid award accounts of amounts > zero$ and pass it to the create invoices method
if (!getValidAwardAccounts(tmpAcctList, awd).containsAll(tmpAcctList)) {
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NON_BILLABLE, awardAccount.getAccountNumber(), awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
generateAndSaveContractsAndGrantsInvoiceDocument(awd, getValidAwardAccounts(tmpAcctList, awd), awd.getPrimaryAwardOrganization().getChartOfAccountsCode(), awd.getPrimaryAwardOrganization().getOrganizationCode(), errorMessages, accountDetails, locCreationType);
}
}
}
/**
* Generates and then saves a Contracts & Grants Invoice Document
* @param awd the award for the document
* @param validAwardAccounts the award accounts which should appear on the document
* @param coaCode the chart code for the document
* @param orgCode the organization code for the document
* @param errLines a List of error messages, to be appended to if there are errors in document generation
* @param accountDetails letter of credit details if we're creating via loc
* @param locCreationType letter of credit creation type if we're creating via loc
*/
protected void generateAndSaveContractsAndGrantsInvoiceDocument(ContractsAndGrantsBillingAward awd, List<ContractsAndGrantsBillingAwardAccount> validAwardAccounts, final String coaCode, final String orgCode, List<ErrorMessage> errorMessages, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
ContractsGrantsInvoiceDocument cgInvoiceDocument = createCGInvoiceDocumentByAwardInfo(awd, validAwardAccounts, coaCode, orgCode, errorMessages, accountDetails, locCreationType);
if (ObjectUtils.isNotNull(cgInvoiceDocument)) {
if ( !KualiDecimal.ZERO.equals(cgInvoiceDocument.getTotalInvoiceAmount()) ||
StringUtils.equalsIgnoreCase(awd.getBillingFrequencyCode(), ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) ||
StringUtils.equalsIgnoreCase(awd.getBillingFrequencyCode(), ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
// Saving the document
try {
documentService.saveDocument(cgInvoiceDocument, DocumentSystemSaveEvent.class);
} catch (WorkflowException ex) {
LOG.error("Error creating cgin documents: " + ex.getMessage(), ex);
throw new RuntimeException("Error creating cgin documents: " + ex.getMessage(), ex);
}
} else {
ErrorMessage errorMessage;
if (!awd.getActiveAwardAccounts().isEmpty()) {
errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NON_BILLABLE, awd.getActiveAwardAccounts().get(0).getAccountNumber(), awd.getProposalNumber().toString());
} else {
errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NON_BILLABLE, null, awd.getProposalNumber().toString());
}
errorMessages.add(errorMessage);
}
}
}
/**
* @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#createCGInvoiceDocumentByAwardInfo(org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward, java.util.List, java.lang.String, java.lang.String, java.util.List, java.util.List, java.lang.String)
*/
@Override
public ContractsGrantsInvoiceDocument createCGInvoiceDocumentByAwardInfo(ContractsAndGrantsBillingAward awd, List<ContractsAndGrantsBillingAwardAccount> accounts, String chartOfAccountsCode, String organizationCode, List<ErrorMessage> errorMessages, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
ContractsGrantsInvoiceDocument cgInvoiceDocument = null;
if (ObjectUtils.isNotNull(accounts) && !accounts.isEmpty()) {
if (chartOfAccountsCode != null && organizationCode != null) {
try {
cgInvoiceDocument = (ContractsGrantsInvoiceDocument) documentService.getNewDocument(ContractsGrantsInvoiceDocument.class);
// Set description to the document created.
cgInvoiceDocument.getDocumentHeader().setDocumentDescription(ArConstants.BatchFileSystem.CGINVOICE_DOCUMENT_DESCRIPTION_OF_BATCH_PROCESS);
// setup several Default Values for CGInvoice document which extends from Customer Invoice Document
// a) set billing org and chart code
cgInvoiceDocument.setBillByChartOfAccountCode(chartOfAccountsCode);
cgInvoiceDocument.setBilledByOrganizationCode(organizationCode);
// b) set processing org and chart code
List<String> procCodes = getContractsGrantsInvoiceDocumentService().getProcessingFromBillingCodes(chartOfAccountsCode, organizationCode);
AccountsReceivableDocumentHeader accountsReceivableDocumentHeader = new AccountsReceivableDocumentHeader();
accountsReceivableDocumentHeader.setDocumentNumber(cgInvoiceDocument.getDocumentNumber());
// Set processing chart and org codes
if (procCodes != null){
int procCodesSize = procCodes.size();
// Set processing chart
if (procCodesSize > 0){
accountsReceivableDocumentHeader.setProcessingChartOfAccountCode(procCodes.get(0));
}
// Set processing org code
if (procCodesSize > 1){
accountsReceivableDocumentHeader.setProcessingOrganizationCode(procCodes.get(1));
}
}
cgInvoiceDocument.setAccountsReceivableDocumentHeader(accountsReceivableDocumentHeader);
populateInvoiceFromAward(awd, accounts, cgInvoiceDocument, accountDetails, locCreationType);
contractsGrantsInvoiceDocumentService.createSourceAccountingLines(cgInvoiceDocument, accounts);
if (ObjectUtils.isNotNull(cgInvoiceDocument.getInvoiceGeneralDetail().getAward())) {
contractsGrantsInvoiceDocumentService.updateSuspensionCategoriesOnDocument(cgInvoiceDocument);
}
LOG.info("Created Contracts & Grants Invoice Document " + cgInvoiceDocument.getDocumentNumber());
}
catch (WorkflowException ex) {
LOG.error("Error creating cgin documents: " + ex.getMessage(), ex);
throw new RuntimeException("Error creating cgin documents: " + ex.getMessage(), ex);
}
}
else {
// if chart of account code or organization code is not available, output the error
final ErrorMessage errorMessage = new ErrorMessage(ArKeyConstants.ContractsGrantsInvoiceCreateDocumentConstants.NO_CHART_OR_ORG, awd.getProposalNumber().toString());
errorMessages.add(errorMessage);
}
}
return cgInvoiceDocument;
}
/**
* This method takes all the applicable attributes from the associated award object and sets those attributes into their
* corresponding invoice attributes.
*
* @param award The associated award that the invoice will be linked to.
* @param awardAccounts
* @param document
* @param accountDetails letter of credit details if we're creating via loc
* @param locCreationType letter of credit creation type if we're creating via loc
*/
protected void populateInvoiceFromAward(ContractsAndGrantsBillingAward award, List<ContractsAndGrantsBillingAwardAccount> awardAccounts, ContractsGrantsInvoiceDocument document, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails, String locCreationType) {
if (ObjectUtils.isNotNull(award)) {
// Invoice General Detail section
InvoiceGeneralDetail invoiceGeneralDetail = new InvoiceGeneralDetail();
invoiceGeneralDetail.setDocumentNumber(document.getDocumentNumber());
invoiceGeneralDetail.setProposalNumber(award.getProposalNumber());
invoiceGeneralDetail.setAward(award);
// Set the last Billed Date and Billing Period
Timestamp ts = new Timestamp(new java.util.Date().getTime());
java.sql.Date today = new java.sql.Date(ts.getTime());
AccountingPeriod currPeriod = accountingPeriodService.getByDate(today);
java.sql.Date[] pair = verifyBillingFrequencyService.getStartDateAndEndDateOfPreviousBillingPeriod(award, currPeriod);
invoiceGeneralDetail.setBillingPeriod(pair[0] + " to " + pair[1]);
invoiceGeneralDetail.setLastBilledDate(pair[1]);
populateInvoiceDetailFromAward(invoiceGeneralDetail, award);
document.setInvoiceGeneralDetail(invoiceGeneralDetail);
// To set Bill by address identifier because it is a required field - set the value to 1 as it is never being used.
document.setCustomerBillToAddressIdentifier(1);
// Set Invoice due date to current date as it is required field and never used.
document.setInvoiceDueDate(dateTimeService.getCurrentSqlDateMidnight());
// copy award's customer address to invoice address details
document.getInvoiceAddressDetails().clear();
ContractsAndGrantsBillingAgency agency = award.getAgency();
if (ObjectUtils.isNotNull(agency)) {
final List<InvoiceAddressDetail> invoiceAddressDetails = buildInvoiceAddressDetailsFromAgency(agency, document);
document.getInvoiceAddressDetails().addAll(invoiceAddressDetails);
}
java.sql.Date invoiceDate = document.getInvoiceGeneralDetail().getLastBilledDate();
if (document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)) {// To check if award has milestones
final List<Milestone> milestones = getContractsGrantsBillingUtilityService().getActiveMilestonesForProposalNumber(award.getProposalNumber());
if (!CollectionUtils.isEmpty(milestones)) {
// copy award milestones to invoice milestones
document.getInvoiceMilestones().clear();
final List<InvoiceMilestone> invoiceMilestones = buildInvoiceMilestones(milestones, invoiceDate);
document.getInvoiceMilestones().addAll(invoiceMilestones);
}
}
else if (document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {// To check if award has bills
final List<Bill> bills = getContractsGrantsBillingUtilityService().getActiveBillsForProposalNumber(award.getProposalNumber());
if (!CollectionUtils.isEmpty(bills)) {
// copy award milestones to invoice milestones
document.getInvoiceBills().clear();
final List<InvoiceBill> invoiceBills = buildInvoiceBills(bills, invoiceDate);
document.getInvoiceBills().addAll(invoiceBills);
}
}
// copy award's accounts to invoice account details
document.getAccountDetails().clear();
final List<InvoiceAccountDetail> invoiceAccountDetails = new ArrayList<>();
List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes = new ArrayList<>();
Map<String, KualiDecimal> budgetAmountsByCostCategory = new HashMap<>();
Integer currentYear = getUniversityDateService().getCurrentFiscalYear();
final boolean firstFiscalPeriod = isFirstFiscalPeriod();
final Integer fiscalYear = firstFiscalPeriod && useTimeBasedBillingFrequency(document.getInvoiceGeneralDetail().getBillingFrequencyCode()) ? currentYear - 1 : currentYear;
final SystemOptions systemOptions = optionsService.getOptions(fiscalYear);
List<String> balanceTypeCodeList = new ArrayList<String>();
balanceTypeCodeList.add(systemOptions.getBudgetCheckingBalanceTypeCd());
balanceTypeCodeList.add(systemOptions.getActualFinancialBalanceTypeCd());
for (ContractsAndGrantsBillingAwardAccount awardAccount : awardAccounts) {
InvoiceAccountDetail invoiceAccountDetail = buildInvoiceAccountDetailForAwardAccount(award, awardAccount, document.getDocumentNumber(), document.getInvoiceGeneralDetail());
final ContractsGrantsLetterOfCreditReviewDetail locReviewDetail = retrieveMatchingLetterOfCreditReviewDetail(awardAccount, accountDetails);
List<Balance> glBalances = retrieveBalances(fiscalYear, awardAccount.getChartOfAccountsCode(), awardAccount.getAccountNumber(), balanceTypeCodeList);
KualiDecimal awardAccountBudgetAmount = KualiDecimal.ZERO;
KualiDecimal balanceAmount = KualiDecimal.ZERO;
KualiDecimal awardAccountCumulativeAmount = KualiDecimal.ZERO;
for (Balance balance : glBalances) {
if (!isBalanceCostShare(balance)) {
if (balance.getBalanceTypeCode().equalsIgnoreCase(systemOptions.getBudgetCheckingBalanceTypeCd())) {
awardAccountBudgetAmount = addBalanceToAwardAccountBudgetAmount(balance, awardAccountBudgetAmount, firstFiscalPeriod);
updateCategoryBudgetAmountsByBalance(balance, budgetAmountsByCostCategory, firstFiscalPeriod);
}
else if (balance.getBalanceTypeCode().equalsIgnoreCase(systemOptions.getActualFinancialBalanceTypeCd())) {
awardAccountCumulativeAmount = addBalanceToAwardAccountCumulativeAmount(document, balance, award, awardAccountCumulativeAmount, firstFiscalPeriod);
updateCategoryActualAmountsByBalance(document, balance, award, invoiceDetailAccountObjectsCodes, firstFiscalPeriod);
}
}
invoiceAccountDetail.setTotalBudget(awardAccountBudgetAmount);
invoiceAccountDetail.setCumulativeExpenditures(awardAccountCumulativeAmount);
}
invoiceAccountDetails.add(invoiceAccountDetail);
if (!ObjectUtils.isNull(locReviewDetail) && !locReviewDetail.getClaimOnCashBalance().negated().equals(locReviewDetail.getAmountToDraw()) && StringUtils.equalsIgnoreCase(award.getBillingFrequencyCode(), ArConstants.LOC_BILLING_SCHEDULE_CODE)) {
distributeAmountAmongAllAccountObjectCodes(document, awardAccount, invoiceDetailAccountObjectsCodes, locReviewDetail);
}
else {
updateInvoiceDetailAccountObjectCodesByBilledAmount(awardAccount, invoiceDetailAccountObjectsCodes);
}
}
document.getAccountDetails().addAll(invoiceAccountDetails);
if (!document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) && !document.getInvoiceGeneralDetail().getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
document.getInvoiceDetailAccountObjectCodes().addAll(invoiceDetailAccountObjectsCodes);
List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilleds = getAwardAccountObjectCodeTotalBilledDao().getAwardAccountObjectCodeTotalBuildByProposalNumberAndAccount(awardAccounts);
List<ContractsGrantsInvoiceDetail> invoiceDetails = generateValuesForCategories(document.getDocumentNumber(), document.getInvoiceDetailAccountObjectCodes(), budgetAmountsByCostCategory, awardAccountObjectCodeTotalBilleds);
document.getInvoiceDetails().addAll(invoiceDetails);
}
// Set some basic values to invoice Document
populateContractsGrantsInvoiceDocument(award, document, accountDetails, locCreationType);
}
}
/**
* Finds a letter of credit review detail which matches the given award account, or null if one could not be found
* @param awardAccount the award account to find a matching contracts grants letter of credit review detail for
* @param accountDetails a List of contracts grants letter of credit review details
* @return the matching contracts grants review detail, or null if one could not be found
*/
protected ContractsGrantsLetterOfCreditReviewDetail retrieveMatchingLetterOfCreditReviewDetail(ContractsAndGrantsBillingAwardAccount awardAccount, List<ContractsGrantsLetterOfCreditReviewDetail> accountDetails) {
if (CollectionUtils.isEmpty(accountDetails)) {
return null;
}
for (ContractsGrantsLetterOfCreditReviewDetail reviewDetail : accountDetails) {
if (reviewDetail.getProposalNumber().equals(awardAccount.getProposalNumber()) && StringUtils.equals(reviewDetail.getChartOfAccountsCode(), awardAccount.getChartOfAccountsCode()) && StringUtils.equals(reviewDetail.getAccountNumber(), awardAccount.getAccountNumber())) {
return reviewDetail;
}
}
return null;
}
/**
* Updates the appropriate amounts for the InvoiceDetailAccountObjectCode matching the given balance
* @param document the CINV document we're generating
* @param balance the balance to update amounts by
* @param award the award on the CINV document we're generating
* @param invoiceDetailAccountObjectsCodes the List of invoiceDetailObjectCodes to update one of
* @param firstFiscalPeriod whether we're generating the CINV document in the fiscal fiscal period or not
*/
protected void updateCategoryActualAmountsByBalance(ContractsGrantsInvoiceDocument document, Balance balance, ContractsAndGrantsBillingAward award, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, boolean firstFiscalPeriod) {
final CostCategory category = getCostCategoryService().getCostCategoryForObjectCode(balance.getUniversityFiscalYear(), balance.getChartOfAccountsCode(), balance.getObjectCode());
if (!ObjectUtils.isNull(category)) {
final InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode = getInvoiceDetailAccountObjectCodeByBalanceAndCategory(invoiceDetailAccountObjectCodes, balance, document.getDocumentNumber(), document.getInvoiceGeneralDetail().getProposalNumber(), category);
if (useTimeBasedBillingFrequency(document.getInvoiceGeneralDetail().getBillingFrequencyCode())) {
if (firstFiscalPeriod) {
invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).add(cleanAmount(balance.getContractsGrantsBeginningBalanceAmount())).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount())));
if (!includePeriod13InPeriod01Calculations()) {
invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).subtract(cleanAmount(balance.getMonth13Amount())));
}
} else {
invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).add(calculateBalanceAmountWithoutLastBilledPeriod(document.getInvoiceGeneralDetail().getLastBilledDate(), balance)));
}
}
else {// For other billing frequencies
KualiDecimal balanceAmount = cleanAmount(balance.getContractsGrantsBeginningBalanceAmount()).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount()));
invoiceDetailAccountObjectCode.setCumulativeExpenditures(cleanAmount(invoiceDetailAccountObjectCode.getCumulativeExpenditures()).add(cleanAmount(balance.getContractsGrantsBeginningBalanceAmount()).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount()))));
}
}
}
/**
* Sums the balance to the given awardAccountCumulativeAmount and returns that summed amount
* @param document the CINV document we're generating
* @param balance the balance to update amounts by
* @param award the award on the CINV document we're generating
* @param awardAccountCumulativeAmount the beginning cumulative expense amount for the award account of the balance
* @param firstFiscalPeriod whether we're generating the CINV document in the fiscal fiscal period or not
* @return the updated cumulative amount on the award account
*/
protected KualiDecimal addBalanceToAwardAccountCumulativeAmount(ContractsGrantsInvoiceDocument document, Balance balance, ContractsAndGrantsBillingAward award, KualiDecimal awardAccountCumulativeAmount, boolean firstFiscalPeriod) {
if (useTimeBasedBillingFrequency(document.getInvoiceGeneralDetail().getBillingFrequencyCode())) {
if (firstFiscalPeriod) {
KualiDecimal newAwardAccountCumulativeAmount = awardAccountCumulativeAmount.add(cleanAmount(balance.getContractsGrantsBeginningBalanceAmount())).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount()));
if (!includePeriod13InPeriod01Calculations()) {
newAwardAccountCumulativeAmount = awardAccountCumulativeAmount.subtract(balance.getMonth13Amount());
}
return newAwardAccountCumulativeAmount;
} else {
return awardAccountCumulativeAmount.add(calculateBalanceAmountWithoutLastBilledPeriod(award.getLastBilledDate(), balance));
}
}
else {// For other billing frequencies
KualiDecimal balanceAmount = cleanAmount(balance.getContractsGrantsBeginningBalanceAmount()).add(cleanAmount(balance.getAccountLineAnnualBalanceAmount()));
return awardAccountCumulativeAmount.add(balanceAmount);
}
}
/**
* Updates the cost category budget amount (in the given Map, budgetAmountsByCostCategory) by the total amount of the balance
* @param balance the balance to update the budget amounts by
* @param budgetAmountsByCostCategory the Map of budget amounts sorted by cost category
* @param firstFiscalPeriod whether this CINV is being generated in the first fiscal period or not
* @return the updated award account budget amount
*/
protected void updateCategoryBudgetAmountsByBalance(Balance balance, Map<String, KualiDecimal> budgetAmountsByCostCategory, boolean firstFiscalPeriod) {
CostCategory category = getCostCategoryService().getCostCategoryForObjectCode(balance.getUniversityFiscalYear(), balance.getChartOfAccountsCode(), balance.getObjectCode());
if (!ObjectUtils.isNull(category)) {
final KualiDecimal balanceAmount = getBudgetBalanceAmount(balance, firstFiscalPeriod);
KualiDecimal categoryBudgetAmount = budgetAmountsByCostCategory.get(category.getCategoryCode());
if (categoryBudgetAmount == null) {
categoryBudgetAmount = KualiDecimal.ZERO;
}
categoryBudgetAmount = categoryBudgetAmount.add(balanceAmount);
budgetAmountsByCostCategory.put(category.getCategoryCode(), categoryBudgetAmount);
} else {
LOG.warn("Could not find cost category for balance: "+balance.getUniversityFiscalYear()+" "+balance.getChartOfAccountsCode()+" "+balance.getAccountNumber()+" "+balance.getSubAccountNumber()+" "+balance.getObjectCode()+" "+balance.getSubObjectCode()+" "+balance.getBalanceTypeCode());
}
}
/**
* Adds the budget balance to the award account budget amount
* @param balance the balance to update the budget amounts by
* @param awardAccountBudgetAmount the beginning award account budget amount
* @param firstFiscalPeriod whether this CINV is being generated in the first fiscal period or not
* @return the updated award account budget amount
*/
protected KualiDecimal addBalanceToAwardAccountBudgetAmount(Balance balance, KualiDecimal awardAccountBudgetAmount, boolean firstFiscalPeriod) {
final KualiDecimal balanceAmount = getBudgetBalanceAmount(balance, firstFiscalPeriod);
return awardAccountBudgetAmount.add(balanceAmount);
}
/**
* Determines the balance amount (cg + annual) from the given budget balance
* @param balance balance to find amount from
* @param firstFiscalPeriod whether the CINV is being created in the first fiscal period or not
* @return the total amount from the balance
*/
protected KualiDecimal getBudgetBalanceAmount(Balance balance, boolean firstFiscalPeriod) {
KualiDecimal balanceAmount = balance.getContractsGrantsBeginningBalanceAmount().add(balance.getAccountLineAnnualBalanceAmount());
if (firstFiscalPeriod && !includePeriod13InPeriod01Calculations()) {
balanceAmount = balanceAmount.subtract(balance.getMonth13Amount()); // get rid of period 13 if we should not include in calculations
}
return balanceAmount;
}
/**
* Builds a new invoice account detail for a given award account
* @param award the award associated with the award account
* @param awardAccount the award account to build the invoice account detail for
* @param documentNumber the number of the document we're currently building
* @param invoiceGeneralDetail the invoice general detail for the the document we're currently building
* @return the built invoice account detail
*/
protected InvoiceAccountDetail buildInvoiceAccountDetailForAwardAccount(ContractsAndGrantsBillingAward award, ContractsAndGrantsBillingAwardAccount awardAccount, final String documentNumber, InvoiceGeneralDetail invoiceGeneralDetail) {
InvoiceAccountDetail invoiceAccountDetail = new InvoiceAccountDetail();
invoiceAccountDetail.setDocumentNumber(documentNumber);
invoiceAccountDetail.setAccountNumber(awardAccount.getAccountNumber());
if (ObjectUtils.isNotNull(awardAccount.getAccount()) && StringUtils.isNotEmpty(awardAccount.getAccount().getContractControlAccountNumber())) {
invoiceAccountDetail.setContractControlAccountNumber(awardAccount.getAccount().getContractControlAccountNumber());
}
invoiceAccountDetail.setChartOfAccountsCode(awardAccount.getChartOfAccountsCode());
invoiceAccountDetail.setProposalNumber(awardAccount.getProposalNumber());
return invoiceAccountDetail;
}
/**
* Generates InvoiceBills for each of the given Bills
* @param bills the bulls to associate with a contracts & grants billing invoice
* @param invoiceDate the date of the invoice we're building
* @return the List of generated InvoiceBill objects
*/
protected List<InvoiceBill> buildInvoiceBills(List<Bill> bills, java.sql.Date invoiceDate) {
List<InvoiceBill> invoiceBills = new ArrayList<>();
for (Bill awdBill : bills) {
// To check for null - Bill Completion date.
// To consider the completed milestones only.
if (awdBill.getBillDate() != null && !invoiceDate.before(awdBill.getBillDate()) && !awdBill.isBilled() && awdBill.getEstimatedAmount().isGreaterThan(KualiDecimal.ZERO)) {
InvoiceBill invBill = new InvoiceBill();
invBill.setBillNumber(awdBill.getBillNumber());
invBill.setBillIdentifier(awdBill.getBillIdentifier());
invBill.setBillDescription(awdBill.getBillDescription());
invBill.setBillDate(awdBill.getBillDate());
invBill.setEstimatedAmount(awdBill.getEstimatedAmount());
invoiceBills.add(invBill);
}
}
return invoiceBills;
}
/**
* Generates InvoiceMilestones for each of the given milestones
* @param milestones the milestones to associate with a contracts & grants billing invoice
* @param invoiceDate the date of the invoice we're building
* @return the List of InvoiceMilestones
*/
protected List<InvoiceMilestone> buildInvoiceMilestones(List<Milestone> milestones, java.sql.Date invoiceDate) {
List<InvoiceMilestone> invoiceMilestones = new ArrayList<>();
for (Milestone awdMilestone : milestones) {
// To consider the completed milestones only.
// To check for null - Milestone Completion date.
if (awdMilestone.getMilestoneActualCompletionDate() != null && !invoiceDate.before(awdMilestone.getMilestoneActualCompletionDate()) && !awdMilestone.isBilled() && awdMilestone.getMilestoneAmount().isGreaterThan(KualiDecimal.ZERO)) {
InvoiceMilestone invMilestone = new InvoiceMilestone();
invMilestone.setMilestoneNumber(awdMilestone.getMilestoneNumber());
invMilestone.setMilestoneIdentifier(awdMilestone.getMilestoneIdentifier());
invMilestone.setMilestoneDescription(awdMilestone.getMilestoneDescription());
invMilestone.setMilestoneActualCompletionDate(awdMilestone.getMilestoneActualCompletionDate());
invMilestone.setMilestoneAmount(awdMilestone.getMilestoneAmount());
invoiceMilestones.add(invMilestone);
}
}
return invoiceMilestones;
}
/**
* Builds a list of InvoiceAddressDetails based on the customer associated with an Agency
* @param agency the agency associated with the proposal we're building a CINV document for
* @param documentNumber the document number of the CINV document we're creating
* @return a List of the generated invoice address details
*/
protected List<InvoiceAddressDetail> buildInvoiceAddressDetailsFromAgency(ContractsAndGrantsBillingAgency agency, ContractsGrantsInvoiceDocument document) {
Map<String, Object> mapKey = new HashMap<String, Object>();
mapKey.put(KFSPropertyConstants.CUSTOMER_NUMBER, agency.getCustomerNumber());
final List<CustomerAddress> customerAddresses = (List<CustomerAddress>) businessObjectService.findMatching(CustomerAddress.class, mapKey);
String documentNumber = document.getDocumentNumber();
List<InvoiceAddressDetail> invoiceAddressDetails = new ArrayList<>();
for (CustomerAddress customerAddress : customerAddresses) {
if (StringUtils.equalsIgnoreCase(ArKeyConstants.CustomerConstants.CUSTOMER_ADDRESS_TYPE_CODE_PRIMARY, customerAddress.getCustomerAddressTypeCode())) {
document.setCustomerBillToAddressOnInvoice(customerAddress);
}
InvoiceAddressDetail invoiceAddressDetail = new InvoiceAddressDetail();
invoiceAddressDetail.setCustomerNumber(customerAddress.getCustomerNumber());
invoiceAddressDetail.setDocumentNumber(documentNumber);
invoiceAddressDetail.setCustomerAddressIdentifier(customerAddress.getCustomerAddressIdentifier());
invoiceAddressDetail.setCustomerAddressTypeCode(customerAddress.getCustomerAddressTypeCode());
invoiceAddressDetail.setCustomerAddressName(customerAddress.getCustomerAddressName());
invoiceAddressDetail.setInvoiceTransmissionMethodCode(customerAddress.getInvoiceTransmissionMethodCode());
invoiceAddressDetail.setCustomerEmailAddress(customerAddress.getCustomerEmailAddress());
invoiceAddressDetail.setCustomerLine1StreetAddress(customerAddress.getCustomerLine1StreetAddress());
invoiceAddressDetail.setCustomerLine2StreetAddress(customerAddress.getCustomerLine2StreetAddress());
invoiceAddressDetail.setCustomerCityName(customerAddress.getCustomerCityName());
invoiceAddressDetail.setCustomerStateCode(customerAddress.getCustomerStateCode());
invoiceAddressDetail.setCustomerZipCode(customerAddress.getCustomerZipCode());
invoiceAddressDetail.setCustomerCountryCode(customerAddress.getCustomerCountryCode());
invoiceAddressDetail.setCustomerInternationalMailCode(customerAddress.getCustomerInternationalMailCode());
invoiceAddressDetail.setCustomerAddressInternationalProvinceName(customerAddress.getCustomerAddressInternationalProvinceName());
if (StringUtils.isNotBlank(customerAddress.getCustomerInvoiceTemplateCode())) {
invoiceAddressDetail.setCustomerInvoiceTemplateCode(customerAddress.getCustomerInvoiceTemplateCode());
} else {
AccountsReceivableCustomer customer = agency.getCustomer();
if (ObjectUtils.isNotNull(customer) && StringUtils.isNotBlank(customer.getCustomerInvoiceTemplateCode())) {
invoiceAddressDetail.setCustomerInvoiceTemplateCode(customer.getCustomerInvoiceTemplateCode());
}
}
invoiceAddressDetails.add(invoiceAddressDetail);
}
return invoiceAddressDetails;
}
/**
* 1. This method is responsible to populate categories column for the ContractsGrantsInvoice Document. 2. The categories are
* retrieved from the Maintenance document as a collection and then a logic with conditions to handle ranges of Object Codes. 3.
* Once the object codes are retrieved and categories are set the performAccountingCalculations method of InvoiceDetail BO will
* do all the accounting calculations.
* @param documentNumber the number of the document we want to add invoice details to
* @param invoiceDetailAccountObjectCodes the List of InvoiceDetailAccountObjectCodes containing amounts to sum into our invoice details
* @param budgetAmountsByCostCategory the budget amounts, sorted by cost category
* @param awardAccountObjectCodeTotalBilleds the business objects containg what has been billed from the document's award accounts already
*/
public List<ContractsGrantsInvoiceDetail> generateValuesForCategories(String documentNumber, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, Map<String, KualiDecimal> budgetAmountsByCostCategory, List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilleds) {
Collection<CostCategory> costCategories = retrieveAllBillingCategories();
List<ContractsGrantsInvoiceDetail> invoiceDetails = new ArrayList<>();
Map<String, List<InvoiceDetailAccountObjectCode>> invoiceDetailAccountObjectCodesMap = mapInvoiceDetailAccountObjectCodesByCategoryCode(invoiceDetailAccountObjectCodes);
Map<String, List<AwardAccountObjectCodeTotalBilled>> billedsMap = mapAwardAccountObjectCodeTotalBilledsByCategoryCode(awardAccountObjectCodeTotalBilleds);
for (CostCategory category : costCategories) {
ContractsGrantsInvoiceDetail invDetail = new ContractsGrantsInvoiceDetail();
invDetail.setDocumentNumber(documentNumber);
invDetail.setCategoryCode(category.getCategoryCode());
invDetail.setCostCategory(category);
invDetail.setIndirectCostIndicator(category.isIndirectCostIndicator());
// calculate total billed first
invDetail.setCumulativeExpenditures(KualiDecimal.ZERO);
invDetail.setInvoiceAmount(KualiDecimal.ZERO);
invDetail.setTotalPreviouslyBilled(KualiDecimal.ZERO);
List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodesForCategory = invoiceDetailAccountObjectCodesMap.get(category.getCategoryCode());
if (!CollectionUtils.isEmpty(invoiceDetailAccountObjectCodesForCategory)) {
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodesForCategory) {
invDetail.setCumulativeExpenditures(invDetail.getCumulativeExpenditures().add(invoiceDetailAccountObjectCode.getCumulativeExpenditures()));
invDetail.setInvoiceAmount(invDetail.getInvoiceAmount().add(invoiceDetailAccountObjectCode.getCurrentExpenditures()));
}
}
List<AwardAccountObjectCodeTotalBilled> billedForCategory = billedsMap.get(category.getCategoryCode());
if (!CollectionUtils.isEmpty(billedForCategory)) {
for (AwardAccountObjectCodeTotalBilled accountObjectCodeTotalBilled : billedForCategory) {
invDetail.setTotalPreviouslyBilled(invDetail.getTotalPreviouslyBilled().add(accountObjectCodeTotalBilled.getTotalBilled())); // this adds up all the total billed based on object code into categories; sum for this category.
}
}
// calculate the rest using billed to date
if (!ObjectUtils.isNull(budgetAmountsByCostCategory.get(category.getCategoryCode()))) {
invDetail.setTotalBudget(budgetAmountsByCostCategory.get(category.getCategoryCode()));
} else {
invDetail.setTotalBudget(KualiDecimal.ZERO);
}
invoiceDetails.add(invDetail);
}
return invoiceDetails;
}
/**
* Converts a List of InvoiceDetailAccountObjectCodes into a map where the key is the category code
* @param invoiceDetailAccountObjectCodes a List of InvoiceDetailAccountObjectCodes
* @return that List converted to a Map, keyed by category code
*/
protected Map<String, List<InvoiceDetailAccountObjectCode>> mapInvoiceDetailAccountObjectCodesByCategoryCode(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes) {
Map<String, List<InvoiceDetailAccountObjectCode>> invoiceDetailAccountObjectCodesMap = new HashMap<>();
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) {
List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodesForCategory = invoiceDetailAccountObjectCodesMap.get(invoiceDetailAccountObjectCode.getCategoryCode());
if (invoiceDetailAccountObjectCodesForCategory == null) {
invoiceDetailAccountObjectCodesForCategory = new ArrayList<>();
}
invoiceDetailAccountObjectCodesForCategory.add(invoiceDetailAccountObjectCode);
invoiceDetailAccountObjectCodesMap.put(invoiceDetailAccountObjectCode.getCategoryCode(), invoiceDetailAccountObjectCodesForCategory);
}
return invoiceDetailAccountObjectCodesMap;
}
/**
* Converts a List of AwardAccountObjectCodeTotalBilled into a Map, keyed by the Cost Category which most closely matches them
* @param awardAccountObjectCodeTotalBilleds the List of AwardAccountObjectCodeTotalBilled business objects to Map
* @return the Mapped AwardAccountObjectCodeTotalBilled records
*/
protected Map<String, List<AwardAccountObjectCodeTotalBilled>> mapAwardAccountObjectCodeTotalBilledsByCategoryCode( List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilleds) {
Integer fiscalYear = getUniversityDateService().getCurrentFiscalYear();
Map<String, List<AwardAccountObjectCodeTotalBilled>> billedsMap = new HashMap<>();
for (AwardAccountObjectCodeTotalBilled billed : awardAccountObjectCodeTotalBilleds) {
final CostCategory category = getCostCategoryService().getCostCategoryForObjectCode(fiscalYear, billed.getChartOfAccountsCode(), billed.getFinancialObjectCode());
if (!ObjectUtils.isNull(category)) {
List<AwardAccountObjectCodeTotalBilled> billedForCategory = billedsMap.get(category.getCategoryCode());
if (billedForCategory == null) {
billedForCategory = new ArrayList<>();
}
billedForCategory.add(billed);
billedsMap.put(category.getCategoryCode(), billedForCategory);
} else {
LOG.warn("Could not find cost category for AwardAccountObjectCodeTotalBilled, fiscal year = "+fiscalYear+" "+billed.getChartOfAccountsCode()+" "+billed.getFinancialObjectCode());
}
}
return billedsMap;
}
/**
* This method takes all the applicable attributes from the associated award object and sets those attributes into their
* corresponding invoice attributes.
* @param invoiceGeneralDetail the invoice detail to populate
* @param award The associated award that the invoice will be linked to.
*/
protected void populateInvoiceDetailFromAward(InvoiceGeneralDetail invoiceGeneralDetail, ContractsAndGrantsBillingAward award) {
// copy General details from award to the invoice
invoiceGeneralDetail.setAwardTotal(award.getAwardTotalAmount());
invoiceGeneralDetail.setAgencyNumber(award.getAgencyNumber());
if (ObjectUtils.isNotNull(award.getBillingFrequencyCode())) {
invoiceGeneralDetail.setBillingFrequencyCode(award.getBillingFrequencyCode());
}
if (ObjectUtils.isNotNull(award.getInstrumentTypeCode())) {
invoiceGeneralDetail.setInstrumentTypeCode(award.getInstrumentTypeCode());
}
// To set Award Date range - this would be (Award Start Date to Award Stop Date)
String awdDtRange = award.getAwardBeginningDate() + " to " + award.getAwardEndingDate();
invoiceGeneralDetail.setAwardDateRange(awdDtRange);
// set the billed to Date Field
// To check if award has milestones
if (StringUtils.equalsIgnoreCase(invoiceGeneralDetail.getBillingFrequencyCode(), ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)) {
invoiceGeneralDetail.setTotalPreviouslyBilled(contractsGrantsInvoiceDocumentService.getMilestonesBilledToDateAmount(award.getProposalNumber()));
}
else if (StringUtils.equalsIgnoreCase(invoiceGeneralDetail.getBillingFrequencyCode(),ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
invoiceGeneralDetail.setTotalPreviouslyBilled(contractsGrantsInvoiceDocumentService.getPredeterminedBillingBilledToDateAmount(award.getProposalNumber()));
}
else {
invoiceGeneralDetail.setTotalPreviouslyBilled(contractsGrantsInvoiceDocumentService.getAwardBilledToDateAmountByProposalNumber(award.getProposalNumber()));
}
}
/**
* For letter of credit, this distributes the amount for matching LOC invoice detail account object codes (which is very probably all of invoice detail account object codes in the given list) evenly
* @param document the CINV document we're creating
* @param awdAcct the C&G Award Account
* @param invoiceDetailAccountObjectsCodes the List of invoice detail account object codes we're attempting to generate
* @param locReviewDetail the contracts grants letter of credit review detail which is related to the given award account
*/
protected void distributeAmountAmongAllAccountObjectCodes(ContractsGrantsInvoiceDocument document, ContractsAndGrantsBillingAwardAccount awdAcct, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes, ContractsGrantsLetterOfCreditReviewDetail locReviewDetail) {
final List<InvoiceDetailAccountObjectCode> locRedistributionInvoiceDetailAccountObjectCodes = filterInvoiceAccountObjectCodesByDocumentAndAccount(document, awdAcct, invoiceDetailAccountObjectsCodes);
final Map<String, List<InvoiceDetailAccountObjectCode>> locRedistributionAccountObjectCodesByCategory = mapInvoiceDetailAccountObjectCodesByCategoryCode(locRedistributionInvoiceDetailAccountObjectCodes);
final Map<String, BigDecimal> percentagesByCategory = calculatePercentagesByCategory(locRedistributionAccountObjectCodesByCategory, locReviewDetail.getClaimOnCashBalance().negated());
final Map<String, KualiDecimal> amountsByCategory = calculateAmountsByCategory(percentagesByCategory, locReviewDetail.getAmountToDraw());
redistributeAmountsToInvoiceAccountCategories(locRedistributionAccountObjectCodesByCategory, amountsByCategory);
takeAPennyLeaveAPennyCGBStyle(locRedistributionInvoiceDetailAccountObjectCodes, locReviewDetail.getAmountToDraw());
}
/**
* Filters the given list of invoice detail account object codes by the given document and account
* @param document the document which owns the invoice detail account object codes
* @param awdAcct the award account to find invoice detail account object codes for
* @param invoiceDetailAccountObjectsCodes the original list of invoice detail account object codes
* @return a list of invoice detail account object codes associated with the given document and the given account
*/
protected List<InvoiceDetailAccountObjectCode> filterInvoiceAccountObjectCodesByDocumentAndAccount(ContractsGrantsInvoiceDocument document, ContractsAndGrantsBillingAwardAccount awdAcct, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes) {
List<InvoiceDetailAccountObjectCode> locRedistributionInvoiceDetailAccountObjectCodes = new ArrayList<InvoiceDetailAccountObjectCode>();
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectsCodes) {
if (StringUtils.equals(invoiceDetailAccountObjectCode.getDocumentNumber(), document.getDocumentNumber()) && invoiceDetailAccountObjectCode.getProposalNumber().equals(document.getInvoiceGeneralDetail().getProposalNumber()) && StringUtils.equals(invoiceDetailAccountObjectCode.getAccountNumber(), awdAcct.getAccountNumber()) && StringUtils.equals(invoiceDetailAccountObjectCode.getChartOfAccountsCode(), awdAcct.getChartOfAccountsCode())) {
locRedistributionInvoiceDetailAccountObjectCodes.add(invoiceDetailAccountObjectCode);
}
}
return locRedistributionInvoiceDetailAccountObjectCodes;
}
/**
* Sums the current expenditures of the given invoice detail account object codes
* @param invoiceDetailAccountObjectCodes invoice detail account object codes to total the current expenditures of
* @return the total of the current expenditures
*/
protected InvoiceDetailAccountObjectCode sumInvoiceDetailAccountObjectCodes(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes) {
InvoiceDetailAccountObjectCode total = new InvoiceDetailAccountObjectCode();
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) {
total.setCumulativeExpenditures(total.getCumulativeExpenditures().add(invoiceDetailAccountObjectCode.getCumulativeExpenditures()));
total.setCurrentExpenditures(total.getCurrentExpenditures().add(invoiceDetailAccountObjectCode.getCurrentExpenditures()));
total.setTotalBilled(total.getTotalBilled().add(invoiceDetailAccountObjectCode.getTotalBilled()));
}
return total;
}
/**
* Calculates the percentage of the given total each list of invoice detail account object codes represents
* @param invoiceDetailAccountObjectCodesByCategory a Map of invoice detail account object codes mapped by category
* @param total the total of all of the invoice detail account object codes
* @return A Map keyed by category where the value is the percentage of the total that category represents
*/
protected Map<String, BigDecimal> calculatePercentagesByCategory(Map<String, List<InvoiceDetailAccountObjectCode>> invoiceDetailAccountObjectCodesByCategory, KualiDecimal total) {
Map<String, BigDecimal> percentagesByCategory = new HashMap<>();
for (String categoryCode : invoiceDetailAccountObjectCodesByCategory.keySet()) {
if (total.equals(KualiDecimal.ZERO)) {
percentagesByCategory.put(categoryCode, BigDecimal.ZERO);
} else {
percentagesByCategory.put(categoryCode, calculatePercentageByInvoiceDetailAccountObjectCodes(invoiceDetailAccountObjectCodesByCategory.get(categoryCode), total));
}
}
return percentagesByCategory;
}
/**
* Finds the percentage that the given total is of the sum of the current expenditures of the given invoiceDetailAccountObjectCodes
* @param invoiceDetailAccountObjectCodes a List of invoice detail account object codes to sum
* @param total the total of all of the invoice detail account object codes for that account
* @return the percentage of the total of the given List of invoice detail account object code current expenditures are of the given total
*/
protected BigDecimal calculatePercentageByInvoiceDetailAccountObjectCodes(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, KualiDecimal total) {
final KualiDecimal cumulativeExpenditureTotal = sumInvoiceDetailAccountObjectCodes(invoiceDetailAccountObjectCodes).getCumulativeExpenditures();
return cumulativeExpenditureTotal.bigDecimalValue().divide(total.bigDecimalValue(), 10, RoundingMode.HALF_UP);
}
/**
* Given a Map of category keys mapping percentage values and an amount, find what amount each percentage would be
* @param percentagesByCategory a map of category code keys mapping percentage values
* @param amount the amount to split by percentages
* @return a Map of amounts keyed by category codes
*/
protected Map<String, KualiDecimal> calculateAmountsByCategory(Map<String, BigDecimal> percentagesByCategory, KualiDecimal amount) {
final BigDecimal bigDecimalAmount = amount.bigDecimalValue().setScale(2, RoundingMode.HALF_UP);
Map<String, KualiDecimal> amountsByCategory = new HashMap<>();
for (String categoryCode : percentagesByCategory.keySet()) {
amountsByCategory.put(categoryCode, new KualiDecimal(bigDecimalAmount.multiply(percentagesByCategory.get(categoryCode))));
}
return amountsByCategory;
}
protected void redistributeAmountsToInvoiceAccountCategories(Map<String, List<InvoiceDetailAccountObjectCode>> redistributionAccountObjectCodesByCategory, Map<String, KualiDecimal> amountsByCategory) {
for (String categoryCode : redistributionAccountObjectCodesByCategory.keySet()) {
final List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes = redistributionAccountObjectCodesByCategory.get(categoryCode);
if (invoiceDetailAccountObjectCodes.size() == 1) {
invoiceDetailAccountObjectCodes.get(0).setCurrentExpenditures(amountsByCategory.get(categoryCode));
} else {
splitOutRedistribution(invoiceDetailAccountObjectCodes, amountsByCategory.get(categoryCode));
}
}
}
/**
* If the total of current expenditures within the list of InvoiceDetailAccountObjectCode business objects does not meet the amount to target,
* steal or give a penny from one of those business objects so that it does
* @param invoiceDetailAccountObjectCodes a List of InvoiceDetailAccountObjectCode business objects
* @param amountToTarget the amount which the sum of those objects should equal
*/
protected void takeAPennyLeaveAPennyCGBStyle(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, KualiDecimal amountToTarget) {
if (!CollectionUtils.isEmpty(invoiceDetailAccountObjectCodes)) {
final KualiDecimal currentExpenditureTotal = sumInvoiceDetailAccountObjectCodes(invoiceDetailAccountObjectCodes).getCurrentExpenditures();
if (!currentExpenditureTotal.equals(amountToTarget)) {
final KualiDecimal difference = currentExpenditureTotal.subtract(amountToTarget);
InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode = findFirstPositiveCurrentExpenditureInvoiceDetailAccountObjectCode(invoiceDetailAccountObjectCodes);
if (invoiceDetailAccountObjectCode != null) {
invoiceDetailAccountObjectCode.setCurrentExpenditures(invoiceDetailAccountObjectCode.getCurrentExpenditures().subtract(difference));
}
}
}
}
/**
* Given a list of invoice detail account object codes, return the first one with a positive currentExpenditure field
* @param invoiceDetailAccountObjectCodes the list of InvoiceDetailAccountObjectCodes to find the first one with a positive currentExpenditure
* @return the first invoice detail account object code with a positive currentExpenditure or null if nothing could be found
*/
protected InvoiceDetailAccountObjectCode findFirstPositiveCurrentExpenditureInvoiceDetailAccountObjectCode(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes) {
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) {
if (!ObjectUtils.isNull(invoiceDetailAccountObjectCode.getCurrentExpenditures()) && invoiceDetailAccountObjectCode.getCurrentExpenditures().isPositive()) {
return invoiceDetailAccountObjectCode;
}
}
return null;
}
/**
* Splits an amount evenly over the given List of invoice detail account object codes
* @param invoiceDetailAccountObjectCodes a List of invoice detail account object codes to divvy an amount equally among
* @param amount the amount to divvy
*/
protected void splitOutRedistribution(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, KualiDecimal amount) {
final KualiDecimal amountEach = new KualiDecimal(amount.bigDecimalValue().divide(new BigDecimal(invoiceDetailAccountObjectCodes.size()), 2, RoundingMode.HALF_UP));
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectCodes) {
invoiceDetailAccountObjectCode.setCurrentExpenditures(amountEach);
}
}
/**
* Updates all of the given invoice detail object codes by the billed amount for the given award account (and updates the current expenditures accordingly)
* @param awdAcct the award account to find billing information for
* @param invoiceDetailAccountObjectsCodes the List of invoice detail account object code business objects to update
*/
protected void updateInvoiceDetailAccountObjectCodesByBilledAmount(ContractsAndGrantsBillingAwardAccount awdAcct, List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes) {
List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilledList = retrieveBillingInformationForAwardAccount(awdAcct);
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectsCodes) {
// since there may be multiple accounts represented in the Invoice Detail Account Object Codes, only process the ones that match
if (StringUtils.equals(invoiceDetailAccountObjectCode.getChartOfAccountsCode(), awdAcct.getChartOfAccountsCode()) &&
StringUtils.equals(invoiceDetailAccountObjectCode.getAccountNumber(), awdAcct.getAccountNumber())) {
if (!CollectionUtils.isEmpty(awardAccountObjectCodeTotalBilledList)) {
for (AwardAccountObjectCodeTotalBilled awardAccountObjectCodeTotalBilled : awardAccountObjectCodeTotalBilledList) {
if (invoiceDetailAccountObjectCode.getFinancialObjectCode().equalsIgnoreCase(awardAccountObjectCodeTotalBilled.getFinancialObjectCode())) {
invoiceDetailAccountObjectCode.setTotalBilled(awardAccountObjectCodeTotalBilled.getTotalBilled());
}
}
}
invoiceDetailAccountObjectCode.setCurrentExpenditures(invoiceDetailAccountObjectCode.getCumulativeExpenditures().subtract(invoiceDetailAccountObjectCode.getTotalBilled()));
}
}
}
/**
* Retrieves all of the billing information performed against the given award account
* @param awdAcct a C&G award account
* @return the List of billing information
*/
protected List<AwardAccountObjectCodeTotalBilled> retrieveBillingInformationForAwardAccount(ContractsAndGrantsBillingAwardAccount awdAcct) {
Map<String, Object> totalBilledKeys = new HashMap<String, Object>();
totalBilledKeys.put(KFSPropertyConstants.PROPOSAL_NUMBER, awdAcct.getProposalNumber());
totalBilledKeys.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, awdAcct.getChartOfAccountsCode());
totalBilledKeys.put(KFSPropertyConstants.ACCOUNT_NUMBER, awdAcct.getAccountNumber());
List<AwardAccountObjectCodeTotalBilled> awardAccountObjectCodeTotalBilledList = (List<AwardAccountObjectCodeTotalBilled>) businessObjectService.findMatching(AwardAccountObjectCodeTotalBilled.class, totalBilledKeys);
return awardAccountObjectCodeTotalBilledList;
}
/**
* Determines if today, the document creation date, occurs within the first fiscal period
* @return true if it is the first fiscal period, false otherwise
*/
protected boolean isFirstFiscalPeriod() {
final AccountingPeriod currentPeriod = accountingPeriodService.getByDate(getDateTimeService().getCurrentSqlDate());
final boolean firstFiscalPeriod = StringUtils.equals(currentPeriod.getUniversityFiscalPeriodCode(), KFSConstants.MONTH1);
return firstFiscalPeriod;
}
/**
* @return a Collection of all active Contracts & Grants billing categories
*/
protected Collection<CostCategory> retrieveAllBillingCategories() {
Map<String, Object> criteria = new HashMap<String, Object>();
criteria.put(KFSPropertyConstants.ACTIVE, true);
Collection<CostCategory> costCategories = businessObjectService.findMatching(CostCategory.class, criteria);
return costCategories;
}
/**
* Looks up or constructs an InvoiceDetailAccountObjectCode based on a given balance and billing category
* @param invoiceDetailAccountObjectCodes the list of invoice detail account object codes to find a matching Invoice Detail Account Object Code in
* @param bal the balance to get the account object code from
* @param documentNumber the document number of the CINV doc being created
* @param proposalNumber the proposal number associated with the award on the CINV document we're currently building
* @param costCategory the cost category associated with the balance
* @return the retrieved or constructed (if nothing was found in the database) InvoiceDetailAccountObjectCode object
*/
protected InvoiceDetailAccountObjectCode getInvoiceDetailAccountObjectCodeByBalanceAndCategory(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectCodes, Balance bal, String documentNumber, final Long proposalNumber, CostCategory category) {
// Check if there is an existing invoice detail account object code existing (if there are more than one fiscal years)
InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode = lookupInvoiceDetailAccountObjectCode(invoiceDetailAccountObjectCodes, bal, proposalNumber);
if (ObjectUtils.isNull(invoiceDetailAccountObjectCode)) {
if (!ObjectUtils.isNull(category)) {
invoiceDetailAccountObjectCode = new InvoiceDetailAccountObjectCode();
invoiceDetailAccountObjectCode.setDocumentNumber(documentNumber);
invoiceDetailAccountObjectCode.setProposalNumber(proposalNumber);
invoiceDetailAccountObjectCode.setFinancialObjectCode(bal.getObjectCode());
invoiceDetailAccountObjectCode.setCategoryCode(category.getCategoryCode());
invoiceDetailAccountObjectCode.setAccountNumber(bal.getAccountNumber());
invoiceDetailAccountObjectCode.setChartOfAccountsCode(bal.getChartOfAccountsCode());
invoiceDetailAccountObjectCodes.add(invoiceDetailAccountObjectCode);
} else {
LOG.warn("Could not find cost category for balance: "+bal.getUniversityFiscalYear()+" "+bal.getChartOfAccountsCode()+" "+bal.getAccountNumber()+" "+bal.getSubAccountNumber()+" "+bal.getObjectCode()+" "+bal.getSubObjectCode()+" "+bal.getBalanceTypeCode());
}
}
return invoiceDetailAccountObjectCode;
}
/**
* Looks for a matching invoice detail account object code in the given list that matches the given balance and proposal number
* @param invoiceDetailAccountObjectsCodes a List of invoice detail account object codes to look up values from
* @param bal the balance to match
* @param proposalNumber the proposal number to match
* @return the matching invoice detail account object code record, or null if no matching record can be found
*/
protected InvoiceDetailAccountObjectCode lookupInvoiceDetailAccountObjectCode(List<InvoiceDetailAccountObjectCode> invoiceDetailAccountObjectsCodes, Balance bal, final Long proposalNumber) {
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : invoiceDetailAccountObjectsCodes) {
if (StringUtils.equals(bal.getChartOfAccountsCode(), invoiceDetailAccountObjectCode.getChartOfAccountsCode())
&& StringUtils.equals(bal.getAccountNumber(), invoiceDetailAccountObjectCode.getAccountNumber())
&& StringUtils.equals(bal.getObjectCode(), invoiceDetailAccountObjectCode.getFinancialObjectCode())
&& org.apache.commons.lang.ObjectUtils.equals(proposalNumber, invoiceDetailAccountObjectCode.getProposalNumber())) {
return invoiceDetailAccountObjectCode;
}
}
return null;
}
/**
* Determines if a balance represents a cost share or not
* @param bal the balance to check
* @return true if the balance is a cost share, false otherwise
*/
protected boolean isBalanceCostShare(Balance bal) {
return !ObjectUtils.isNull(bal.getSubAccount()) && !ObjectUtils.isNull(bal.getSubAccount().getA21SubAccount()) && StringUtils.equalsIgnoreCase(bal.getSubAccount().getA21SubAccount().getSubAccountTypeCode(), KFSConstants.SubAccountType.COST_SHARE);
}
/**
* Given the billing frequency code, determines if the billing is time-based: monthly, quarterly, bi-annual, or annual
* @param billingFrequencyCode the billing frequency code
* @return true if time-based billing is used, false if
*/
protected boolean useTimeBasedBillingFrequency(String billingFrequencyCode) {
return billingFrequencyCode.equalsIgnoreCase(ArConstants.MONTHLY_BILLING_SCHEDULE_CODE) || billingFrequencyCode.equalsIgnoreCase(ArConstants.QUATERLY_BILLING_SCHEDULE_CODE) || billingFrequencyCode.equalsIgnoreCase(ArConstants.SEMI_ANNUALLY_BILLING_SCHEDULE_CODE) || billingFrequencyCode.equalsIgnoreCase(ArConstants.ANNUALLY_BILLING_SCHEDULE_CODE);
}
/**
* Retrieves balances used to populate amounts for an invoice account detail
* @param fiscalYear the fiscal year of the balances to find
* @param chartOfAccountsCode the chart of accounts code of balances to find
* @param accountNumber the account number of balances to find
* @param balanceTypeCodeList the balance type codes of balances to find
* @return a List of retrieved balances
*/
protected List<Balance> retrieveBalances(Integer fiscalYear, String chartOfAccountsCode, String accountNumber, List<String> balanceTypeCodeList) {
final SystemOptions systemOptions = optionsService.getOptions(fiscalYear);
Map<String, Object> balanceKeys = new HashMap<String, Object>();
balanceKeys.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
balanceKeys.put(KFSPropertyConstants.ACCOUNT_NUMBER, accountNumber);
balanceKeys.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, fiscalYear);
balanceKeys.put(KFSPropertyConstants.OBJECT_TYPE_CODE, retrieveExpenseObjectTypes());
balanceKeys.put(KFSPropertyConstants.BALANCE_TYPE_CODE,balanceTypeCodeList);
return (List<Balance>)getBusinessObjectService().findMatching(Balance.class, balanceKeys);
}
/**
* Determines if Period 13 should be included in Period 01 calculations for invoice details and invoice account details
* @return true if period 13 should be included, false otherwise
*/
protected boolean includePeriod13InPeriod01Calculations() {
return getParameterService().getParameterValueAsBoolean(ContractsGrantsInvoiceDocument.class, ArParameterKeyConstants.INCLUDE_PERIOD_13_IN_BUDGET_AND_CURRENT_IND_PARM_NM, Boolean.FALSE);
}
/**
* This method helps in setting up basic values for Contracts & Grants Invoice Document
*/
protected void populateContractsGrantsInvoiceDocument(ContractsAndGrantsBillingAward award, ContractsGrantsInvoiceDocument document, List<ContractsGrantsLetterOfCreditReviewDetail> locReviewDetails, String locCreationType) {
if (ObjectUtils.isNotNull(award.getAgency())) {
if (ObjectUtils.isNotNull(document.getAccountsReceivableDocumentHeader())) {
document.getAccountsReceivableDocumentHeader().setCustomerNumber(award.getAgency().getCustomerNumber());
}
Customer customer = getCustomerService().getByPrimaryKey(award.getAgency().getCustomerNumber());
if (ObjectUtils.isNotNull(customer)) {
document.setCustomerName(customer.getCustomerName());
}
}
// To set open invoice indicator to true to help doing cash control for the invoice
document.setOpenInvoiceIndicator(true);
// To set LOC creation type and appropriate values from award.
if (!StringUtils.isBlank(locCreationType)) {
document.getInvoiceGeneralDetail().setLetterOfCreditCreationType(locCreationType);
}
// To set up values for Letter of Credit Fund and Fund Group irrespective of the LOC Creation type.
if (StringUtils.isNotEmpty(award.getLetterOfCreditFundCode())) {
document.getInvoiceGeneralDetail().setLetterOfCreditFundCode(award.getLetterOfCreditFundCode());
}
if (ObjectUtils.isNotNull(award.getLetterOfCreditFund())) {
if (StringUtils.isNotEmpty(award.getLetterOfCreditFund().getLetterOfCreditFundGroupCode())) {
document.getInvoiceGeneralDetail().setLetterOfCreditFundGroupCode(award.getLetterOfCreditFund().getLetterOfCreditFundGroupCode());
}
}
KualiDecimal totalAmountBilledToDate = KualiDecimal.ZERO;
if (document.getInvoiceMilestones().size() > 0) {
totalAmountBilledToDate = calculateMilestoneAmount(document);
}
else if (document.getInvoiceBills().size() > 0) {
totalAmountBilledToDate = calculateTotalBillAmount(document);
}
else {
totalAmountBilledToDate = calculateTotalExpenditureAmount(document, locReviewDetails).add(getContractsGrantsInvoiceDocumentService().getOtherTotalBilledForAwardPeriod(document));
}
document.getInvoiceGeneralDetail().setTotalAmountBilledToDate(totalAmountBilledToDate);
}
protected KualiDecimal calculateMilestoneAmount(ContractsGrantsInvoiceDocument document) {
KualiDecimal totalMilestoneAmount = KualiDecimal.ZERO;
// To calculate the total milestone amount.
if (document.getInvoiceMilestones().size() > 0) {
for (InvoiceMilestone milestone : document.getInvoiceMilestones()) {
if (milestone.getMilestoneAmount() != null) {
totalMilestoneAmount = totalMilestoneAmount.add(milestone.getMilestoneAmount());
}
}
}
totalMilestoneAmount = totalMilestoneAmount.add(document.getInvoiceGeneralDetail().getTotalPreviouslyBilled());
return totalMilestoneAmount;
}
protected KualiDecimal calculateTotalBillAmount(ContractsGrantsInvoiceDocument document) {
KualiDecimal totalBillAmount = KualiDecimal.ZERO;
// To calculate the total bill amount.
if (document.getInvoiceBills().size() > 0) {
for (InvoiceBill bill : document.getInvoiceBills()) {
if (bill.getEstimatedAmount() != null) {
totalBillAmount = totalBillAmount.add(bill.getEstimatedAmount());
}
}
}
totalBillAmount = totalBillAmount.add(document.getInvoiceGeneralDetail().getTotalPreviouslyBilled());
return totalBillAmount;
}
protected KualiDecimal calculateTotalExpenditureAmount(ContractsGrantsInvoiceDocument document, List<ContractsGrantsLetterOfCreditReviewDetail> locReviewDetails) {
Map<String, KualiDecimal> totalBilledByAccountNumberMap = new HashMap<String, KualiDecimal>();
for (InvoiceDetailAccountObjectCode invoiceDetailAccountObjectCode : document.getInvoiceDetailAccountObjectCodes()) {
String key = invoiceDetailAccountObjectCode.getChartOfAccountsCode()+"-"+invoiceDetailAccountObjectCode.getAccountNumber();
KualiDecimal totalBilled = cleanAmount(totalBilledByAccountNumberMap.get(key));
totalBilled = totalBilled.add(invoiceDetailAccountObjectCode.getTotalBilled());
totalBilledByAccountNumberMap.put(key, totalBilled);
}
KualiDecimal totalExpendituredAmount = KualiDecimal.ZERO;
for (InvoiceAccountDetail invAcctD : document.getAccountDetails()) {
KualiDecimal currentExpenditureAmount = KualiDecimal.ZERO;
if (!ObjectUtils.isNull(totalBilledByAccountNumberMap.get(invAcctD.getChartOfAccountsCode()+"-"+invAcctD.getAccountNumber()))) {
invAcctD.setTotalPreviouslyBilled(totalBilledByAccountNumberMap.get(invAcctD.getChartOfAccountsCode()+"-"+invAcctD.getAccountNumber()));
} else {
invAcctD.setTotalPreviouslyBilled(KualiDecimal.ZERO);
}
currentExpenditureAmount = invAcctD.getCumulativeExpenditures().subtract(invAcctD.getTotalPreviouslyBilled());
invAcctD.setInvoiceAmount(currentExpenditureAmount);
// overwriting account detail expenditure amount if locReview Indicator is true - and award belongs to LOC Billing
if (!ObjectUtils.isNull(document.getInvoiceGeneralDetail())) {
ContractsAndGrantsBillingAward award = document.getInvoiceGeneralDetail().getAward();
if (ObjectUtils.isNotNull(award) && StringUtils.equalsIgnoreCase(award.getBillingFrequencyCode(), ArConstants.LOC_BILLING_SCHEDULE_CODE) && !CollectionUtils.isEmpty(locReviewDetails)) {
for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
final ContractsGrantsLetterOfCreditReviewDetail locReviewDetail = retrieveMatchingLetterOfCreditReviewDetail(awardAccount, locReviewDetails);
if (!ObjectUtils.isNull(locReviewDetail) && StringUtils.equals(awardAccount.getChartOfAccountsCode(), invAcctD.getChartOfAccountsCode()) && StringUtils.equals(awardAccount.getAccountNumber(), invAcctD.getAccountNumber())) {
currentExpenditureAmount = locReviewDetail.getAmountToDraw();
invAcctD.setInvoiceAmount(currentExpenditureAmount);
}
}
}
}
totalExpendituredAmount = totalExpendituredAmount.add(currentExpenditureAmount);
}
totalExpendituredAmount = totalExpendituredAmount.add(document.getInvoiceGeneralDetail().getTotalPreviouslyBilled());
return totalExpendituredAmount;
}
/**
* This method would make sure the amounts of the current period are not included. So it calculates the cumulative and
* subtracts the current period values. This would be done for Billing Frequencies - Monthly, Quarterly, Semi-Annual and Annual.
*
* @param glBalance
* @return balanceAmount
*/
protected KualiDecimal calculateBalanceAmountWithoutLastBilledPeriod(java.sql.Date lastBilledDate, Balance glBalance) {
Timestamp ts = new Timestamp(new java.util.Date().getTime());
java.sql.Date today = new java.sql.Date(ts.getTime());
AccountingPeriod currPeriod = accountingPeriodService.getByDate(today);
String currentPeriodCode = currPeriod.getUniversityFiscalPeriodCode();
KualiDecimal currentBalanceAmount = KualiDecimal.ZERO;
switch (currentPeriodCode) {
case KFSConstants.MONTH13:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth12Amount()));
// notice - no break!!!! we want to fall through to pick up all the prior months amounts
case KFSConstants.MONTH12:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth11Amount()));
case KFSConstants.MONTH11:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth10Amount()));
case KFSConstants.MONTH10:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth9Amount()));
case KFSConstants.MONTH9:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth8Amount()));
case KFSConstants.MONTH8:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth7Amount()));
case KFSConstants.MONTH7:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth6Amount()));
case KFSConstants.MONTH6:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth5Amount()));
case KFSConstants.MONTH5:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth4Amount()));
case KFSConstants.MONTH4:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth3Amount()));
case KFSConstants.MONTH3:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth2Amount()));
case KFSConstants.MONTH2:
currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth1Amount()));
}
return glBalance.getContractsGrantsBeginningBalanceAmount().add(currentBalanceAmount);
}
/**
* Null protects the addition in retrieveAccurateBalanceAmount
* @param amount the amount to return
* @return zero if the amount was null, the given amount otherwise
*/
protected KualiDecimal cleanAmount(KualiDecimal amount) {
return amount == null ? KualiDecimal.ZERO : amount;
}
/**
* @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#retrieveNonLOCAwards()
*/
@Override
public Collection<ContractsAndGrantsBillingAward> retrieveNonLOCAwards() {
Map<String, Object> map = new HashMap<String, Object>();
map.put(KFSPropertyConstants.ACTIVE, true);
// It would be nice not to have to manually remove LOC awards, maybe when we convert to KRAD
// we could leverage the KRAD-DATA Criteria framework to avoid this
Collection<ContractsAndGrantsBillingAward> awards = kualiModuleService.getResponsibleModuleService(ContractsAndGrantsBillingAward.class).getExternalizableBusinessObjectsList(ContractsAndGrantsBillingAward.class, map);
Iterator<ContractsAndGrantsBillingAward> it = awards.iterator();
while (it.hasNext()) {
ContractsAndGrantsBillingAward award = it.next();
if (StringUtils.equalsIgnoreCase(award.getBillingFrequencyCode(), ArConstants.LOC_BILLING_SCHEDULE_CODE)) {
it.remove();
}
}
return awards;
}
/**
* @see org.kuali.kfs.module.ar.batch.service.ContractsGrantsInvoiceCreateDocumentService#validateAwards(java.util.Collection, java.util.Collection)
*/
@Override
public Collection<ContractsAndGrantsBillingAward> validateAwards(Collection<ContractsAndGrantsBillingAward> awards, Collection<ContractsGrantsInvoiceDocumentErrorLog> contractsGrantsInvoiceDocumentErrorLogs, String errOutputFile, String creationProcessTypeCode) {
Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup = new HashMap<ContractsAndGrantsBillingAward, List<String>>();
List<ContractsAndGrantsBillingAward> qualifiedAwards = new ArrayList<ContractsAndGrantsBillingAward>();
if (ObjectUtils.isNull(contractsGrantsInvoiceDocumentErrorLogs)) {
contractsGrantsInvoiceDocumentErrorLogs = new ArrayList<ContractsGrantsInvoiceDocumentErrorLog>();
}
performAwardValidation(awards, invalidGroup, qualifiedAwards);
if (!CollectionUtils.isEmpty(invalidGroup)) {
if (StringUtils.isNotBlank(errOutputFile)) {
writeErrorToFile(invalidGroup, errOutputFile);
}
storeValidationErrors(invalidGroup, contractsGrantsInvoiceDocumentErrorLogs, creationProcessTypeCode);
}
return qualifiedAwards;
}
/**
* Perform all validation checks on the awards passed in to determine if CGB Invoice documents can be
* created for the given awards.
*
* @param awards to be validated
* @param invalidGroup Map of errors per award that failed validation
* @param qualifiedAwards List of awards that are valid to create CGB Invoice docs from
*/
protected void performAwardValidation(Collection<ContractsAndGrantsBillingAward> awards, Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup, List<ContractsAndGrantsBillingAward> qualifiedAwards) {
for (ContractsAndGrantsBillingAward award : awards) {
List<String> errorList = new ArrayList<String>();
if (award.getAwardBeginningDate() != null) {
if (award.getBillingFrequencyCode() != null && getContractsGrantsBillingAwardVerificationService().isValueOfBillingFrequencyValid(award)) {
if (verifyBillingFrequencyService.validateBillingFrequency(award)) {
validateAward(errorList, award);
} else {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_INVALID_BILLING_PERIOD));
}
} else {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_BILLING_FREQUENCY_MISSING_ERROR));
}
} else {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_START_DATE_MISSING_ERROR));
}
if (errorList.size() > 0) {
invalidGroup.put(award, errorList);
} else {
qualifiedAwards.add(award);
}
}
}
/**
* Perform validation for an award to determine if a CGB Invoice document can be created for the award.
*
* @param errorList list of validation errors per award
* @param award to perform validation upon
*/
protected void validateAward(List<String> errorList, ContractsAndGrantsBillingAward award) {
// 1. Award is excluded from invoicing
if (award.isExcludedFromInvoicing()) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_EXCLUDED_FROM_INVOICING));
}
// 2. Award is Inactive
if (!award.isActive()) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_INACTIVE_ERROR));
}
// 4. Award invoicing option is missing
if (StringUtils.isEmpty(award.getInvoicingOptionCode())) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_INVOICING_OPTION_MISSING_ERROR));
}
// 5. Award billing frequency is not set correctly
if (!getContractsGrantsBillingAwardVerificationService().isBillingFrequencySetCorrectly(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_SINGLE_ACCOUNT_ERROR));
}
// 6. Award has no accounts assigned
if (CollectionUtils.isEmpty(award.getActiveAwardAccounts())) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_NO_ACTIVE_ACCOUNTS_ASSIGNED_ERROR));
}
// 7. Award contains expired account or accounts
Collection<Account> expAccounts = getContractsGrantsInvoiceDocumentService().getExpiredAccountsOfAward(award);
if (ObjectUtils.isNotNull(expAccounts) && !expAccounts.isEmpty()) {
StringBuilder line = new StringBuilder();
line.append(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_CONAINS_EXPIRED_ACCOUNTS_ERROR));
for (Account expAccount : expAccounts) {
line.append(" (expired account: " + expAccount.getAccountNumber() + " expiration date " + expAccount.getAccountExpirationDate() + ") ");
}
errorList.add(line.toString());
}
// 8. Award has final invoice Billed already
if (getContractsGrantsBillingAwardVerificationService().isAwardFinalInvoiceAlreadyBuilt(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_FINAL_BILLED_ERROR));
}
// 9. Award has no valid milestones to invoice
if (!getContractsGrantsBillingAwardVerificationService().hasMilestonesToInvoice(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_NO_VALID_MILESTONES));
}
// 10. All has no valid bills to invoice
if (!getContractsGrantsBillingAwardVerificationService().hasBillsToInvoice(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_NO_VALID_BILLS));
}
// 11. Agency has no matching Customer record
if (!getContractsGrantsBillingAwardVerificationService().owningAgencyHasCustomerRecord(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_AGENCY_NO_CUSTOMER_RECORD));
}
// 12. All accounts of an Award have zero$ to invoice
if (!hasBillableAccounts(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_AWARD_NO_VALID_ACCOUNTS));
}
// 13. Award does not have appropriate Contract Control Accounts set based on Invoicing Options
List<String> errorString = contractsGrantsInvoiceDocumentService.checkAwardContractControlAccounts(award);
if (!CollectionUtils.isEmpty(errorString) && errorString.size() > 1) {
errorList.add(configurationService.getPropertyValueAsString(errorString.get(0)).replace("{0}", errorString.get(1)));
}
// 14. System Information and ORganization Accounting Default not setup.
if (!getContractsGrantsBillingAwardVerificationService().isChartAndOrgSetupForInvoicing(award)) {
errorList.add(configurationService.getPropertyValueAsString(ArKeyConstants.CGINVOICE_CREATION_SYS_INFO_OADF_NOT_SETUP));
}
}
protected void writeErrorToFile(Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup, String errOutputFile) {
PrintStream outputFileStream = null;
File errOutPutfile = new File(errOutputFile);
try {
outputFileStream = new PrintStream(errOutPutfile);
writeReportHeader(outputFileStream);
for (ContractsAndGrantsBillingAward award : invalidGroup.keySet()) {
writeErrorEntryByAward(award, invalidGroup.get(award), outputFileStream);
}
outputFileStream.printf("\r\n");
} catch (IOException ioe) {
LOG.error("Could not write errors in Contracts & Grants Invoice Document creation process to file" + ioe.getMessage());
throw new RuntimeException("Could not write errors in Contracts & Grants Invoice Document creation process to file", ioe);
} finally {
if (outputFileStream != null) {
outputFileStream.close();
}
}
}
protected void storeValidationErrors(Map<ContractsAndGrantsBillingAward, List<String>> invalidGroup, Collection<ContractsGrantsInvoiceDocumentErrorLog> contractsGrantsInvoiceDocumentErrorLogs, String creationProcessTypeCode) {
for (ContractsAndGrantsBillingAward award : invalidGroup.keySet()) {
KualiDecimal cumulativeExpenses = KualiDecimal.ZERO;
ContractsGrantsInvoiceDocumentErrorLog contractsGrantsInvoiceDocumentErrorLog = new ContractsGrantsInvoiceDocumentErrorLog();
if (ObjectUtils.isNotNull(award)){
String proposalNumber = award.getProposalNumber().toString();
Date beginningDate = award.getAwardBeginningDate();
Date endingDate = award.getAwardEndingDate();
KualiDecimal totalAmount = award.getAwardTotalAmount();
final SystemOptions systemOptions = optionsService.getCurrentYearOptions();
contractsGrantsInvoiceDocumentErrorLog.setProposalNumber(award.getProposalNumber());
contractsGrantsInvoiceDocumentErrorLog.setAwardBeginningDate(beginningDate);
contractsGrantsInvoiceDocumentErrorLog.setAwardEndingDate(endingDate);
contractsGrantsInvoiceDocumentErrorLog.setAwardTotalAmount(award.getAwardTotalAmount().bigDecimalValue());
if (ObjectUtils.isNotNull(award.getAwardPrimaryFundManager())) {
contractsGrantsInvoiceDocumentErrorLog.setPrimaryFundManagerPrincipalId(award.getAwardPrimaryFundManager().getPrincipalId());
}
if (!CollectionUtils.isEmpty(award.getActiveAwardAccounts())) {
boolean firstLineFlag = true;
for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
cumulativeExpenses = cumulativeExpenses.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, systemOptions.getActualFinancialBalanceTypeCd(), beginningDate));
if (firstLineFlag) {
firstLineFlag = false;
contractsGrantsInvoiceDocumentErrorLog.setAccounts(awardAccount.getAccountNumber());
}
else {
contractsGrantsInvoiceDocumentErrorLog.setAccounts(contractsGrantsInvoiceDocumentErrorLog.getAccounts() + ";" + awardAccount.getAccountNumber());
}
}
}
contractsGrantsInvoiceDocumentErrorLog.setCumulativeExpensesAmount(cumulativeExpenses.bigDecimalValue());
}
for (String vCat : invalidGroup.get(award)) {
ContractsGrantsInvoiceDocumentErrorMessage contractsGrantsInvoiceDocumentErrorCategory = new ContractsGrantsInvoiceDocumentErrorMessage();
contractsGrantsInvoiceDocumentErrorCategory.setErrorMessageText(vCat);
contractsGrantsInvoiceDocumentErrorLog.getErrorMessages().add(contractsGrantsInvoiceDocumentErrorCategory);
}
contractsGrantsInvoiceDocumentErrorLog.setErrorDate(dateTimeService.getCurrentTimestamp());
contractsGrantsInvoiceDocumentErrorLog.setCreationProcessTypeCode(creationProcessTypeCode);
businessObjectService.save(contractsGrantsInvoiceDocumentErrorLog);
contractsGrantsInvoiceDocumentErrorLogs.add(contractsGrantsInvoiceDocumentErrorLog);
}
}
protected void storeCreationErrors(List<ErrorMessage> errorMessages, String creationProcessTypeCode) {
for (ErrorMessage errorMessage : errorMessages) {
ContractsGrantsInvoiceDocumentErrorLog contractsGrantsInvoiceDocumentErrorLog = new ContractsGrantsInvoiceDocumentErrorLog();
ContractsGrantsInvoiceDocumentErrorMessage contractsGrantsInvoiceDocumentErrorCategory = new ContractsGrantsInvoiceDocumentErrorMessage();
contractsGrantsInvoiceDocumentErrorCategory.setErrorMessageText(MessageFormat.format(configurationService.getPropertyValueAsString(errorMessage.getErrorKey()), (Object[])errorMessage.getMessageParameters()));
contractsGrantsInvoiceDocumentErrorLog.getErrorMessages().add(contractsGrantsInvoiceDocumentErrorCategory);
contractsGrantsInvoiceDocumentErrorLog.setErrorDate(dateTimeService.getCurrentTimestamp());
contractsGrantsInvoiceDocumentErrorLog.setCreationProcessTypeCode(creationProcessTypeCode);
businessObjectService.save(contractsGrantsInvoiceDocumentErrorLog);
}
}
/**
* This method retrieves all the Contracts & Grants Invoice Documents with a status of Saved and
* routes them to the next step in the routing path.
*
* @return True if the routing was performed successfully. A runtime exception will be thrown if any errors occur while routing.
* @see org.kuali.kfs.module.ar.batch.service.ContractsGrantsInvoiceDocumentCreateService#routeContractsGrantsInvoiceDocuments()
*/
@Override
public void routeContractsGrantsInvoiceDocuments() {
final String currentUserPrincipalId = GlobalVariables.getUserSession().getPerson().getPrincipalId();
List<String> documentIdList = retrieveContractsGrantsInvoiceDocumentsToRoute(DocumentStatus.SAVED, currentUserPrincipalId);
if (LOG.isInfoEnabled()) {
LOG.info("CGinvoice to Route: " + documentIdList);
}
for (String cgInvoiceDocId : documentIdList) {
try {
ContractsGrantsInvoiceDocument cgInvoicDoc = (ContractsGrantsInvoiceDocument) documentService.getByDocumentHeaderId(cgInvoiceDocId);
// To route documents only if the user in the session is same as the initiator.
if (LOG.isInfoEnabled()) {
LOG.info("Routing Contracts & Grants Invoice document # " + cgInvoiceDocId + ".");
}
documentService.prepareWorkflowDocument(cgInvoicDoc);
// calling workflow service to bypass business rule checks
workflowDocumentService.route(cgInvoicDoc.getDocumentHeader().getWorkflowDocument(), "", null);
} catch (WorkflowException e) {
LOG.error("Error routing document # " + cgInvoiceDocId + " " + e.getMessage());
throw new RuntimeException(e.getMessage(), e);
}
}
}
/**
* Returns a list of all saved but not yet routed Contracts & Grants Invoice Documents, using the KualiWorkflowInfo service.
*
* @return a list of Contracts & Grants Invoice Documents to route
*/
protected List<String> retrieveContractsGrantsInvoiceDocumentsToRoute(DocumentStatus statusCode, String initiatorPrincipalId) {
List<String> documentIds = new ArrayList<String>();
Map<String, Object> fieldValues = new HashMap<String, Object>();
fieldValues.put(KFSPropertyConstants.WORKFLOW_DOCUMENT_TYPE_NAME, ArConstants.ArDocumentTypeCodes.CONTRACTS_GRANTS_INVOICE);
fieldValues.put(KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE, statusCode.getCode());
fieldValues.put(KFSPropertyConstants.INITIATOR_PRINCIPAL_ID, initiatorPrincipalId);
Collection<FinancialSystemDocumentHeader> docHeaders = businessObjectService.findMatching(FinancialSystemDocumentHeader.class, fieldValues);
for (FinancialSystemDocumentHeader docHeader : docHeaders) {
documentIds.add(docHeader.getDocumentNumber());
}
return documentIds;
}
protected void writeErrorEntryByAward(ContractsAndGrantsBillingAward award, List<String> validationCategory, PrintStream printStream) throws IOException {
// %15s %18s %20s %19s %15s %18s %23s %18s
if (ObjectUtils.isNotNull(award)){
KualiDecimal cumulativeExpenses = KualiDecimal.ZERO;
String awardBeginningDate;
String awardEndingDate;
String awardTotalAmount;
String proposalNumber = award.getProposalNumber().toString();
Date beginningDate = award.getAwardBeginningDate();
Date endingDate = award.getAwardEndingDate();
KualiDecimal totalAmount = award.getAwardTotalAmount();
if (ObjectUtils.isNotNull(beginningDate)) {
awardBeginningDate = beginningDate.toString();
} else {
awardBeginningDate = "null award beginning date";
}
if (ObjectUtils.isNotNull(endingDate)) {
awardEndingDate = endingDate.toString();
} else {
awardEndingDate = "null award ending date";
}
if (ObjectUtils.isNotNull(totalAmount) && ObjectUtils.isNotNull(totalAmount.bigDecimalValue())) {
awardTotalAmount = totalAmount.toString();
} else {
awardTotalAmount = "null award total amount";
}
if (CollectionUtils.isEmpty(award.getActiveAwardAccounts())) {
writeToReport(proposalNumber, "", awardBeginningDate, awardEndingDate, awardTotalAmount, cumulativeExpenses.toString(), printStream);
}
else {
final SystemOptions systemOptions = optionsService.getCurrentYearOptions();
// calculate cumulativeExpenses
for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
cumulativeExpenses = cumulativeExpenses.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, systemOptions.getActualFinancialBalanceTypeCd(), award.getAwardBeginningDate()));
}
boolean firstLineFlag = true;
for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
if (firstLineFlag) {
writeToReport(proposalNumber, awardAccount.getAccountNumber(), awardBeginningDate, awardEndingDate, awardTotalAmount, cumulativeExpenses.toString(), printStream);
firstLineFlag = false;
}
else {
writeToReport("", awardAccount.getAccountNumber(), "", "", "", "", printStream);
}
}
}
}
// To print all the errors from the validation category.
for (String vCat : validationCategory) {
printStream.printf("%s", " " + vCat);
printStream.printf("\r\n");
}
printStream.printf(REPORT_LINE_DIVIDER);
printStream.printf("\r\n");
}
protected void writeToReport(String proposalNumber, String accountNumber, String awardBeginningDate, String awardEndingDate, String awardTotalAmount, String cumulativeExpenses, PrintStream printStream) throws IOException {
printStream.printf("%15s", proposalNumber);
printStream.printf("%18s", accountNumber);
printStream.printf("%20s", awardBeginningDate);
printStream.printf("%19s", awardEndingDate);
printStream.printf("%15s", awardTotalAmount);
printStream.printf("%23s", cumulativeExpenses);
printStream.printf("\r\n");
}
/**
* @param printStream
* @throws IOException
*/
protected void writeReportHeader(PrintStream printStream) throws IOException {
printStream.printf("%15s%18s%20s%19s%15s%23s\r\n", "Proposal Number", "Account Number", "Award Start Date", "Award Stop Date", "Award Total", "Cumulative Expenses");
printStream.printf("%23s", "Validation Category");
printStream.printf("\r\n");
printStream.printf(REPORT_LINE_DIVIDER);
printStream.printf("\r\n");
}
protected boolean hasBillableAccounts(ContractsAndGrantsBillingAward award) {
String billingFrequencyCode = award.getBillingFrequencyCode();
if (StringUtils.equalsIgnoreCase(billingFrequencyCode, ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) ||
StringUtils.equalsIgnoreCase(billingFrequencyCode, ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
return !getContractsGrantsBillingAwardVerificationService().isInvoiceInProgress(award);
} else {
return CollectionUtils.isEmpty(award.getActiveAwardAccounts()) || !CollectionUtils.isEmpty(getValidAwardAccounts(award.getActiveAwardAccounts(), award));
}
}
/**
* This method returns the valid award accounts based on evaluation of billing frequency and invoice document status
*
* @param awardAccounts
* @return valid awardAccounts
*/
protected List<ContractsAndGrantsBillingAwardAccount> getValidAwardAccounts(List<ContractsAndGrantsBillingAwardAccount> awardAccounts, ContractsAndGrantsBillingAward award) {
if (!award.getBillingFrequencyCode().equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) && !award.getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
List<ContractsAndGrantsBillingAwardAccount> validAwardAccounts = new ArrayList<ContractsAndGrantsBillingAwardAccount>();
Set<Account> invalidAccounts = harvestAccountsFromContractsGrantsInvoices(getInProgressInvoicesForAward(award));
for (ContractsAndGrantsBillingAwardAccount awardAccount : awardAccounts) {
if (!invalidAccounts.contains(awardAccount.getAccount())) {
if (verifyBillingFrequencyService.validateBillingFrequency(award, awardAccount)) {
validAwardAccounts.add(awardAccount);
}
}
}
return validAwardAccounts;
}
else {
return awardAccounts;
}
}
/**
* Pulls all the unique accounts from the source accounting lines on the given ContractsGrantsInvoiceDocument
* @param contractsGrantsInvoices the invoices to pull unique accounts from
* @return a Set of the unique accounts
*/
protected Set<Account> harvestAccountsFromContractsGrantsInvoices(Collection<ContractsGrantsInvoiceDocument> contractsGrantsInvoices) {
Set<Account> accounts = new HashSet<Account>();
for (ContractsGrantsInvoiceDocument invoice : contractsGrantsInvoices) {
for (InvoiceAccountDetail invoiceAccountDetail : invoice.getAccountDetails()) {
final Account account = getAccountService().getByPrimaryId(invoiceAccountDetail.getChartOfAccountsCode(), invoiceAccountDetail.getAccountNumber());
if (!ObjectUtils.isNull(account)) {
accounts.add(account);
}
}
}
return accounts;
}
/**
* Looks up all the in progress contracts & grants invoices for the award
* @param award the award to look up contracts & grants invoices for
* @return a Collection matching in progress/pending Contracts & Grants Invoice documents
*/
protected Collection<ContractsGrantsInvoiceDocument> getInProgressInvoicesForAward(ContractsAndGrantsBillingAward award) {
Map<String, Object> fieldValues = new HashMap<String, Object>();
fieldValues.put(ArPropertyConstants.ContractsGrantsInvoiceDocumentFields.PROPOSAL_NUMBER, award.getProposalNumber());
fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER+"."+KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE, financialSystemDocumentService.getPendingDocumentStatuses());
return businessObjectService.findMatching(ContractsGrantsInvoiceDocument.class, fieldValues);
}
/**
* Retrieve expense object types by the basic accounting category for expenses
* @see org.kuali.kfs.module.ar.service.ContractsGrantsInvoiceCreateDocumentService#retrieveExpenseObjectTypes()
*/
@Override
public Collection<String> retrieveExpenseObjectTypes() {
List<String> objectTypeCodes = new ArrayList<>();
Map<String, Object> fieldValues = new HashMap<>();
fieldValues.put(KFSPropertyConstants.BASIC_ACCOUNTING_CATEGORY_CODE, KFSConstants.BasicAccountingCategoryCodes.EXPENSES);
final Collection<ObjectType> objectTypes = getBusinessObjectService().findMatching(ObjectType.class, fieldValues);
for (ObjectType objectType : objectTypes) {
objectTypeCodes.add(objectType.getCode());
}
return objectTypeCodes;
}
public AccountService getAccountService() {
return accountService;
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
/**
* Sets the accountingPeriodService attribute value.
*
* @param accountingPeriodService The accountingPeriodService to set.
*/
public void setAccountingPeriodService(AccountingPeriodService accountingPeriodService) {
this.accountingPeriodService = accountingPeriodService;
}
/**
* Sets the verifyBillingFrequencyService attribute value.
*
* @param verifyBillingFrequencyService The verifyBillingFrequencyService to set.
*/
public void setVerifyBillingFrequencyService(VerifyBillingFrequencyService verifyBillingFrequencyService) {
this.verifyBillingFrequencyService = verifyBillingFrequencyService;
}
public BusinessObjectService getBusinessObjectService() {
return businessObjectService;
}
/**
* Sets the businessObjectService attribute value.
*
* @param businessObjectService The businessObjectService to set.
*/
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
/**
* Sets the workflowDocumentService attribute value.
*
* @param workflowDocumentService The workflowDocumentService to set.
*/
public void setWorkflowDocumentService(WorkflowDocumentService workflowDocumentService) {
this.workflowDocumentService = workflowDocumentService;
}
/**
* Sets the documentService attribute value.
*
* @param documentService The documentService to set.
*/
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
/**
* Sets the accountsReceivableDocumentHeaderService attribute value.
*
* @param accountsReceivableDocumentHeaderService The accountsReceivableDocumentHeaderService to set.
*/
public void setAccountsReceivableDocumentHeaderService(AccountsReceivableDocumentHeaderService accountsReceivableDocumentHeaderService) {
this.accountsReceivableDocumentHeaderService = accountsReceivableDocumentHeaderService;
}
/**
* Sets the contractsGrantsInvoiceDocumentService attribute value.
*
* @param contractsGrantsInvoiceDocumentService The contractsGrantsInvoiceDocumentService to set.
*/
public void setContractsGrantsInvoiceDocumentService(ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService) {
this.contractsGrantsInvoiceDocumentService = contractsGrantsInvoiceDocumentService;
}
public ContractsGrantsInvoiceDocumentService getContractsGrantsInvoiceDocumentService() {
return contractsGrantsInvoiceDocumentService;
}
public DateTimeService getDateTimeService() {
return dateTimeService;
}
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
/**
* Sets the kualiModuleService attribute value.
*
* @param kualiModuleService The kualiModuleService to set.
*/
public void setKualiModuleService(KualiModuleService kualiModuleService) {
this.kualiModuleService = kualiModuleService;
}
public ConfigurationService getConfigurationService() {
return configurationService;
}
public void setConfigurationService(ConfigurationService configurationService) {
this.configurationService = configurationService;
}
public ContractsGrantsBillingUtilityService getContractsGrantsBillingUtilityService() {
return contractsGrantsBillingUtilityService;
}
public void setContractsGrantsBillingUtilityService(ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService) {
this.contractsGrantsBillingUtilityService = contractsGrantsBillingUtilityService;
}
public ContractsAndGrantsModuleBillingService getContractsAndGrantsModuleBillingService() {
return contractsAndGrantsModuleBillingService;
}
public void setContractsAndGrantsModuleBillingService(ContractsAndGrantsModuleBillingService contractsAndGrantsModuleBillingService) {
this.contractsAndGrantsModuleBillingService = contractsAndGrantsModuleBillingService;
}
public FinancialSystemDocumentService getFinancialSystemDocumentService() {
return financialSystemDocumentService;
}
public void setFinancialSystemDocumentService(FinancialSystemDocumentService financialSystemDocumentService) {
this.financialSystemDocumentService = financialSystemDocumentService;
}
public UniversityDateService getUniversityDateService() {
return universityDateService;
}
public void setUniversityDateService(UniversityDateService universityDateService) {
this.universityDateService = universityDateService;
}
public AwardAccountObjectCodeTotalBilledDao getAwardAccountObjectCodeTotalBilledDao() {
return awardAccountObjectCodeTotalBilledDao;
}
public void setAwardAccountObjectCodeTotalBilledDao(AwardAccountObjectCodeTotalBilledDao awardAccountObjectCodeTotalBilledDao) {
this.awardAccountObjectCodeTotalBilledDao = awardAccountObjectCodeTotalBilledDao;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public ParameterService getParameterService() {
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public ContractsGrantsBillingAwardVerificationService getContractsGrantsBillingAwardVerificationService() {
return contractsGrantsBillingAwardVerificationService;
}
public void setContractsGrantsBillingAwardVerificationService(ContractsGrantsBillingAwardVerificationService contractsGrantsBillingAwardVerificationService) {
this.contractsGrantsBillingAwardVerificationService = contractsGrantsBillingAwardVerificationService;
}
public CostCategoryService getCostCategoryService() {
return costCategoryService;
}
public void setCostCategoryService(CostCategoryService costCategoryService) {
this.costCategoryService = costCategoryService;
}
public OptionsService getOptionsService() {
return optionsService;
}
public void setOptionsService(OptionsService optionsService) {
this.optionsService = optionsService;
}
}
|
package com.robrua.orianna.api.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.robrua.orianna.api.Utils;
import com.robrua.orianna.api.dto.BaseRiotAPI;
import com.robrua.orianna.type.api.LoadPolicy;
import com.robrua.orianna.type.core.staticdata.Champion;
import com.robrua.orianna.type.core.staticdata.Item;
import com.robrua.orianna.type.core.staticdata.MapDetails;
import com.robrua.orianna.type.core.staticdata.Mastery;
import com.robrua.orianna.type.core.staticdata.Realm;
import com.robrua.orianna.type.core.staticdata.Rune;
import com.robrua.orianna.type.core.staticdata.SummonerSpell;
import com.robrua.orianna.type.dto.staticdata.ChampionList;
import com.robrua.orianna.type.dto.staticdata.ItemList;
import com.robrua.orianna.type.dto.staticdata.MapData;
import com.robrua.orianna.type.dto.staticdata.MasteryList;
import com.robrua.orianna.type.dto.staticdata.RuneList;
import com.robrua.orianna.type.dto.staticdata.SummonerSpellList;
public abstract class StaticDataAPI {
private static Set<Long> IGNORE_ITEMS = new HashSet<>(Arrays.asList(new Long[] {0L, 3210L, 3207L, 3176L, 3005L, 3131L, 2040L, 2039L, 3186L, 2037L, 3128L}));
/**
* @param ID
* the ID of the champion to get
* @return the champion
*/
public synchronized static Champion getChampion(final long ID) {
Champion champion = RiotAPI.store.get(Champion.class, ID);
if(champion != null) {
return champion;
}
final com.robrua.orianna.type.dto.staticdata.Champion champ = BaseRiotAPI.getChampion(ID);
if(champ == null) {
return null;
}
champion = new Champion(champ);
if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) {
RiotAPI.getItems(new ArrayList<>(champ.getItemIDs()));
}
RiotAPI.store.store(champion, ID);
return champion;
}
/**
* @return all the champions
*/
public synchronized static List<Champion> getChampions() {
List<Champion> champions = RiotAPI.store.getAll(Champion.class);
if(champions != null) {
return champions;
}
final ChampionList champs = BaseRiotAPI.getChampions();
champions = new ArrayList<>(champs.getData().size());
final List<Long> IDs = new ArrayList<>(champions.size());
for(final com.robrua.orianna.type.dto.staticdata.Champion champ : champs.getData().values()) {
champions.add(new Champion(champ));
IDs.add(champ.getId().longValue());
}
if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) {
RiotAPI.getItems(new ArrayList<>(champs.getItemIDs()));
}
RiotAPI.store.store(champions, IDs, true);
return Collections.unmodifiableList(champions);
}
/**
* @param IDs
* the IDs of the champions to get
* @return the champions
*/
public synchronized static List<Champion> getChampions(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Champion> champions = RiotAPI.store.get(Champion.class, IDs);
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(champions.get(i) == null) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return champions;
}
if(toGet.size() == 1) {
champions.set(index.get(0), getChampion(toGet.get(0)));
return champions;
}
getChampions();
final List<Champion> gotten = RiotAPI.store.get(Champion.class, toGet);
int count = 0;
for(final Integer id : index) {
champions.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(champions);
}
/**
* @param IDs
* the IDs of the champions to get
* @return the champions
*/
public static List<Champion> getChampions(final long... IDs) {
return getChampions(Utils.convert(IDs));
}
/**
* @param ID
* the ID of the item to get
* @return the item
*/
public synchronized static Item getItem(final long ID) {
if(IGNORE_ITEMS.contains(ID)) {
return null;
}
Item item = RiotAPI.store.get(Item.class, ID);
if(item != null) {
return item;
}
final com.robrua.orianna.type.dto.staticdata.Item it = BaseRiotAPI.getItem(ID);
item = new Item(it);
RiotAPI.store.store(item, ID);
return item;
}
/**
* @return all the items
*/
public synchronized static List<Item> getItems() {
List<Item> items = RiotAPI.store.getAll(Item.class);
if(items != null) {
return items;
}
final ItemList its = BaseRiotAPI.getItems();
items = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(items.size());
for(final com.robrua.orianna.type.dto.staticdata.Item item : its.getData().values()) {
items.add(new Item(item));
IDs.add(item.getId().longValue());
}
RiotAPI.store.store(items, IDs, true);
return Collections.unmodifiableList(items);
}
/**
* @param IDs
* the IDs of the items to get
* @return the items
*/
public synchronized static List<Item> getItems(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Item> items = RiotAPI.store.get(Item.class, IDs);
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(items.get(i) == null && !IGNORE_ITEMS.contains(IDs.get(i))) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return items;
}
if(toGet.size() == 1) {
items.set(index.get(0), getItem(toGet.get(0)));
return items;
}
getItems();
final List<Item> gotten = RiotAPI.store.get(Item.class, toGet);
int count = 0;
for(final Integer id : index) {
items.add(id, gotten.get(count++));
}
return Collections.unmodifiableList(items);
}
/**
* @param IDs
* the IDs of the items to get
* @return the items
*/
public static List<Item> getItems(final long... IDs) {
return getItems(Utils.convert(IDs));
}
/**
* @return the languages
*/
public static List<String> getLanguages() {
return BaseRiotAPI.getLanguages();
}
/**
* @return the language strings
*/
public static Map<String, String> getLanguageStrings() {
final com.robrua.orianna.type.dto.staticdata.LanguageStrings str = BaseRiotAPI.getLanguageStrings();
return str.getData();
}
/**
* @return information for the maps
*/
public synchronized static List<MapDetails> getMapInformation() {
List<MapDetails> info = RiotAPI.store.getAll(MapDetails.class);
if(info != null) {
return info;
}
final MapData inf = BaseRiotAPI.getMapInformation();
info = new ArrayList<>(inf.getData().size());
final List<Long> IDs = new ArrayList<>(info.size());
for(final com.robrua.orianna.type.dto.staticdata.MapDetails map : inf.getData().values()) {
info.add(new MapDetails(map));
IDs.add(map.getMapId().longValue());
}
RiotAPI.store.store(info, IDs, true);
return Collections.unmodifiableList(info);
}
/**
* @return all the masteries
*/
public synchronized static List<Mastery> getMasteries() {
List<Mastery> masteries = RiotAPI.store.getAll(Mastery.class);
if(masteries != null) {
return masteries;
}
final MasteryList its = BaseRiotAPI.getMasteries();
masteries = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(masteries.size());
for(final com.robrua.orianna.type.dto.staticdata.Mastery mastery : its.getData().values()) {
masteries.add(new Mastery(mastery));
IDs.add(mastery.getId().longValue());
}
RiotAPI.store.store(masteries, IDs, true);
return Collections.unmodifiableList(masteries);
}
/**
* @param IDs
* the IDs of the masteries to get
* @return the masteries
*/
public synchronized static List<Mastery> getMasteries(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Mastery> masteries = RiotAPI.store.get(Mastery.class, IDs);
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(masteries.get(i) == null) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return masteries;
}
if(toGet.size() == 1) {
masteries.set(index.get(0), getMastery(toGet.get(0)));
return masteries;
}
getMasteries();
final List<Mastery> gotten = RiotAPI.store.get(Mastery.class, toGet);
int count = 0;
for(final Integer id : index) {
masteries.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(masteries);
}
/**
* @param IDs
* the IDs of the masteries to get
* @return the masteries
*/
public static List<Mastery> getMasteries(final long... IDs) {
return getMasteries(Utils.convert(IDs));
}
/**
* @param ID
* the ID of the mastery to get
* @return the mastery
*/
public synchronized static Mastery getMastery(final long ID) {
Mastery mastery = RiotAPI.store.get(Mastery.class, ID);
if(mastery != null) {
return mastery;
}
final com.robrua.orianna.type.dto.staticdata.Mastery mast = BaseRiotAPI.getMastery(ID);
mastery = new Mastery(mast);
RiotAPI.store.store(mastery, ID);
return mastery;
}
/**
* @return the realm
*/
public synchronized static Realm getRealm() {
Realm realm = RiotAPI.store.get(Realm.class, "");
if(realm != null) {
return realm;
}
realm = new Realm(BaseRiotAPI.getRealm());
RiotAPI.store.store(realm, "");
return realm;
}
/**
* @param ID
* the ID of the rune to get
* @return the rune
*/
public synchronized static Rune getRune(final long ID) {
Rune rune = RiotAPI.store.get(Rune.class, ID);
if(rune != null) {
return rune;
}
final com.robrua.orianna.type.dto.staticdata.Rune run = BaseRiotAPI.getRune(ID);
rune = new Rune(run);
RiotAPI.store.store(rune, ID);
return rune;
}
/**
* @return all the runes
*/
public synchronized static List<Rune> getRunes() {
List<Rune> runes = RiotAPI.store.getAll(Rune.class);
if(runes != null) {
return runes;
}
final RuneList its = BaseRiotAPI.getRunes();
runes = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(runes.size());
for(final com.robrua.orianna.type.dto.staticdata.Rune rune : its.getData().values()) {
runes.add(new Rune(rune));
IDs.add(rune.getId().longValue());
}
RiotAPI.store.store(runes, IDs, true);
return Collections.unmodifiableList(runes);
}
/**
* @param IDs
* the IDs of the runes to get
* @return the runes
*/
public synchronized static List<Rune> getRunes(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Rune> runes = RiotAPI.store.get(Rune.class, IDs);
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(runes.get(i) == null) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return runes;
}
if(toGet.size() == 1) {
runes.set(index.get(0), getRune(toGet.get(0)));
return runes;
}
getRunes();
final List<Rune> gotten = RiotAPI.store.get(Rune.class, toGet);
int count = 0;
for(final Integer id : index) {
runes.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(runes);
}
/**
* @param IDs
* the IDs of the runes to get
* @return the runes
*/
public static List<Rune> getRunes(final long... IDs) {
return getRunes(Utils.convert(IDs));
}
/**
* @param ID
* the ID of the summoner spell to get
* @return the summoner spell
*/
public synchronized static SummonerSpell getSummonerSpell(final long ID) {
SummonerSpell spell = RiotAPI.store.get(SummonerSpell.class, ID);
if(spell != null) {
return spell;
}
final com.robrua.orianna.type.dto.staticdata.SummonerSpell spl = BaseRiotAPI.getSummonerSpell(ID);
spell = new SummonerSpell(spl);
RiotAPI.store.store(spell, ID);
return spell;
}
/**
* @return all the summoner spells
*/
public synchronized static List<SummonerSpell> getSummonerSpells() {
List<SummonerSpell> spells = RiotAPI.store.getAll(SummonerSpell.class);
if(spells != null) {
return spells;
}
final SummonerSpellList its = BaseRiotAPI.getSummonerSpells();
spells = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(spells.size());
for(final com.robrua.orianna.type.dto.staticdata.SummonerSpell spell : its.getData().values()) {
spells.add(new SummonerSpell(spell));
IDs.add(spell.getId().longValue());
}
RiotAPI.store.store(spells, IDs, true);
return Collections.unmodifiableList(spells);
}
/**
* @param IDs
* the IDs of the summoner spells to get
* @return the summoner spells
*/
public synchronized static List<SummonerSpell> getSummonerSpells(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<SummonerSpell> spells = RiotAPI.store.get(SummonerSpell.class, IDs);
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(spells.get(i) == null) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return spells;
}
if(toGet.size() == 1) {
spells.set(index.get(0), getSummonerSpell(toGet.get(0)));
return spells;
}
getSummonerSpells();
final List<SummonerSpell> gotten = RiotAPI.store.get(SummonerSpell.class, toGet);
int count = 0;
for(final Integer id : index) {
spells.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(spells);
}
/**
* @param IDs
* the IDs of the summoner spells to get
* @return the summoner spells
*/
public static List<SummonerSpell> getSummonerSpells(final long... IDs) {
return getSummonerSpells(Utils.convert(IDs));
}
/**
* @return the versions
*/
public static List<String> getVersions() {
return BaseRiotAPI.getVersions();
}
}
|
package io.corbel.evci.converter;
import java.io.IOException;
import java.lang.reflect.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.corbel.evci.model.EworkerMessage;
public class DomainObjectJsonMessageConverter extends Jackson2JsonMessageConverter {
private static final Logger LOG = LoggerFactory.getLogger(DomainObjectJsonMessageConverter.class);
private final Type domainObjectClass;
private final ObjectMapper objectMapper;
public DomainObjectJsonMessageConverter(Type domainObjectClass, ObjectMapper objectMapper) {
this.domainObjectClass = domainObjectClass;
this.objectMapper = objectMapper;
setJsonObjectMapper(objectMapper);
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
Object content = null;
if (message.getClass().equals(domainObjectClass)) {
return message;
}
MessageProperties properties = message.getMessageProperties();
if (properties != null) {
String contentType = properties.getContentType();
if (contentType != null && contentType.contains("json")) {
String encoding = properties.getContentEncoding();
if (encoding == null) {
encoding = getDefaultCharset();
}
try {
JavaType targetJavaType = objectMapper.getTypeFactory().constructType(domainObjectClass);
if (EworkerMessage.class.equals(targetJavaType.getParameterSource())) {
content = convertBytesToObject(message.getBody(), encoding, targetJavaType);
} else {
JavaType eworkerMsgJavaType = objectMapper.getTypeFactory().constructType(EworkerMessage.class);
try {
EworkerMessage eworkerMessage = (EworkerMessage) convertBytesToObject(message.getBody(), encoding,
eworkerMsgJavaType);
content = objectMapper.convertValue(eworkerMessage.getContent(), targetJavaType);
} catch (IOException ignored) {
content = convertBytesToObject(message.getBody(), encoding, targetJavaType);
}
}
} catch (IOException e) {
throw new MessageConversionException("Failed to convert message content", e);
}
} else {
LOG.warn("Could not convert incoming message with content-type [" + contentType + "]");
throw new MessageConversionException("Failed to convert message content. Unknown content-type: [" + contentType + "]");
}
}
if (content == null) {
content = message.getBody();
}
return content;
}
private Object convertBytesToObject(byte[] body, String encoding, JavaType targetJavaType) throws IOException {
String contentAsString = new String(body, encoding);
return objectMapper.readValue(contentAsString, targetJavaType);
}
}
|
package org.eclipse.che.api.vfs.watcher;
import static java.lang.Thread.currentThread;
import static java.nio.file.Files.exists;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Watches directories for interactions with their entries. Based on {@link WatchService} that uses
* underlying filesystem implementations. Does not perform any data modification (including
* filesystem items) except for tracking and notification the upper layers. Service operates with
* ordinary java file system paths in counter to che virtual file system which may have custom root
* element and structure. Transforming one we of path representation into another and backwards is
* the responsibility of upper services.
*/
@Singleton
public class FileWatcherService {
private static final Logger LOG = LoggerFactory.getLogger(FileWatcherService.class);
private final AtomicBoolean suspended = new AtomicBoolean(true);
private final AtomicBoolean running = new AtomicBoolean();
private final Map<WatchKey, Path> keys = new ConcurrentHashMap<>();
private final Map<Path, Integer> registrations = new ConcurrentHashMap<>();
private final FileWatcherExcludePatternsRegistry excludePatternsRegistry;
private final FileWatcherEventHandler handler;
private final WatchService service;
private final Modifier[] eventModifiers;
private final Kind<?>[] eventKinds;
private ExecutorService executor;
@Inject
public FileWatcherService(
FileWatcherExcludePatternsRegistry excludePatternsRegistry,
FileWatcherEventHandler handler,
WatchService service) {
this.excludePatternsRegistry = excludePatternsRegistry;
this.handler = handler;
this.service = service;
this.eventModifiers = getWatchEventModifiers();
this.eventKinds = getWatchEventKinds();
}
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
@SuppressWarnings("unchecked")
private static <T> T cast(Object event) {
return (T) event;
}
private static Kind<?>[] getWatchEventKinds() {
return new Kind<?>[] {ENTRY_DELETE, ENTRY_MODIFY, ENTRY_CREATE};
}
/**
* This is required to speed up mac based file watcher implementations
*
* @return sensitivity watch event modifier
*/
private static Modifier[] getWatchEventModifiers() {
String className = "com.sun.nio.file.SensitivityWatchEventModifier";
try {
Class<?> c = Class.forName(className);
Field f = c.getField("HIGH");
Modifier modifier = cast(f.get(c));
LOG.debug("Class '{}' is found in classpath setting corresponding watch modifier", className);
return new Modifier[] {modifier};
} catch (Exception e) {
LOG.debug("Class '{}' is not found in classpath, falling to default mode", className, e);
return new Modifier[] {};
}
}
@PostConstruct
void start() throws IOException {
ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
ThreadFactory factory =
builder
.setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance())
.setNameFormat(FileWatcherService.class.getSimpleName())
.setDaemon(true)
.build();
executor = newSingleThreadExecutor(factory);
executor.execute(this::run);
}
@PreDestroy
void stop() {
running.compareAndSet(true, false);
try {
LOG.debug("Cancelling watch keys");
keys.keySet().forEach(WatchKey::cancel);
LOG.debug("Closing java watch service");
service.close();
} catch (IOException e) {
LOG.error("Closing of java watch service failed: ", e.getMessage());
}
try {
LOG.debug("Executor task shutdown started");
executor.shutdown();
executor.awaitTermination(5, SECONDS);
} catch (InterruptedException e) {
currentThread().interrupt();
LOG.debug("Executor task is interrupted");
} finally {
if (!executor.isTerminated()) {
LOG.debug("Executor task is not shutdown yet");
}
executor.shutdownNow();
LOG.debug("Executor tasks have been shutdown");
}
}
boolean isStopped() {
return executor.isShutdown();
}
/**
* Registers a directory for tracking of corresponding entry creation, modification or deletion
* events. Each call of this method increase by one registration counter that corresponds to each
* folder being watched. Any event related to such directory entry is passed further to the
* specific handler only if registration counter related to the directory is above zero, otherwise
* registration watch key is canceled and no further directory watching is being performed.
*
* @param dir directory
*/
public void register(Path dir) {
if (!Files.exists(dir)) {
LOG.debug("Trying to register directory '{}' but it does not exist", dir);
return;
}
LOG.debug("Registering directory '{}'", dir);
if (keys.values().contains(dir)) {
int previous = registrations.get(dir);
LOG.debug(
"Directory is already being watched, increasing watch counter, previous value: {}",
previous);
registrations.put(dir, previous + 1);
} else {
try {
LOG.debug("Starting watching directory '{}'", dir);
synchronized (keys) {
WatchKey watchKey = dir.register(service, eventKinds, eventModifiers);
keys.put(watchKey, dir);
registrations.put(dir, 1);
}
} catch (IOException e) {
LOG.error("Can't register dir {} in file watch service", dir, e);
}
}
}
/**
* Cancels registration of a directory for being watched. Each call of this method decreases by
* one registration counter that corresponds to directory specified by the argument. If
* registration counter comes to zero directory watching is totally cancelled.
*
* <p>If this method is called for not existing directory nothing happens.
*
* <p>If this method is called for not registered directory nothing happens.
*
* @param dir directory
*/
void unRegister(Path dir) {
LOG.debug("Canceling directory '{}' registration", dir);
Predicate<Entry<WatchKey, Path>> equalsDir = it -> it.getValue().equals(dir);
if (!exists(dir)) {
LOG.debug("Trying to unregister directory '{}' while it does not exist", dir);
registrations.remove(dir);
keys.entrySet().stream().filter(equalsDir).map(Entry::getKey).forEach(WatchKey::cancel);
keys.entrySet().removeIf(equalsDir);
return;
}
if (!registrations.containsKey(dir)) {
LOG.debug("Trying to unregister directory '{}' while it is not registered", dir);
return;
}
int previous = registrations.get(dir);
if (previous == 1) {
LOG.debug("Stopping watching directory '{}'", dir);
registrations.remove(dir);
keys.entrySet().stream().filter(equalsDir).map(Entry::getKey).forEach(WatchKey::cancel);
keys.entrySet().removeIf(equalsDir);
} else {
LOG.debug(
"Directory is being watched by someone else, decreasing watch counter, previous value: {}",
previous);
registrations.put(dir, previous - 1);
}
}
/**
* Resumes service after it was in suspended state. If method is called when the service is
* already not in a suspended state nothing happens.
*/
void resume() {
if (suspended.compareAndSet(true, false)) {
LOG.debug("Resuming service.");
}
}
/**
* Temporary suspends service of generating any events. Events received by service in suspended
* state are totally skipped. If method is called when the service is already in a suspended state
* nothing happens.
*/
void suspend() {
if (suspended.compareAndSet(false, true)) {
LOG.debug("Suspending service.");
}
}
private void run() {
suspended.compareAndSet(true, false);
running.compareAndSet(false, true);
while (running.get()) {
try {
WatchKey watchKey = service.take();
Path dir;
synchronized (keys) {
dir = keys.get(watchKey);
}
if (dir == null) {
resetAndRemove(watchKey, dir);
LOG.debug("Reported directory is not registered - skipping.");
continue;
}
List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
if (suspended.get()) {
resetAndRemove(watchKey, dir);
LOG.debug("File watchers are running in suspended mode - skipping.");
continue;
}
for (WatchEvent<?> event : watchEvents) {
Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
LOG.warn("Detected file system events overflowing");
continue;
}
WatchEvent<Path> ev = cast(event);
Path item = ev.context();
Path path = dir.resolve(item).toAbsolutePath();
if (excludePatternsRegistry.isExcluded(path)) {
LOG.debug("Path is within exclude list, skipping...");
continue;
}
handler.handle(path, kind);
}
resetAndRemove(watchKey, dir);
} catch (InterruptedException e) {
running.compareAndSet(true, false);
LOG.debug(
"Interruption error when running file watcher, most likely caused by stopping it", e);
} catch (ClosedWatchServiceException e) {
running.compareAndSet(true, false);
LOG.debug("Closing watch service while some of keys may be processing", e);
}
}
}
private void resetAndRemove(WatchKey watchKey, Path dir) {
if (!watchKey.reset()) {
if (dir != null) {
registrations.remove(dir);
}
keys.remove(watchKey);
}
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.TextAreaBuilder;
import lombok.Getter;
import lombok.Setter;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextArea extends Component {
/** The foreground color of the caret. */
@Getter @Setter private Color caretForegroundColor;
/** The background color of the caret. */
@Getter @Setter private Color caretBackgroundColor;
/** The foreground color of non-caret characters. */
@Getter @Setter private Color foregroundColor;
/** The background color of non-caret characters. */
@Getter @Setter private Color backgroundColor;
/** Whether or not the HOME key can be used to move the caret to the first index of the field. */
@Getter @Setter private boolean homeKeyEnabled;
/** Whether or not the END key can be used to move the caret to the last index of the field. */
@Getter @Setter private boolean endKeyEnabled;
/** Whether or not the DELETE key can be used to erase the character that the caret is on. */
@Getter @Setter private boolean deleteKeyEnabled;
/** Whether or not the LEFT ARROW key can be used to move the caret one index to the left. */
@Getter @Setter private boolean leftArrowKeyEnabled;
/** Whether or not the RIGHT ARROW key can be used to move the caret one index to the right. */
@Getter @Setter private boolean rightArrowKeyEnabled;
/** Whether or not the UP ARROW key can be used to move the caret one index up. */
@Getter @Setter private boolean upArrowKeyEnabled;
/** Whether or not the DOWN ARROW key can be used to move the caret one index up. */
@Getter @Setter private boolean downArrowKeyEnabled;
/** Whether or not the ENTER key can be used to advance the caret to the first position of the next line. */
@Getter @Setter private boolean enterKeyEnabled;
/** Whether or not the BACK SPACE key can be used to erase the character before the caret and move the caret backwards. */
@Getter @Setter private boolean backSpaceKeyEnabled;
/** The current position of the visual caret on the x-axis. */
@Getter private int x_index_caret_visual = 0;
/** The current position of the visual caret on the y-axis. */
@Getter private int y_index_caret_visual = 0;
/** The current position of the caret, on the x-axis, in the enteredText array. */
@Getter private int x_index_caret_actual = 0;
/** The current position of the caret, on the y-axis, in the enteredText array. */
@Getter private int y_index_caret_actual = 0;
/** The maximum number of characters that the field can contain along the x-axis. */
@Getter private int maxHorizontalCharacters;
/** The maximum number of characters that the field can contain along the y-axis. */
@Getter private int maxVerticalCharacters;
/** The text entered by the user. */
@Getter private char[][] enteredText;
/** The pattern used to determine which typed characters can be entered into the field. */
@Getter @Setter private Pattern allowedCharacterPattern;
/**
* Constructs a new AsciiTextField.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public TextArea(final TextAreaBuilder builder) {
super(builder.getColumnIndex(), builder.getRowIndex(), builder.getWidth(), builder.getHeight());
Objects.requireNonNull(builder);
super.setRadio(builder.getRadio());
caretForegroundColor = builder.getCaretForegroundColor();
caretBackgroundColor = builder.getCaretBackgroundColor();
foregroundColor = builder.getForegroundColor();
backgroundColor = builder.getBackgroundColor();
homeKeyEnabled = builder.isHomeKeyEnabled();
endKeyEnabled = builder.isEndKeyEnabled();
deleteKeyEnabled = builder.isDeleteKeyEnabled();
leftArrowKeyEnabled = builder.isLeftArrowKeyEnabled();
rightArrowKeyEnabled = builder.isRightArrowKeyEnabled();
upArrowKeyEnabled = builder.isUpArrowKeyEnabled();
downArrowKeyEnabled = builder.isDownArrowKeyEnabled();
enterKeyEnabled = builder.isEnterKeyEnabled();
backSpaceKeyEnabled = builder.isBackSpaceKeyEnabled();
maxHorizontalCharacters = builder.getMaxHorizontalCharacters();
maxVerticalCharacters = builder.getMaxVerticalCharacters();
enteredText = new char[maxVerticalCharacters][maxHorizontalCharacters];
clearText();
allowedCharacterPattern = builder.getAllowedCharacterPattern();
// Set the area's initial colors:
for (final AsciiString string : super.getStrings()) {
string.setBackgroundColor(backgroundColor);
string.setForegroundColor(foregroundColor);
}
// Set initial caret position:
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual);
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual);
}
@Override
public void createEventListeners(final Panel panel) {
super.createEventListeners(panel);
final KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(final KeyEvent e) {
if (isFocused()) {
final char character = e.getKeyChar();
final Matcher matcher = allowedCharacterPattern.matcher(character + "");
if (matcher.matches()) {
changeVisualCharacter(x_index_caret_visual, y_index_caret_visual, character);
changeActualCharacter(x_index_caret_actual, y_index_caret_actual, character);
final boolean caretAtEndOfLine = x_index_caret_actual == maxHorizontalCharacters - 1;
if (caretAtEndOfLine) {
if (y_index_caret_actual < maxVerticalCharacters - 1) {
moveCaretDown();
moveCaretToStartOfLine();
}
} else {
moveCaretRight();
}
updateDisplayedCharacters();
transmitDraw();
}
}
}
@Override
public void keyPressed(final KeyEvent e) {
}
@Override
public void keyReleased(final KeyEvent e) {
if (isFocused()) {
int keyCode = e.getKeyCode();
switch (keyCode) {
// Move the caret to the first position on the left:
case KeyEvent.VK_HOME: {
if (homeKeyEnabled) {
moveCaretToStartOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the last position on the right:
case KeyEvent.VK_END: {
if (endKeyEnabled) {
moveCaretToEndOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Erase the current character:
case KeyEvent.VK_DELETE: {
if (deleteKeyEnabled) {
clearCurrentCell();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position to the left:
case KeyEvent.VK_LEFT: {
if (leftArrowKeyEnabled) {
boolean moveToPreviousLine = x_index_caret_actual == 0;
moveToPreviousLine &= y_index_caret_actual > 0;
if (moveToPreviousLine) {
moveCaretUp();
moveCaretToEndOfLine();
} else {
moveCaretLeft();
}
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position to the right:
case KeyEvent.VK_RIGHT: {
if (isRightArrowKeyEnabled()) {
boolean moveToNextLine = x_index_caret_actual == maxHorizontalCharacters - 1;
moveToNextLine &= y_index_caret_actual < maxVerticalCharacters - 1;
if (moveToNextLine) {
moveCaretDown();
moveCaretToStartOfLine();
} else {
moveCaretRight();
}
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position up:
case KeyEvent.VK_UP: {
if (upArrowKeyEnabled) {
moveCaretUp();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position down:
case KeyEvent.VK_DOWN: {
if (downArrowKeyEnabled) {
moveCaretDown();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the first position of the next row:
case KeyEvent.VK_ENTER: {
boolean canWork = enterKeyEnabled;
canWork &= y_index_caret_actual < maxVerticalCharacters - 1;
if (canWork) {
moveCaretDown();
moveCaretToStartOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Delete the character to the left of the caret, then move the caret one position left:
case KeyEvent.VK_BACK_SPACE: {
if (! backSpaceKeyEnabled) {
break;
}
final boolean caretAtStartOfLine = x_index_caret_actual == 0;
final boolean caretAtEndOfLine = x_index_caret_actual == maxHorizontalCharacters - 1;
if (caretAtStartOfLine) {
if (y_index_caret_actual > 0) {
moveCaretUp();
moveCaretToEndOfLine();
}
} else if (caretAtEndOfLine) {
final AsciiCharacter currentChar = TextArea.super.getStrings()[y_index_caret_visual].getCharacters()[x_index_caret_visual];
if (currentChar.getCharacter() == ' ') {
moveCaretLeft();
}
} else {
moveCaretLeft();
}
clearCurrentCell();
updateDisplayedCharacters();
transmitDraw();
break;
}
}
}
}
};
super.getEventListeners().add(keyListener);
}
/** Moves the caret one cell up. */
private void moveCaretUp() {
if (y_index_caret_visual > 0) {
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual - 1);
}
if (y_index_caret_actual > 0) {
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual - 1);
}
}
/** Moves the caret one cell down. */
private void moveCaretDown() {
if (y_index_caret_visual < super.getHeight() - 1) {
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual + 1);
}
if (y_index_caret_actual < maxVerticalCharacters - 1) {
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual + 1);
}
}
/** Moves the caret one cell left. */
private void moveCaretLeft() {
if (x_index_caret_visual > 0) {
changeVisualCaretPosition(x_index_caret_visual - 1, y_index_caret_visual);
}
if (x_index_caret_actual > 0) {
changeActualCaretPosition(x_index_caret_actual - 1, y_index_caret_actual);
}
}
/** Moves the caret one cell right. */
private void moveCaretRight() {
if (x_index_caret_visual < super.getWidth() - 1) {
changeVisualCaretPosition(x_index_caret_visual + 1, y_index_caret_visual);
}
if (x_index_caret_actual < maxHorizontalCharacters - 1) {
changeActualCaretPosition(x_index_caret_actual + 1, y_index_caret_actual);
}
}
/** Moves the caret to the beginning of the current line. */
private void moveCaretToStartOfLine() {
changeVisualCaretPosition(0, y_index_caret_visual);
changeActualCaretPosition(0, y_index_caret_actual);
}
/** Moves the caret to the end of the current line. */
private void moveCaretToEndOfLine() {
changeVisualCaretPosition(super.getWidth() - 1, y_index_caret_visual);
changeActualCaretPosition(maxHorizontalCharacters - 1, y_index_caret_actual);
}
/** Deletes the character in the current cell. */
private void clearCurrentCell() {
changeVisualCharacter(x_index_caret_visual, y_index_caret_visual, ' ');
changeActualCharacter(x_index_caret_actual, y_index_caret_actual, ' ');
}
/**
* Moves the visual caret to the specified location.
*
* @param newColumnIndex
* The new column index for the caret.
*
* @param newRowIndex
* The new row index for the caret.
*/
private void changeVisualCaretPosition(final int newColumnIndex, final int newRowIndex) {
final Radio<String> radio = super.getRadio();
// Reset current position's fore/background:
AsciiCharacter[] characters = super.getString(y_index_caret_visual).getCharacters();
characters[x_index_caret_visual].setForegroundColor(foregroundColor);
characters[x_index_caret_visual].setBackgroundColor(backgroundColor);
if (radio != null) {
// Reset current position's blink/hidden state:
characters[x_index_caret_visual].disableBlinkEffect();
characters[x_index_caret_visual].setHidden(false);
}
// Set new position's fore/background:
characters = super.getString(newRowIndex).getCharacters();
characters[newColumnIndex].setForegroundColor(caretForegroundColor);
characters[newColumnIndex].setBackgroundColor(caretBackgroundColor);
if (radio != null) {
// Set new position's blink state:
characters[newColumnIndex].enableBlinkEffect((short) 1000, radio);
}
x_index_caret_visual = newColumnIndex;
y_index_caret_visual = newRowIndex;
}
/**
* Moves the actual caret to the specified location.
*
* @param newColumnIndex
* The new column index for the caret.
*
* @param newRowIndex
* The new row index for the caret.
*/
private void changeActualCaretPosition(final int newColumnIndex, final int newRowIndex) {
x_index_caret_actual = newColumnIndex;
y_index_caret_actual = newRowIndex;
}
/**
* Changes the visual character at the specified location.
*
* @param columnIndex
* The column index.
*
* @param rowIndex
* The row index.
*
* @param character
* The new character.
*/
private void changeVisualCharacter(final int columnIndex, final int rowIndex, final char character) {
final AsciiCharacter[] characters = super.getString(rowIndex).getCharacters();
characters[columnIndex].setCharacter(character);
}
/**
* Changes the actual character at the specified index.
*
* @param columnIndex
* The column index.
*
* @param rowIndex
* The row index.
*
* @param character
* The new character.
*/
private void changeActualCharacter(final int columnIndex, final int rowIndex, final char character) {
if (columnIndex < 0 || columnIndex > maxHorizontalCharacters) {
return;
}
if (rowIndex < 0 || rowIndex > maxVerticalCharacters) {
return;
}
enteredText[rowIndex][columnIndex] = character;
}
private void updateDisplayedCharacters() {
final int xDifference = x_index_caret_actual - x_index_caret_visual;
final int yDifference = y_index_caret_actual - y_index_caret_visual;
for (int y = yDifference ; y < super.getHeight() + yDifference ; y++) {
final AsciiString string = super.getString(y - yDifference);
final AsciiCharacter[] characters = string.getCharacters();
for (int x = xDifference ; x < super.getWidth() + xDifference ; x++) {
characters[x - xDifference].setCharacter(enteredText[y][x]);
}
}
}
/**
* Sets the text contained within a row of the area.
*
* @param rowIndex
* The row index.
*
* @param text
* The text.
*
* @throws NullPointerException
* If the text is null.
*/
public void setText(final int rowIndex, String text) {
Objects.requireNonNull(text);
if (text.length() > maxHorizontalCharacters) {
text = text.substring(0, maxHorizontalCharacters);
}
System.arraycopy(text.toCharArray(), 0, enteredText[rowIndex], 0, text.length());
}
/**
* Sets the text contained within the area.
*
* Clears the field before setting.
*
* @param text
* The list of text.
*
* @throws NullPointerException
* If the text is null.
*/
public void setText(final List<String> text) {
Objects.requireNonNull(text);
clearText();
for (int i = 0 ; i < text.size() && i < maxVerticalCharacters ; i++) {
setText(i, text.get(i));
}
}
/** @return The text contained within the area. */
public String[] getText() {
final String[] strings = new String[super.getHeight() + 1];
String temp = "";
for (int i = 0 ; i < enteredText.length ; i++) {
for (final char c : enteredText[i]) {
temp += c;
}
strings[i] = temp;
temp = "";
}
return strings;
}
public void clearText(final int rowIndex) {
if (rowIndex < 0) {
throw new IllegalArgumentException("The row index cannot be below 0.");
}
if (rowIndex > super.getHeight()) {
throw new IllegalArgumentException("The row index cannot be above " + super.getHeight() +".");
}
Arrays.fill(enteredText[rowIndex], ' ');
if (y_index_caret_actual == y_index_caret_visual && y_index_caret_actual == rowIndex) {
for (final AsciiCharacter character : super.getString(rowIndex).getCharacters()) {
character.setCharacter(' ');
}
}
}
/** Clears all text from the field. */
public void clearText() {
for (int i = 0 ; i < enteredText.length ; i++) {
Arrays.fill(enteredText[i], ' ');
}
for (final AsciiString string : super.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
character.setCharacter(' ');
}
}
}
}
|
package org.elasticsearch.xpack.ml.dataframe.inference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.OriginSettingClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.xpack.core.ml.inference.results.InferenceResults;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.dataframe.DestinationIndex;
import org.elasticsearch.xpack.ml.dataframe.stats.DataCountsTracker;
import org.elasticsearch.xpack.ml.dataframe.stats.ProgressTracker;
import org.elasticsearch.xpack.ml.extractor.ExtractedField;
import org.elasticsearch.xpack.ml.extractor.ExtractedFields;
import org.elasticsearch.xpack.ml.inference.loadingservice.LocalModel;
import org.elasticsearch.xpack.ml.inference.loadingservice.ModelLoadingService;
import org.elasticsearch.xpack.ml.utils.persistence.LimitAwareBulkIndexer;
import org.elasticsearch.xpack.ml.utils.persistence.ResultsPersisterService;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public class InferenceRunner {
private static final Logger LOGGER = LogManager.getLogger(InferenceRunner.class);
private static final int MAX_PROGRESS_BEFORE_COMPLETION = 98;
private final Settings settings;
private final Client client;
private final ModelLoadingService modelLoadingService;
private final ResultsPersisterService resultsPersisterService;
private final TaskId parentTaskId;
private final DataFrameAnalyticsConfig config;
private final ExtractedFields extractedFields;
private final ProgressTracker progressTracker;
private final DataCountsTracker dataCountsTracker;
private volatile boolean isCancelled;
public InferenceRunner(Settings settings, Client client, ModelLoadingService modelLoadingService,
ResultsPersisterService resultsPersisterService, TaskId parentTaskId, DataFrameAnalyticsConfig config,
ExtractedFields extractedFields, ProgressTracker progressTracker, DataCountsTracker dataCountsTracker) {
this.settings = Objects.requireNonNull(settings);
this.client = Objects.requireNonNull(client);
this.modelLoadingService = Objects.requireNonNull(modelLoadingService);
this.resultsPersisterService = Objects.requireNonNull(resultsPersisterService);
this.parentTaskId = Objects.requireNonNull(parentTaskId);
this.config = Objects.requireNonNull(config);
this.extractedFields = Objects.requireNonNull(extractedFields);
this.progressTracker = Objects.requireNonNull(progressTracker);
this.dataCountsTracker = Objects.requireNonNull(dataCountsTracker);
}
public void cancel() {
isCancelled = true;
}
public void run(String modelId) {
if (isCancelled) {
return;
}
LOGGER.info("[{}] Started inference on test data against model [{}]", config.getId(), modelId);
try {
PlainActionFuture<LocalModel> localModelPlainActionFuture = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, localModelPlainActionFuture);
TestDocsIterator testDocsIterator = new TestDocsIterator(new OriginSettingClient(client, ClientHelper.ML_ORIGIN), config,
extractedFields);
try (LocalModel localModel = localModelPlainActionFuture.actionGet()) {
inferTestDocs(localModel, testDocsIterator);
}
} catch (Exception e) {
LOGGER.error(new ParameterizedMessage("[{}] Error during inference against model [{}]", config.getId(), modelId), e);
throw ExceptionsHelper.serverError("[{}] failed running inference on model [{}]; cause was [{}]", e, config.getId(), modelId,
e.getMessage());
}
}
// Visible for testing
void inferTestDocs(LocalModel model, TestDocsIterator testDocsIterator) {
long totalDocCount = 0;
long processedDocCount = 0;
try (LimitAwareBulkIndexer bulkIndexer = new LimitAwareBulkIndexer(settings, this::executeBulkRequest)) {
while (testDocsIterator.hasNext()) {
if (isCancelled) {
break;
}
Deque<SearchHit> batch = testDocsIterator.next();
if (totalDocCount == 0) {
totalDocCount = testDocsIterator.getTotalHits();
}
for (SearchHit doc : batch) {
dataCountsTracker.incrementTestDocsCount();
InferenceResults inferenceResults = model.inferNoStats(featuresFromDoc(doc));
bulkIndexer.addAndExecuteIfNeeded(createIndexRequest(doc, inferenceResults, config.getDest().getResultsField()));
processedDocCount++;
int progressPercent = Math.min((int) (processedDocCount * 100.0 / totalDocCount), MAX_PROGRESS_BEFORE_COMPLETION);
progressTracker.updateInferenceProgress(progressPercent);
}
}
}
if (isCancelled == false) {
progressTracker.updateInferenceProgress(100);
}
}
private Map<String, Object> featuresFromDoc(SearchHit doc) {
Map<String, Object> features = new HashMap<>();
for (ExtractedField extractedField : extractedFields.getAllFields()) {
Object[] values = extractedField.value(doc);
if (values.length == 1) {
features.put(extractedField.getName(), values[0]);
}
}
return features;
}
private IndexRequest createIndexRequest(SearchHit hit, InferenceResults results, String resultField) {
Map<String, Object> resultsMap = new LinkedHashMap<>(results.asMap());
resultsMap.put(DestinationIndex.IS_TRAINING, false);
Map<String, Object> source = new LinkedHashMap<>(hit.getSourceAsMap());
source.put(resultField, resultsMap);
IndexRequest indexRequest = new IndexRequest(hit.getIndex());
indexRequest.id(hit.getId());
indexRequest.source(source);
indexRequest.opType(DocWriteRequest.OpType.INDEX);
indexRequest.setParentTask(parentTaskId);
return indexRequest;
}
private void executeBulkRequest(BulkRequest bulkRequest) {
resultsPersisterService.bulkIndexWithHeadersWithRetry(
config.getHeaders(),
bulkRequest,
config.getId(),
() -> isCancelled == false,
errorMsg -> {});
}
}
|
package org.hammerc.marble.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* .
* @author wizardc
*/
public class FileUtil
{
public static final String SEPARATOR = File.separator;
public static final String LINE_SEPARATOR = System.getProperty("line.separator", "\r\n");
/**
* .
* @param path .
* @param data .
* @return .
*/
public static boolean saveAsBytes(String path, byte[] data)
{
createDirectoty(path);
try
{
FileOutputStream outputStream = new FileOutputStream(path);
outputStream.write(data);
outputStream.close();
}
catch(IOException exception)
{
return false;
}
return true;
}
/**
* .
* @param path .
* @param data .
* @return .
*/
public static boolean saveAsString(String path, String data)
{
return saveAsString(path, data, "UTF8");
}
/**
* .
* @param path .
* @param data .
* @param charsetName .
* @return .
*/
public static boolean saveAsString(String path, String data, String charsetName)
{
try
{
byte[] bytes = data.getBytes(charsetName);
return saveAsBytes(path, bytes);
}
catch(IOException exception)
{
return false;
}
}
/**
* .
* @param path .
* @return .
* @throws IOException .
*/
public static byte[] readAsBytes(String path) throws IOException
{
File file = new File(path);
Long length = file.length();
byte[] bytes = new byte[length.intValue()];
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bytes);
inputStream.close();
return bytes;
}
/**
* .
* @param path .
* @return .
* @throws IOException .
*/
public static String readAsString(String path) throws IOException
{
return readAsString(path, "UTF8");
}
/**
* .
* @param path .
* @param charsetName .
* @return .
* @throws IOException .
*/
public static String readAsString(String path, String charsetName) throws IOException
{
byte[] bytes = readAsBytes(path);
return new String(bytes, charsetName);
}
/**
* .
* @param source .
* @param dest .
* @param overwrite .
* @return .
* @throws IOException .
*/
public static boolean moveTo(String source, String dest, boolean overwrite) throws IOException
{
if(copyTo(source, dest, overwrite))
{
deletePath(source);
return true;
}
return false;
}
/**
* .
* @param source .
* @param dest .
* @param overwrite .
* @return .
* @throws IOException .
*/
public static boolean copyTo(String source, String dest, boolean overwrite) throws IOException
{
if(source.equals(dest))
{
return true;
}
File sourceFile = new File(source);
File destFile = new File(dest);
if(!sourceFile.exists())
{
return false;
}
if(destFile.exists() && !overwrite)
{
return false;
}
byte[] content = readAsBytes(source);
saveAsBytes(dest, content);
return true;
}
/**
* .
* @param path .
* @return .
*/
public static boolean deletePath(String path)
{
File file = new File(path);
if(file.isDirectory())
{
for(String item : file.list())
{
if(!deletePath(file.getAbsolutePath() + File.separator + item))
{
return false;
}
}
}
return file.delete();
}
/**
* .
* @param path .
* @return .
*/
public static String getDirectory(String path)
{
int separatePos = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
return separatePos == -1 ? null : path.substring(0, separatePos);
}
/**
* .
* @param path .
* @return .
*/
public static String getFileName(String path)
{
int separatePos = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
return separatePos == -1 ? null : path.substring(separatePos + 1, path.length());
}
/**
* .
* @param fileName .
* @return .
*/
public static String getFileExtension(String fileName)
{
if(fileName == null || fileName.lastIndexOf(".") == -1 || fileName.lastIndexOf(".") == fileName.length() - 1)
{
return null;
}
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
/**
* .
* @param path .
* @param recursive .
* @return .
*/
public static List<File> getFileList(String path, boolean recursive)
{
return getFileList(path, "(.*)", recursive);
}
/**
* .
* @param path .
* @param regex .
* @param recursive .
* @return .
*/
public static List<File> getFileList(String path, String regex, boolean recursive)
{
File rootFolder = new File(path);
Pattern pattern = Pattern.compile(regex);
return getFiles(rootFolder, pattern, recursive);
}
private static List<File> getFiles(File rootFolder, Pattern regexPattern, boolean recursive)
{
List<File> result = new ArrayList<File>();
File[] files = rootFolder.listFiles();
if(files != null)
{
for(File file : files)
{
if(file.isDirectory() && recursive)
{
result.addAll(getFiles(file, regexPattern, recursive));
}
else
{
if(regexPattern.matcher(file.getAbsolutePath()).matches())
{
result.add(file);
}
}
}
}
return result;
}
/**
* .
* @param path .
* @return .
*/
public static boolean exists(String path)
{
File file = new File(path);
return file.exists();
}
/**
* .
* @param path .
*/
public static void createDirectoty(String path)
{
File file = new File(path);
File directoty = file.isDirectory() ? file : file.getParentFile();
if(!directoty.exists())
{
directoty.mkdirs();
}
}
/**
* , .
* @param path .
* @return .
*/
public static String formatPath(String path)
{
String separator = SEPARATOR;
if(separator.equals("\\"))
{
separator = "\\\\";
}
path = path.replaceAll("\\\\", separator);
path = path.replaceAll("/", separator);
int index = path.lastIndexOf(SEPARATOR);
if(index == path.length() - 1)
{
path = path.substring(0, path.length() - 1);
}
return path;
}
/**
* .
* @param source .
* @return .
*/
public static String unifyEnter(String source)
{
source = source.replaceAll("\\r\\n", "\r");
source = source.replaceAll("\\n", "\r");
source = source.replaceAll("\\r", LINE_SEPARATOR);
return source;
}
}
|
package uk.org.rlinsdale.nbpcglibrary.form;
import java.io.IOException;
import uk.org.rlinsdale.nbpcglibrary.common.Listener;
import uk.org.rlinsdale.nbpcglibrary.data.entity.SetChangeEventParams;
/**
* The Choice Field Model - basic implementation
*
* @author Richard Linsdale (richard.linsdale at blueyonder.co.uk)
* @param <T> the type of the source value
*/
public abstract class EntityChoiceFieldModel<T> extends EntityFieldModel<T> {
/**
* Add a listener to collection from which the choice list is derived.
*
* @param listener the listener
* @throws IOException if problems
*/
public void addCollectionListeners(Listener<SetChangeEventParams> listener) throws IOException {
}
/**
* Remove a listener from the collection from which the choice list is
* derived.
*
* @param listener the listener
* @throws IOException if problems
*/
public void removeCollectionListeners(Listener<SetChangeEventParams> listener) throws IOException {
}
}
|
package org.savara.gadget.server.service;
import com.google.inject.Inject;
import org.savara.gadget.server.model.Gadget;
import org.savara.gadget.server.model.Page;
import org.savara.gadget.server.model.Widget;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
public class GadgetServiceImpl implements GadgetService{
private EntityManager entityManager;
//TODO: need to be replaced with initial data sql.
private static Gadget todoList;
private static Gadget currencyConverter;
private static Gadget bamWidget;
private static Gadget dateAndTime;
@Inject
public GadgetServiceImpl(EntityManager em) {
this.entityManager = em;
initialize();
}
private void initialize() {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
entityManager.persist(todoList);
entityManager.persist(currencyConverter);
entityManager.persist(bamWidget);
entityManager.persist(dateAndTime);
entityManager.getTransaction().commit();
}
static {
todoList = new Gadget();
todoList.setAuthorEmail("weather@google.com");
todoList.setTitle(" To-Do List");
todoList.setAuthor("Labpixies");
todoList.setDescription(" Easily manage and track everything you need To-Do. The gadget lets you create multiple To-Do lists, each with a unique purpose.");
todoList.setThumbnailUrl("http:
todoList.setTitleUrl("");
todoList.setUrl("http:
currencyConverter = new Gadget();
currencyConverter.setAuthor("Google");
currencyConverter.setAuthorEmail("info@tofollow.com");
currencyConverter.setTitle(" Currency Converter");
currencyConverter.setThumbnailUrl("http:
currencyConverter.setDescription(" This is the currency converter widget");
currencyConverter.setUrl("http:
bamWidget = new Gadget();
bamWidget.setAuthor("Jeff Yu");
bamWidget.setAuthorEmail("Jeff@test.com");
bamWidget.setTitle(" BAM Gadget");
bamWidget.setThumbnailUrl("http://hosting.gmodules.com/ig/gadgets/file/112016200750717054421/74e562e0-7881-4ade-87bb-ca9977151084.jpg");
bamWidget.setDescription(" This is the BAM gadget prototype...");
bamWidget.setUrl("http://sam-gadget.appspot.com/Gadget/SamGadget.gadget.xml");
dateAndTime = new Gadget();
dateAndTime.setAuthor("Google");
dateAndTime.setAuthorEmail("admin@google.com");
dateAndTime.setTitle(" Date & Time");
dateAndTime.setThumbnailUrl("http://gadgets.adwebmaster.net/images/gadgets/datetimemulti/thumbnail_en.jpg");
dateAndTime.setDescription(" Add a clock to your page. Click edit to change it to the color of your choice");
dateAndTime.setUrl("http:
}
public List<Gadget> getAllGadgets(int offset, int pageSize) {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Query query = entityManager.createQuery("select gadget from Gadget gadget");
query.setFirstResult(offset).setMaxResults(pageSize);
List<Gadget> gadgets = query.getResultList();
entityManager.getTransaction().commit();
return gadgets;
}
public int getAllGadgetsNum() {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Query query = entityManager.createQuery("select count(gadget.id) from Gadget gadget");
Long result = (Long)query.getSingleResult();
entityManager.getTransaction().commit();
return result.intValue();
}
public void addGadgetToPage(Gadget gadget, Page page) {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Widget widget = new Widget();
widget.setAppUrl(gadget.getUrl());
widget.setName(gadget.getTitle());
widget.setPage(page);
//TODO: hard-coded for testing...
widget.setOrder(page.getWidgets().size() + 1);
entityManager.persist(widget);
page.getWidgets().add(widget);
entityManager.merge(page);
entityManager.getTransaction().commit();
}
public Gadget getGadgetById(long gadgetId) {
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
Gadget gadget = entityManager.find(Gadget.class, gadgetId);
entityManager.getTransaction().commit();
return gadget;
}
}
|
// CloudCoder - a web-based pedagogical programming environment
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package org.cloudcoder.app.server.persist.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.cloudcoder.app.server.persist.PasswordUtil;
import org.cloudcoder.app.shared.model.CourseRegistration;
import org.cloudcoder.app.shared.model.CourseRegistrationType;
import org.cloudcoder.app.shared.model.User;
import org.slf4j.LoggerFactory;
/**
* TODO: Move the database code here into JDBCDatabase?
*
* @author jaimespacco
*
*/
public class ConfigurationUtil
{
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger=LoggerFactory.getLogger(ConfigurationUtil.class);
public static String ask(Scanner keyboard, String prompt) {
return ConfigurationUtil.ask(keyboard, prompt, null);
}
public static<E> E choose(Scanner keyboard, String prompt, List<E> values) {
System.out.println(prompt);
int count = 0;
for (E val : values) {
System.out.println((count++) + " - " + val);
}
System.out.print("[Enter value in range 0.." + (values.size()-1) + "] ");
int choice = Integer.parseInt(keyboard.nextLine().trim());
return values.get(choice);
}
public static int askInt(Scanner keyboard, String prompt) {
System.out.print(prompt);
return Integer.parseInt(keyboard.nextLine().trim());
}
public static String askString(Scanner keyboard, String prompt) {
System.out.print(prompt);
return keyboard.nextLine();
}
public static CourseRegistration findRegistration(Connection conn, int userId, int courseId) throws SQLException
{
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = conn.prepareStatement("select * from " + CourseRegistration.SCHEMA.getDbTableName() + " where user_id = ? and course_id = ?");
stmt.setInt(1, userId);
stmt.setInt(2, courseId);
resultSet= stmt.executeQuery();
if (!resultSet.next()) {
return null;
}
CourseRegistration reg=new CourseRegistration();
DBUtil.loadModelObjectFields(reg, CourseRegistration.SCHEMA, resultSet);
return reg;
} finally {
DBUtil.closeQuietly(resultSet);
DBUtil.closeQuietly(stmt);
}
}
public static User findUser(Connection conn, String username) throws SQLException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = conn.prepareStatement("select * from " + User.SCHEMA.getDbTableName() + " where username = ?");
stmt.setString(1, username);
resultSet= stmt.executeQuery();
if (!resultSet.next()) {
return null;
}
User user = new User();
DBUtil.loadModelObjectFields(user, User.SCHEMA, resultSet);
return user;
} finally {
DBUtil.closeQuietly(resultSet);
DBUtil.closeQuietly(stmt);
}
}
public static User findUser(Connection conn, int userid) throws SQLException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = conn.prepareStatement("select * from " + User.SCHEMA.getDbTableName() + " where id = ?");
stmt.setInt(1, userid);
resultSet= stmt.executeQuery();
if (!resultSet.next()) {
return null;
}
User user = new User();
DBUtil.loadModelObjectFields(user, User.SCHEMA, resultSet);
return user;
} finally {
DBUtil.closeQuietly(resultSet);
DBUtil.closeQuietly(stmt);
}
}
/**
* Update the text fields of the given record. Any
* parameters left blank will remain unchanged. For example,
* if the password parameter is an empty string, this method
* will not change the password currently stored in the database.
*
* @param conn
* @param userid
* @param username
* @param firstname
* @param lastname
* @param email
* @param password
* @return The userid of the record that was changed.
* @throws SQLException
*/
public static boolean updateUser(Connection conn,
int userid,
String username,
String firstname,
String lastname,
String email,
String password)
throws SQLException
{
User user=findUser(conn, userid);
if (user!=null) {
if (username.length()>0) {
user.setUsername(username);
}
if (firstname.length()>0) {
user.setFirstname(firstname);
}
if (lastname.length()>0) {
user.setLastname(lastname);
}
if (email.length()>0) {
user.setEmail(email);
}
if (password.length()>0) {
user.setPasswordHash(PasswordUtil.hashPassword(password));
}
// update all the fields other than id and username
updateUserById(conn, user);
return true;
}
// couldn't find
throw new SQLException("Unable to find user record with id "+userid);
}
/**
* Create a user.
*
* @param conn database connection
* @param ccUserName user name
* @param ccPassword password (plaintext)
* @param ccWebsite user's website URL
* @return the user id of the newly-created user
* @throws SQLException
*/
public static int createOrUpdateUser(Connection conn,
String ccUserName,
String firstname,
String lastname,
String email,
String ccPassword,
String ccWebsite)
throws SQLException
{
User user=findUser(conn, ccUserName);
if (user!=null) {
user.setFirstname(firstname);
user.setLastname(lastname);
user.setEmail(email);
if (ccPassword.length()!=60 || !ccPassword.startsWith("$2a$")) {
// Sanity check to avoid re-hashing an already-hashed password:
// 1) hashed passwords are of length 60
// 2) hashed passwords start with $2a$
// If either of these isn't true, then we has the password.
// In general, no one should be passing anything other than a
// plaintext password to this method, so in theory this is
// unnecessary.
user.setPasswordHash(PasswordUtil.hashPassword(ccPassword));
}
// update all the fields other than id and username
updateUserByUsername(conn, user);
return user.getId();
} else {
user = new User();
user.setUsername(ccUserName);
user.setFirstname(firstname);
user.setLastname(lastname);
user.setEmail(email);
user.setPasswordHash(PasswordUtil.hashPassword(ccPassword));
user.setWebsite(ccWebsite);
DBUtil.storeModelObject(conn, user);
return user.getId();
}
}
public static void updateUserById(Connection conn, User user) throws SQLException
{
// Special case/hack:
// If the password hash is null, then keep the user's existing password.
if (user.getPasswordHash() == null) {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = conn.prepareStatement("select password_hash from cc_users where id = ?");
stmt.setInt(1, user.getId());
resultSet = stmt.executeQuery();
if (!resultSet.next()) {
throw new SQLException("Cannot find current password for user " + user.getId());
}
user.setPasswordHash(resultSet.getString(1));
} finally {
DBUtil.closeQuietly(resultSet);
DBUtil.closeQuietly(stmt);
}
} else if (user.getPasswordHash().length()!=60 || !user.getPasswordHash().startsWith("$2a$")) {
// Sanity check to avoid re-hashing an already-hashed password:
// 1) hashed passwords are of length 60
// 2) hashed passwords start with $2a$
// If either of these isn't true, then we has the password.
// In general, no one should be passing anything other than a
// plaintext password to this method, so in theory this is
// unnecessary.
user.setPasswordHash(PasswordUtil.hashPassword(user.getPasswordHash()));
}
String update="update " + User.SCHEMA.getDbTableName() +
" set " + DBUtil.getUpdatePlaceholdersNoId(User.SCHEMA) +
" where id = ? ";
PreparedStatement stmt=null;
try {
stmt=conn.prepareStatement(update);
int index=DBUtil.bindModelObjectValuesForUpdate(user, user.getSchema(), stmt);
stmt.setInt(index, user.getId());
stmt.executeUpdate();
} finally {
DBUtil.closeQuietly(stmt);
}
}
public static void updateUserByUsername(Connection conn, User user) throws SQLException
{
String update="update " + User.SCHEMA.getDbTableName() +
" set " + DBUtil.getUpdatePlaceholdersNoId(User.SCHEMA) +
" where username = ? ";
PreparedStatement stmt=null;
try {
stmt=conn.prepareStatement(update);
int index=DBUtil.bindModelObjectValuesForUpdate(user, user.getSchema(), stmt);
stmt.setString(index, user.getUsername());
stmt.executeUpdate();
} finally {
DBUtil.closeQuietly(stmt);
}
}
public static String ask(Scanner keyboard, String prompt, String defval) {
System.out.println(prompt);
System.out.print("[default: " + (defval != null ? defval : "") + "] ==> ");
String value = keyboard.nextLine();
if (value.trim().equals("") && defval != null) {
value = defval;
}
return value;
}
public static int registerStudentsForCourseId(InputStream in, int courseId, Connection conn) throws SQLException
{
boolean isAutoCommit = conn.getAutoCommit();
try {
conn.setAutoCommit(false);
Scanner scan=new Scanner(in);
int numAdded=0;
int numProcessed=0;
long totalStart=System.currentTimeMillis();
while (scan.hasNextLine()) {
String line=scan.nextLine().replaceAll("#.*","").trim();
if (line.equals("")) {
continue;
}
numProcessed++;
String[] tokens=line.split("\t");
String username=tokens[0];
String firstname=tokens[1];
String lastname=tokens[2];
String email=tokens[3];
String password=tokens[4];
String website = ""; // We don't attempt to set a website URL for students
int section = 101; // The default section number
if (tokens.length > 5 && tokens[5] != null) {
section=Integer.parseInt(tokens[5]);
}
logger.info("Registering "+username+" for courseId "+courseId);
// Look up the user to see if they already exist
long start=System.currentTimeMillis();
int userId;
User u=findUser(conn, username);
if (u!=null) {
userId=u.getId();
} else {
// user doesn't already exist, so create a new one
userId=createOrUpdateUser(conn,
username,
firstname,
lastname,
email,
password,
website);
}
if (registerUser(conn, userId, courseId, CourseRegistrationType.STUDENT, section)) {
numAdded++;
}
conn.commit();
long register=System.currentTimeMillis()-start;
logger.info(register+" millis to regsiter "+username);
}
long totalTime=System.currentTimeMillis()-totalStart;
logger.warn("Total time to process "+numProcessed+" students was "+totalTime);
return numAdded;
} finally {
conn.setAutoCommit(isAutoCommit);
}
}
public static int registerStudentsForCourseId2(InputStream in, int courseId, Connection conn) throws SQLException
{
Scanner scan=new Scanner(in);
Map<String,User> userMap=getAllUsers(conn);
Set<Integer> usersInCourse=getUsersInCourse(conn, courseId);
int numAdded=0;
int numProcessed=0;
long totalStart=System.currentTimeMillis();
while (scan.hasNextLine()) {
String line=scan.nextLine().replaceAll("#.*","").trim();
if (line.equals("")) {
continue;
}
numProcessed++;
String[] tokens=line.split("\t");
String username=tokens[0];
String firstname=tokens[1];
String lastname=tokens[2];
String email=tokens[3];
String password=tokens[4];
String website = ""; // We don't attempt to set a website URL for students
int section = 101; // The default section number
if (tokens.length > 5 && tokens[5] != null) {
section=Integer.parseInt(tokens[5]);
}
logger.info("Registering "+username+" for courseId "+courseId);
// Look up the user to see if they already exist
long start=System.currentTimeMillis();
int userId;
if (userMap.containsKey(username)) {
userId=userMap.get(username).getId();
} else {
// user doesn't already exist, so create a new one
userId=createOrUpdateUser(conn,
username,
firstname,
lastname,
email,
password,
website);
}
if (!usersInCourse.contains(userId)) {
registerUser(conn, userId, courseId, CourseRegistrationType.STUDENT, section);
}
long register=System.currentTimeMillis()-start;
logger.info(register+" millis to register "+username);
}
long totalTime=System.currentTimeMillis()-totalStart;
logger.warn("Total time to process "+numProcessed+" students was "+totalTime);
return numAdded;
}
private static Set<Integer> getUsersInCourse(Connection conn, int courseId)
throws SQLException
{
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = conn.prepareStatement("select * from " + CourseRegistration.SCHEMA.getDbTableName()+
" where course_id = ?");
stmt.setInt(1, courseId);
Set<Integer> users=new HashSet<Integer>();
resultSet= stmt.executeQuery();
while (resultSet.next()) {
User user=new User();
DBUtil.loadModelObjectFields(user, User.SCHEMA, resultSet);
users.add(user.getId());
}
return users;
} finally {
DBUtil.closeQuietly(resultSet);
DBUtil.closeQuietly(stmt);
} }
private static Map<String, User> getAllUsers(Connection conn)
throws SQLException
{
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = conn.prepareStatement("select * from " + User.SCHEMA.getDbTableName());
Map<String, User> userMap=new HashMap<String,User>();
resultSet= stmt.executeQuery();
while (resultSet.next()) {
User user=new User();
DBUtil.loadModelObjectFields(user, User.SCHEMA, resultSet);
userMap.put(user.getUsername(), user);
}
return userMap;
} finally {
DBUtil.closeQuietly(resultSet);
DBUtil.closeQuietly(stmt);
}
}
public static final String YES = "yes";
/**
* Configure log4j to log to stdout.
*/
public static void configureLog4j() {
Logger rootLogger = Logger.getRootLogger();
if (!rootLogger.getAllAppenders().hasMoreElements()) {
// Set this to Level.DEBUG if there are problems running the migration
rootLogger.setLevel(Level.WARN);
rootLogger.addAppender(new ConsoleAppender(new PatternLayout("%-5p [%t]: %m%n")));
}
}
/**
* Register a user for a course.
*
* @param conn the database connection
* @param userId the user id
* @param courseId the course id
* @param registrationType the registration type
* @param section the section number
* @throws SQLException
*/
public static boolean registerUser(Connection conn, int userId, int courseId, CourseRegistrationType registrationType, int section) throws SQLException {
if (findRegistration(conn, userId, courseId)!=null) {
// already registered!
return false;
}
CourseRegistration courseReg = new CourseRegistration();
courseReg.setCourseId(courseId);
courseReg.setUserId(userId);
courseReg.setRegistrationType(registrationType);
courseReg.setSection(section);
DBUtil.storeModelObject(conn, courseReg);
return true;
}
}
|
package gui;
/**
* This is the class is the main window for the project. This is also where the main function is.
* @author Tanner Zigrang
*/
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainGui extends JFrame
{
/**
* Constructor for the MainGui window
*/
public MainGui()
{
//The code below is for setting up the default window settings
this.setSize(1024, 720);
this.setLocationRelativeTo(null);
this.setTitle("SimCity201 - Team 18");
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.X_AXIS));
//The code below will add a tabbed panel to hold all the control panels. Should take the right third of the window
ControlPanel cpanel = new ControlPanel();
this.add(cpanel, Component.LEFT_ALIGNMENT);
//The code below will add an area for the two gui areas to go.
JPanel guiArea = new JPanel();
guiArea.setLayout(new BoxLayout(guiArea, BoxLayout.Y_AXIS));
guiArea.setPreferredSize(new Dimension(2048/3, 720));
guiArea.add(new WorldView());
guiArea.add(new BuildingWindow());
this.add(guiArea, Component.RIGHT_ALIGNMENT);
}
/**
* Main routine to create an instance of the MainGui window
*/
public static void main(String[] args)
{
@SuppressWarnings("unused")
MainGui gui = new MainGui();
}
}
|
package ems.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import ems.Application;
import ems.user.Student;
import ems.utils.UIutils;
public class JF_Login extends JFrame implements ActionListener,KeyListener{
private JTextField TF_LoginID = null;
private JPasswordField TF_PassWord = null;
private JCheckBox CB_password = null;
OnLoginSuccessListener loginlistener;
public interface OnLoginSuccessListener{
void OnLoginSuccess(int Authoritiy);
}
public void setOnLoginSuccessListener(OnLoginSuccessListener loginlistener){
this.loginlistener = loginlistener;
}
public JF_Login() {
this.init();
}
private void init() {
this.setTitle("ϵͳ-¼");
this.setBounds(100, 100, 400, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
this.setLocationRelativeTo(null);
this.setResizable(false);
JLabel label = new JLabel("˺");
label.setBounds(25, 23, 50, 30);
label.setFont(UIutils.font);
this.getContentPane().add(label);
JLabel label_1 = new JLabel("");
label_1.setBounds(25, 73, 50, 30);
label_1.setFont(UIutils.font);
this.getContentPane().add(label_1);
TF_LoginID = new JTextField();
TF_LoginID.setBounds(94, 23, 274, 30);
TF_LoginID.setFont(UIutils.font);
TF_LoginID.setColumns(10);
this.getContentPane().add(TF_LoginID);
TF_PassWord = new JPasswordField();
TF_PassWord.setBounds(94, 73, 274, 30);
TF_PassWord.setFont(UIutils.font);
TF_PassWord.setEchoChar('*');
TF_PassWord.addKeyListener(this);
this.getContentPane().add(TF_PassWord);
CB_password = new JCheckBox("");
CB_password.setBounds(34, 122, 30, 29);
CB_password.setActionCommand("ɼ");
this.getContentPane().add(CB_password);
JButton BT_login = new JButton("¼");
BT_login.setBounds(92, 122, 130, 30);
BT_login.setFont(UIutils.font);
BT_login.setFocusable(false);
this.getContentPane().add(BT_login);
JButton BT_cancel = new JButton("ȡ");
BT_cancel.setBounds(238, 122, 130, 30);
BT_cancel.setFont(UIutils.font);
BT_cancel.setFocusable(false);
this.getContentPane().add(BT_cancel);
CB_password.addActionListener(this);
BT_login.addActionListener(this);
BT_cancel.addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("ɼ")){
TF_PassWord.setEchoChar(CB_password.isSelected()?(char)0:'*');
}else if(e.getActionCommand().equals("¼")){
Login();
}else if(e.getActionCommand().equals("ȡ")){
System.exit(0);
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==10){
Login();
}
}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
private void Login(){
String LoginID = TF_LoginID.getText();
String PassWord = new String(TF_PassWord.getPassword());
Application mapplication = Application.getApplication();
int Authoritiy = mapplication.getMDB().login(LoginID, PassWord);
if(Authoritiy == -1){
JOptionPane.showMessageDialog(null, "¼ʧܣ", "ʾ",JOptionPane.ERROR_MESSAGE);
}else{
mapplication.setLoginID(LoginID);
loginlistener.OnLoginSuccess(Authoritiy);
//System.out.println(Authoritiy);
}
TF_LoginID.setText("");
TF_PassWord.setText("");
}
}
|
package mods.themike.modjam.inventory;
import mods.themike.modjam.items.ItemRune;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class InventoryStaff implements IInventory {
public ItemStack[] inventory = new ItemStack[1];
EntityPlayer player = null;
public InventoryStaff(EntityPlayer par1) {
player = par1;
}
@Override
public int getSizeInventory() {
return 1;
}
@Override
public ItemStack getStackInSlot(int i) {
return inventory[i];
}
@Override
public ItemStack decrStackSize(int i, int j) {
return null;
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return inventory[i];
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack) {
inventory[i] = itemstack;
ItemStack staff = player.getHeldItem();
if(staff != null) {
ItemStack rune = getStackInSlot(0);
if(rune != null) {
NBTTagCompound tag = new NBTTagCompound();
rune.writeToNBT(tag);
if (staff.getTagCompound() == null) staff.setTagCompound(new NBTTagCompound());
staff.getTagCompound().setTag("item", tag);
player.inventory.setInventorySlotContents(player.inventory.currentItem, staff);
}
}
}
@Override
public String getInvName() {
return "Staff";
}
@Override
public boolean isInvNameLocalized() {
return true;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public void onInventoryChanged() {
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return true;
}
@Override
public void openChest() {
}
@Override
public void closeChest() {
}
@Override
public boolean isStackValidForSlot(int i, ItemStack itemstack) {
return true;
}
}
|
package com.example.ictprojects.mobieleappbowling;
import android.app.Activity;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class AddScoreActivity extends AppCompatActivity
implements View.OnClickListener{
EditText editTotaleScore;
EditText editAantalStrikes;
EditText editAantalspares;
TextView isConnected;
Button submitScoreButton;
ScoreData score;
String TotaleScore;
String AantalStrikes;
String AantalSpares;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addscore_main);
editTotaleScore = (EditText) findViewById(R.id.editTotaleScore);
editAantalStrikes = (EditText) findViewById(R.id.editAantalStrikes);
editAantalspares = (EditText) findViewById(R.id.editAantalspares);
submitScoreButton = (Button) findViewById(R.id.submitScoreButton);
isConnected = (TextView) findViewById(R.id.isConnected);
editTotaleScore.setFilters(new InputFilter[] {new InputFilterMinMax("0", "300")});
editAantalspares.setFilters(new InputFilter[] {new InputFilterMinMax("0", "10")});
editAantalStrikes.setFilters(new InputFilter[] {new InputFilterMinMax("0", "12")});
if(isConnected())
{
isConnected.setBackgroundColor(0xFF00CC00);
isConnected.setText("Connected");
}
else
{
isConnected.setText("No connection");
}
submitScoreButton.setOnClickListener(this);
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
public static String POST(String url,ScoreData score){ //url veranderd
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("Totaal", score.getTotaleScore());
jsonObject.accumulate("Strikes",score.getAantalStrikes());
jsonObject.accumulate("Spare",score.getAantalSpares());
jsonObject.accumulate("Game_ID",3);
jsonObject.accumulate("Google_ID",3);
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept","application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
{
result = convertInputStreamToString(inputStream);
}
else
{
result = "Did not work!";
}
}
catch(Exception e)
{
Log.d("Inputstream", e.getLocalizedMessage());
}
return result;
}
@Override
public void onClick(View view) {
TotaleScore = editTotaleScore.getText().toString();
AantalStrikes = editAantalStrikes.getText().toString();
AantalSpares = editAantalspares.getText().toString();
switch(view.getId()){
case R.id.submitScoreButton:
if(!validate())
Toast.makeText(getBaseContext(),"Enter some data!",Toast.LENGTH_LONG).show();
new HttpAsyncTask().execute("http://localhost/ICTProjects3/ScoreController/MobileApp");
break;
}
}
// heb hier iets moeten veranderen. Extra klasse en geen override. Ik weet niet als dit juist is! Team Bilbo
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
score = new ScoreData();
score.setTotaleScore(TotaleScore);
score.setAantalStrikes(AantalStrikes);
score.setAantalSpares(AantalSpares);
return POST(urls[0],score);
}
//@Override
//protected String doInBackground(String... params) {
// return null;
/*private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected int doInBackground(Integer... urls){
score = new ScoreData();
score.setTotaleScore(Integer.parseInt(editTotaleScore.getText().toString()));
score.setAantalStrikes(Integer.parseInt(editAantalStrikes.getText().toString()));
score.setAantalSpares(Integer.parseInt(editAantalspares.getText().toString()));
return POST(urls[0],score);
}*/
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(),"Data Sent!",Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(editTotaleScore.getText().toString().trim().equals(""))
return false;
else if(editAantalStrikes.getText().toString().trim().equals(""))
return false;
else if(editAantalspares.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader((inputStream)));
String line = "";
String result = "" ;
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();;
return result;
}
}
|
package <%=packageName%>.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.core.io.ClassPathResource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Utility class to load a Spring profile to be used as default
* when there is no <code>spring.profiles.active</code> set in the environment or as command line argument.
* If the value is not available in <code>application.yml</code> then <code>dev</code> profile will be used as default.
*/
public final class DefaultProfileUtil {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(DefaultProfileUtil.class);
private static final String SPRING_PROFILE_ACTIVE = "spring.profiles.active";
private static final Properties BUILD_PROPERTIES = readProperties();
/**
* Get a default profile from <code>application.yml</code>.
*/
public static String getDefaultActiveProfiles(){
if (BUILD_PROPERTIES != null) {
String activeProfile = BUILD_PROPERTIES.getProperty(SPRING_PROFILE_ACTIVE);
if (activeProfile != null && !activeProfile.isEmpty() &&
(activeProfile.contains(Constants.SPRING_PROFILE_DEVELOPMENT) ||
activeProfile.contains(Constants.SPRING_PROFILE_PRODUCTION))) {
return activeProfile;
}
}
log.warn("No Spring profile configured, running with default profile: {}", Constants.SPRING_PROFILE_DEVELOPMENT);
return Constants.SPRING_PROFILE_DEVELOPMENT;
}
/**
* Set a default to use when no profile is configured.
*/
public static void addDefaultProfile(SpringApplication app) {
Map<String, Object> defProperties = new HashMap<>();
defProperties.put(SPRING_PROFILE_ACTIVE, getDefaultActiveProfiles());
app.setDefaultProperties(defProperties);
}
/**
* Load application.yml from classpath.
*/
private static Properties readProperties() {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ClassPathResource("config/application.yml"));
return factory.getObject();
} catch (Exception e) {
log.error("Failed to read application.yml to get default profile");
}
return null;
}
}
|
package org.lilyproject.hadooptestfw;
import static org.apache.zookeeper.ZooKeeper.States.CONNECTED;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.catalog.MetaReader;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.ipc.HRegionInterface;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.zookeeper.*;
import org.lilyproject.util.hbase.HBaseAdminFactory;
public class CleanupUtil {
private Configuration conf;
private String zkConnectString;
private static Set<String> RETAIN_TABLES = new HashSet<String>();
static {
}
private static Map<String, byte[]> DEFAULT_TIMESTAMP_REUSING_TABLES = new HashMap<String, byte[]>();
static {
DEFAULT_TIMESTAMP_REUSING_TABLES.put("record", Bytes.toBytes("data"));
DEFAULT_TIMESTAMP_REUSING_TABLES.put("type", Bytes.toBytes("fieldtype-entry"));
}
public CleanupUtil(Configuration conf, String zkConnectString) {
this.conf = conf;
this.zkConnectString = zkConnectString;
}
public Map<String, byte[]> getDefaultTimestampReusingTables() {
return Collections.unmodifiableMap(DEFAULT_TIMESTAMP_REUSING_TABLES);
}
public void cleanZooKeeper() throws Exception {
int sessionTimeout = 10000;
ZooKeeper zk = new ZooKeeper(zkConnectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Watcher.Event.KeeperState.Disconnected) {
System.err.println("ZooKeeper Disconnected.");
} else if (event.getState() == Event.KeeperState.Expired) {
System.err.println("ZooKeeper session expired.");
}
}
});
long waitUntil = System.currentTimeMillis() + sessionTimeout;
while (zk.getState() != CONNECTED && waitUntil > System.currentTimeMillis()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
break;
}
}
if (zk.getState() != CONNECTED) {
throw new RuntimeException("Failed to connect to ZK within " + sessionTimeout + "ms.");
}
if (zk.exists("/lily", false) != null) {
System.out.println("
List<String> paths = new ArrayList<String>();
collectChildren("/lily", zk, paths);
paths.add("/lily");
for (String path : paths) {
zk.delete(path, -1, null, null);
}
long startWait = System.currentTimeMillis();
while (zk.exists("/lily", null) != null) {
Thread.sleep(5);
if (System.currentTimeMillis() - startWait > 120000) {
throw new RuntimeException("State was not cleared in ZK within the expected timeout");
}
}
System.out.println("Deleted " + paths.size() + " paths from ZooKeeper");
System.out.println("
}
zk.close();
}
private void collectChildren(String path, ZooKeeper zk, List<String> paths) throws InterruptedException, KeeperException {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
String childPath = path + "/" + child;
collectChildren(childPath, zk, paths);
paths.add(childPath);
}
}
public void cleanTables() throws Exception {
Map<String, byte[]> timestampReusingTables = new HashMap<String, byte[]>();
timestampReusingTables.putAll(DEFAULT_TIMESTAMP_REUSING_TABLES);
cleanTables(timestampReusingTables);
}
public void cleanTables(Map<String, byte[]> timestampReusingTables) throws Exception {
System.out.println("
StringBuilder truncateReport = new StringBuilder();
StringBuilder retainReport = new StringBuilder();
HBaseAdmin admin = HBaseAdminFactory.get(conf);
HTableDescriptor[] tables = admin.listTables();
System.out.println("Found tables: " + tables.length);
Set<String> exploitTimestampTables = new HashSet<String>();
for (HTableDescriptor table : tables) {
if (RETAIN_TABLES.contains(table.getNameAsString())) {
if (retainReport.length() > 0)
retainReport.append(", ");
retainReport.append(table.getNameAsString());
continue;
}
HTable htable = new HTable(conf, table.getName());
if (timestampReusingTables.containsKey(table.getNameAsString())) {
insertTimestampTableTestRecord(table.getNameAsString(), htable,
timestampReusingTables.get(table.getNameAsString()));
exploitTimestampTables.add(table.getNameAsString());
}
Scan scan = new Scan();
scan.setCaching(1000);
scan.setCacheBlocks(false);
ResultScanner scanner = htable.getScanner(scan);
Result[] results;
int totalCount = 0;
while ((results = scanner.next(1000)).length > 0) {
List<Delete> deletes = new ArrayList<Delete>(results.length);
for (Result result : results) {
deletes.add(new Delete(result.getRow()));
}
totalCount += deletes.size();
htable.delete(deletes);
}
if (truncateReport.length() > 0)
truncateReport.append(", ");
truncateReport.append(table.getNameAsString()).append(" (").append(totalCount).append(")");
scanner.close();
htable.close();
if (timestampReusingTables.containsKey(table.getNameAsString())) {
flush(admin, table.getNameAsString());
admin.majorCompact(table.getName());
}
}
truncateReport.insert(0, "Truncated the following tables: ");
retainReport.insert(0, "Did not truncate the following tables: ");
System.out.println(truncateReport);
System.out.println(retainReport);
waitForTimestampTables(exploitTimestampTables, timestampReusingTables);
System.out.println("
}
private void insertTimestampTableTestRecord(String tableName, HTable htable, byte[] family) throws IOException {
byte[] tmpRowKey = Bytes.toBytes("HBaseProxyDummyRow");
byte[] COL = Bytes.toBytes("DummyColumn");
Put put = new Put(tmpRowKey);
// put a value with a fixed timestamp
put.add(family, COL, 1, new byte[] { 0 });
htable.put(put);
}
private void waitForTimestampTables(Set<String> tables, Map<String, byte[]> timestampReusingTables)
throws IOException, InterruptedException {
for (String tableName : tables) {
HTable htable = new HTable(conf, tableName);
byte[] CF = timestampReusingTables.get(tableName);
byte[] tmpRowKey = waitForCompact(tableName, CF);
// Delete our dummy row again
htable.delete(new Delete(tmpRowKey));
}
}
private byte[] waitForCompact(String tableName, byte[] CF) throws IOException, InterruptedException {
byte[] tmpRowKey = Bytes.toBytes("HBaseProxyDummyRow");
byte[] COL = Bytes.toBytes("DummyColumn");
HTable htable = new HTable(conf, tableName);
byte[] value = null;
while (value == null) {
Put put = new Put(tmpRowKey);
put.add(CF, COL, 1, new byte[] { 0 });
htable.put(put);
Get get = new Get(tmpRowKey);
Result result = htable.get(get);
value = result.getValue(CF, COL);
if (value == null) {
// If the value is null, it is because the delete marker has not yet been flushed/compacted away
System.out.println("Waiting for flush/compact of " + tableName + " to complete");
Thread.sleep(100);
}
}
return tmpRowKey;
}
/** Force a major compaction and wait for it to finish.
* This method can be used in a test to avoid issue HBASE-2256 after performing a delete operation
* Uses same principle as {@link #cleanTables}
*/
public void majorCompact(String tableName, String[] columnFamilies) throws Exception {
byte[] tmpRowKey = Bytes.toBytes("HBaseProxyDummyRow");
byte[] COL = Bytes.toBytes("DummyColumn");
HBaseAdmin admin = HBaseAdminFactory.get(conf);
HTable htable = new HTable(conf, tableName);
// Write a dummy row
for (String columnFamily : columnFamilies) {
byte[] CF = Bytes.toBytes(columnFamily);
Put put = new Put(tmpRowKey);
put.add(CF, COL, 1, new byte[] { 0 });
htable.put(put);
// Delete the value again
Delete delete = new Delete(tmpRowKey);
delete.deleteColumn(CF, COL);
htable.delete(delete);
}
// Perform major compaction
flush(admin, tableName);
admin.majorCompact(tableName);
// Wait for compact to finish
for (String columnFamily : columnFamilies) {
byte[] CF = Bytes.toBytes(columnFamily);
waitForCompact(tableName, CF);
}
}
public void cleanBlobStore(URI dfsUri) throws Exception {
FileSystem fs = FileSystem.get(new URI(dfsUri.getScheme() + "://" + dfsUri.getAuthority()), conf);
Path blobRootPath = new Path(dfsUri.getPath());
fs.delete(blobRootPath, true);
}
/**
* This method was copied from HBase's HBaseAdmin source file in order to fix a connection leak:
* the CatalogTracker was not closed, this would among other things leak a ZooKeeper client connection
* on each flush (especially important when this is used in the LilyLauncher).
*
* <p></p>This bug was present in chd3u, but already fixed in HBase trunk, so this method can be
* removed after upgrade.
*/
private void flush(HBaseAdmin hbaseAdmin, String tableName) throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
List<Pair<HRegionInfo, HServerAddress>> pairs =
MetaReader.getTableRegionsAndLocations(ct, tableName);
for (Pair<HRegionInfo, HServerAddress> pair: pairs) {
if (pair.getSecond() == null) continue;
flush(hbaseAdmin, pair.getSecond(), pair.getFirst());
}
} finally {
cleanupCatalogTracker(ct);
}
}
/** Copied from HBase source to support flush fix. */
private void flush(HBaseAdmin hbaseAdmin, final HServerAddress hsa, final HRegionInfo hri)
throws IOException {
HRegionInterface rs = hbaseAdmin.getConnection().getHRegionConnection(hsa);
rs.flushRegion(hri);
}
/** Copied from HBase source to support flush fix. */
private synchronized CatalogTracker getCatalogTracker()
throws ZooKeeperConnectionException, IOException {
CatalogTracker ct = null;
try {
HConnection connection =
HConnectionManager.getConnection(new Configuration(this.conf));
ct = new CatalogTracker(connection);
ct.start();
} catch (InterruptedException e) {
// Let it out as an IOE for now until we redo all so tolerate IEs
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
}
return ct;
}
/** Copied from HBase source to support flush fix. */
private void cleanupCatalogTracker(final CatalogTracker ct) {
ct.stop();
HConnectionManager.deleteConnection(ct.getConnection().getConfiguration(), true);
}
}
|
package lecho.lib.hellocharts.renderer;
import lecho.lib.hellocharts.ChartComputator;
import lecho.lib.hellocharts.model.ChartData;
import lecho.lib.hellocharts.model.SelectedValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.Utils;
import lecho.lib.hellocharts.view.Chart;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
public abstract class AbstractChartRenderer implements ChartRenderer {
public int DEFAULT_LABEL_MARGIN_DP = 4;
protected Chart chart;
protected Paint labelPaint = new Paint();
protected Paint labelBackgroundPaint = new Paint();
protected RectF labelBackgroundRect = new RectF();
protected FontMetricsInt fontMetrics = new FontMetricsInt();
protected Viewport tempMaxViewport = new Viewport();
protected float density;
protected float scaledDensity;
protected SelectedValue selectedValue = new SelectedValue();
protected char[] labelBuffer = new char[32];
protected int labelOffset;
protected int labelMargin;
protected boolean isValueLabelBackgroundEnabled;
protected boolean isValueLabelBackgrountAuto;
protected int valueLabelBackgroundColor;
public AbstractChartRenderer(Context context, Chart chart) {
this.density = context.getResources().getDisplayMetrics().density;
this.scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
this.chart = chart;
labelMargin = Utils.dp2px(density, DEFAULT_LABEL_MARGIN_DP);
labelOffset = labelMargin;
labelPaint.setAntiAlias(true);
labelPaint.setStyle(Paint.Style.FILL);
labelPaint.setTextAlign(Align.LEFT);
labelPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
labelPaint.setColor(Color.WHITE);
labelBackgroundPaint.setAntiAlias(true);
labelBackgroundPaint.setStyle(Paint.Style.FILL);
}
@Override
public void initCurrentViewport() {
ChartComputator computator = chart.getChartComputator();
computator.setCurrentViewport(computator.getMaximumViewport());
}
@Override
public void initDataAttributes() {
final ChartData data = chart.getChartData();
Typeface typeface = chart.getChartData().getValueLabelTypeface();
if (null != typeface) {
labelPaint.setTypeface(typeface);
}
labelPaint.setTextSize(Utils.sp2px(scaledDensity, data.getValueLabelTextSize()));
labelPaint.getFontMetricsInt(fontMetrics);
this.isValueLabelBackgroundEnabled = data.isValueLabelBackgroundEnabled();
this.isValueLabelBackgrountAuto = data.isValueLabelBackgroundAuto();
this.valueLabelBackgroundColor = data.getValueLabelBackgroundColor();
this.labelBackgroundPaint.setColor(valueLabelBackgroundColor);
// Important - clear selection when data changed.
selectedValue.clear();
}
/**
* Draws label text and label background if isValueLabelBackgroundEnabled is true.
*/
protected void drawLabelTextAndBackground(Canvas canvas, char[] labelBuffer, int startIndex, int numChars,
int autoBackgroundColor) {
final float textX;
final float textY;
if (isValueLabelBackgroundEnabled) {
if (isValueLabelBackgrountAuto) {
labelBackgroundPaint.setColor(autoBackgroundColor);
}
canvas.drawRect(labelBackgroundRect, labelBackgroundPaint);
textX = labelBackgroundRect.left + labelMargin;
textY = labelBackgroundRect.bottom - labelMargin;
} else {
textX = labelBackgroundRect.left;
textY = labelBackgroundRect.bottom;
}
canvas.drawText(labelBuffer, startIndex, numChars, textX, textY, labelPaint);
}
@Override
public boolean isTouched() {
return selectedValue.isSet();
}
@Override
public void clearTouch() {
selectedValue.clear();
}
@Override
public void setMaxViewport(Viewport maxViewport) {
if (null == maxViewport) {
initMaxViewport();
} else {
this.tempMaxViewport.set(maxViewport);
chart.getChartComputator().setMaxViewport(maxViewport);
}
}
@Override
public Viewport getMaxViewport() {
return tempMaxViewport;
}
@Override
public void setViewport(Viewport viewport) {
if (null == viewport) {
initCurrentViewport();
} else {
chart.getChartComputator().setCurrentViewport(viewport);
}
}
@Override
public Viewport getViewport() {
return chart.getChartComputator().getCurrentViewport();
}
@Override
public void selectValue(SelectedValue selectedValue) {
this.selectedValue.set(selectedValue);
}
@Override
public SelectedValue getSelectedValue() {
return selectedValue;
}
}
|
package com.bbcnewsreader.data;
import java.util.Date;
import java.text.SimpleDateFormat;
import com.bbcnewsreader.R;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DatabaseHandler {
private static final String DATABASE_NAME = "bbcnewsreader.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "items";
private static final String TABLE2_NAME = "categories";
private static final String TABLE3_NAME = "categories_items";
private static final String TABLE_CREATE ="CREATE TABLE " + TABLE_NAME +
"(item_Id integer PRIMARY KEY," +
"title varchar(255), " +
"description varchar(255), " +
"link varchar(255), " +
"pubdate int)";
private static final String TABLE2_CREATE="CREATE TABLE " + TABLE2_NAME +
"(category_Id integer PRIMARY KEY," +
"name varchar(255)," +
"enabled int," +
"url varchar(255))";
private static final String TABLE3_CREATE="CREATE TABLE " + TABLE3_NAME +
"(categoryName varchar(255), " +
"itemId INT)";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
public DatabaseHandler(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
}
/**
* Inserts an RSSItem into the items table, then creates an entry in the relationship
* table between it and its category
* @param title News item's Title as String
* @param description News item's Description as String
* @param link News item's link as String
* @param pubdate News item's published data as String
* @param category News item's category as String
*/
public void insertItem(String title, String description, String link, String pubdate, String category)
{
//Formats the date of the item to Date object, then gets the UNIX TIMESTAMP from the Date.
SimpleDateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
long timestamp=0;
try
{
Date parsed=format.parse(pubdate);
timestamp=parsed.getTime();
}catch(Exception e)
{
//Log.v("ERROR",e.toString());
}
//Compiles then executes the insertion of the item into the items database.
//Takes the rowid of the new record and uses it to get the item_id.
//Moves to first item in Cursor then inserts item_id and category into relationship table.
Cursor cursor=db.query(false,TABLE_NAME,new String[]{"item_Id"},"title=?",new String[] {title},null,null,null,null);
ContentValues cv=null;
if(cursor.getCount()==0)
{
cv=new ContentValues(4);
cv.put("title",title);
cv.put("description",description);
cv.put("link",link);
cv.put("pubdate",timestamp);
long rowid=db.insert(TABLE_NAME, null, cv);
cursor=db.query(false,TABLE_NAME,new String[]{"item_Id"},"rowid=?",new String[] {Long.toString(rowid)},null,null,null, null);
}
cursor.moveToNext();
int itemid=cursor.getInt(0);
cv=new ContentValues(2);
cv.put("categoryName",category);
cv.put("itemId",itemid);
db.insert(TABLE3_NAME, null, cv);
cursor.close();
}
/**
* Adds all the start categories from the XML
*/
public void addCategories()
{
try
{
String[] categoryNames = context.getResources().getStringArray(R.array.category_names);
String[] categoryUrls = context.getResources().getStringArray(R.array.catergory_rss_urls);
for(int i=0;i<categoryNames.length;i++)
{
insertCategory(categoryNames[i],true,categoryUrls[i]);
}
}catch(NullPointerException e)
{
Log.e("categories-xml","Categories XML is broken");
}
}
/**
* Checks whether there are any records in category
* @return true or false
*/
public boolean isCreated()
{
try
{
getCategoryBooleans()[0]=true;
return true;
}
catch(Exception e)
{
return false;
}
}
/**
* Inserts a category into the category table.
* @param name Name of the category as String
* @param enabled Whether the RSSFeed should be fetched as Boolean
*/
public void insertCategory(String name,boolean enabledB,String url)
{
int enabledI;
if(enabledB){enabledI=1;}else{enabledI=0;}
ContentValues cv=new ContentValues(3);
cv.put("name",name);
cv.put("enabled",enabledI);
cv.put("url",url);
db.insert(TABLE2_NAME, null, cv);
}
/**
* Clears all the tables in the database, leaving structure intact.
*/
public void clear() {
db.execSQL("DELETE from "+TABLE_NAME);
db.execSQL("DELETE from "+TABLE2_NAME);
db.execSQL("DELETE from "+TABLE3_NAME);
}
/**
* Drops the entire database then rebuilds it.
*/
public void dropTables()
{
db.execSQL("DROP TABLE "+TABLE_NAME);
db.execSQL("DROP TABLE "+TABLE2_NAME);
db.execSQL("DROP TABLE "+TABLE3_NAME);
}
/**
* Attempts to create the tables.
*/
public void createTables()
{
db.execSQL(TABLE_CREATE);
db.execSQL(TABLE2_CREATE);
db.execSQL(TABLE3_CREATE);
}
/**
* Drops then recreates all the tables.
*/
public void reset()
{
dropTables();
createTables();
}
/**
* Queries the categories table for the enabled column of all rows,
* returning an array of booleans representing whether categories are enabled or not,
* sorted by category_Id.
* @return boolean[] containing enabled column from categories table.
*/
public boolean[] getCategoryBooleans()
{
//FIXME Optimise
Cursor cursor=db.query(TABLE2_NAME, new String[]{"enabled"}, null, null, null, null, "category_Id");
boolean[] enabledCategories = new boolean[cursor.getCount()];
for(int i=1;i<=cursor.getCount();i++)
{
cursor.moveToNext();
if(cursor.getInt(0)==0)
{
enabledCategories[i-1]=false;
}
else
{
enabledCategories[i-1]=true;
}
}
cursor.close();
return enabledCategories;
}
/**
* Returns the links of all the categories that are enabled.
* @return A string[] containing the String urls.
*/
public String[] getEnabledCategories()
{
//Queries the category table to get a list of enabled categories
Cursor cursor=db.query(TABLE2_NAME, new String[]{"url"}, "enabled='1'", null, null, null, "category_Id");
String[] categories=new String[cursor.getCount()];
for(int i=1;i<=cursor.getCount();i++)
{
cursor.moveToNext();
categories[i-1]=cursor.getString(0);
}
cursor.close();
return categories;
}
/**
* Takes an array of booleans and sets the first n categories
* to those values. Where n is length of array
* @param enabled A boolean array of "enabled" values
*/
public void setEnabledCategories(boolean[] enabled) throws NullPointerException
{
ContentValues cv=new ContentValues(1);
for(int i=1;i<enabled.length;i++)
{
if(enabled[i]){cv.put("enabled", 1);}
else{cv.put("enabled", 0);}
db.update(TABLE2_NAME, cv, "category_Id=?", new String[]{Integer.toString(i)});
cv.clear();
}
}
/**
* Takes a category and returns all the title, description and link of all
* the items related to it.
* @param category The Case-sensitive name of the category
* @return A String[{title,description,link}][{item1,item2}].
*/
public String[][] getItems(String category)
{
//FIXME Optimise, add limit? NOT SQL INJECTION SAFE (But internal, so k)
//Query the relation table to get a list of Item_Ids.
Cursor cursor=db.query(TABLE3_NAME, new String[]{"itemId"}, "categoryName=?", new String[]{category}, null, null, null);
/*Create a string consisting of the first item_Id, then a loop appending
* ORs and further item_Id
*/
cursor.moveToNext();
String itemIdQuery=new String("item_Id='"+cursor.getString(0)+"'");
for(int i=2;i<=cursor.getCount();i++)
{
cursor.moveToNext();
itemIdQuery+=(" OR item_Id='"+cursor.getString(0)+"'");
}
//Query the items table to get a the rows with that category
//then fill the String[][] and return it
cursor=db.query(TABLE_NAME,new String[]{"title", "description", "link"},itemIdQuery,null,null,null,"pubdate");
String[][] items=new String[3][cursor.getCount()];
for(int i=1;i<=cursor.getCount();i++)
{
cursor.moveToNext();
items[0][i-1]=cursor.getString(0);
items[1][i-1]=cursor.getString(1);
items[2][i-1]=cursor.getString(2);
}
cursor.close();
return items;
}
/**
* Sets the given category to the given boolean
* @param category The String category you wish to change.
* @param enabled The boolean value you wish to set it to.
*/
public void setEnabled(String category,boolean enabled)
{
//FIXME Skip first step?
//Query the categories table for the id of the category with that name
//Then fetch the id from the first one returned
Cursor cursor=db.query(TABLE2_NAME,new String[]{"category_Id"},"name=?",new String[]{category},null,null,null);
cursor.moveToNext();
int categoryId=cursor.getInt(0);
//Create a box containing the new value/column
ContentValues cv=new ContentValues(1);
if(enabled){cv.put("enabled", 1);}
else{cv.put("enabled", 0);}
//push up to database.
db.update(TABLE2_NAME, cv, "category_Id=?", new String[]{Integer.toString(categoryId)});
cursor.close();
}
/**
* When called will remove all articles that are
* over one month to the second old. Then cleans up
* the relationship table. Possibly resource intensive.
*/
public void clearOld()
{
//FIXME Add parameter, customize the date it wipes from. Optimise?
//Creates a java.util date object with current time
//Subtracts one month in milliseconds and deletes all
//items with a pubdate less than that value.
Date now=new Date();
long oldTime=(now.getTime()-2629743000L);
Cursor cursor=db.query(TABLE_NAME,new String[]{"item_Id"},"pubdate<?",new String[]{Long.toString(oldTime)},null,null,null);
for(int i=1;i<=cursor.getCount();i++)
{
cursor.moveToNext();
db.delete(TABLE3_NAME,"itemId=?",new String[]{Integer.toString(cursor.getInt(0))});
}
db.delete(TABLE_NAME,"pubdate<?",new String[]{Long.toString(oldTime)});
cursor.close();
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//Creates the three tables
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
|
package com.intellij.codeInspection.ex;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ModifiableModel;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.DefaultTreeExpander;
import com.intellij.ide.TreeExpander;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.ide.ui.search.SearchUtil;
import com.intellij.ide.ui.search.SearchableOptionsRegistrar;
import com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.packageDependencies.ui.TreeExpansionMonitor;
import com.intellij.profile.ProfileManager;
import com.intellij.profile.codeInspection.SeverityProvider;
import com.intellij.ui.*;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ResourceUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.Tree;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.*;
import java.util.List;
public class SingleInspectionProfilePanel extends JPanel {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionToolsPanel");
private static final Icon SHOW_INSPECTION_SETTINGS = IconLoader.getIcon("/objectBrowser/showGlobalInspections.png");
@NonNls private static final String INSPECTION_FILTER_HISTORY = "INSPECTION_FILTER_HISTORY";
private static final String UNDER_CONSTRUCTION = InspectionsBundle.message("inspection.tool.description.under.construction.text");
private final ArrayList<Descriptor> myDescriptors = new ArrayList<Descriptor>();
private ModifiableModel mySelectedProfile;
private JEditorPane myBrowser;
private JPanel myOptionsPanel;
private final UserActivityWatcher myUserActivityWatcher = new UserActivityWatcher();
private final JPanel myInspectionProfilePanel = new JPanel(new BorderLayout());
private FilterComponent myProfileFilter;
private final MyTreeNode myRoot = new MyTreeNode(InspectionsBundle.message("inspection.root.node.title"), false, false);
private final Alarm myAlarm = new Alarm();
private boolean myShowInspections = true;
private boolean myModified = false;
private Tree myTree;
private TreeExpander myTreeExpander;
private String myInitialProfile;
@NonNls private static final String EMPTY_HTML = "<html><body></body></html>";
public SingleInspectionProfilePanel(String inspectionProfileName) {
this(inspectionProfileName, null);
}
public SingleInspectionProfilePanel(final String inspectionProfileName, final ModifiableModel profile) {
super(new BorderLayout());
mySelectedProfile = profile;
myInitialProfile = inspectionProfileName;
add(createInspectionProfileSettingsPanel(), BorderLayout.CENTER);
myUserActivityWatcher.addUserActivityListener(new UserActivityListener() {
public void stateChanged() {
//invoke after all other listeners
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (mySelectedProfile == null) return; //panel was disposed
updateProperSettingsForSelection();
wereToolSettingsModified();
}
});
}
});
myUserActivityWatcher.register(myOptionsPanel);
updateSelectedProfileState();
}
private void updateSelectedProfileState() {
if (mySelectedProfile == null) return;
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().restoreVisibleState(myTree);
repaintTableData();
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
TreeUtil.showRowCentered(myTree, myTree.getRowForPath(selectionPath), false);
}
}
private void wereToolSettingsModified() {
for (Descriptor descriptor : myDescriptors) {
if (mySelectedProfile.getErrorLevel(descriptor.getKey()) != descriptor.getLevel()) {
myModified = true;
return;
}
InspectionProfileEntry tool = descriptor.getTool();
if (tool != null) {
if (descriptor.isEnabled()) {
Element oldConfig = descriptor.getConfig();
if (oldConfig == null) continue;
@NonNls Element newConfig = new Element("options");
try {
tool.writeSettings(newConfig);
}
catch (WriteExternalException e) {
LOG.error(e);
}
if (!JDOMUtil.areElementsEqual(oldConfig, newConfig)) {
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
myTree.repaint();
}
}, 300);
myModified = true;
return;
}
}
}
}
myModified = false;
}
private void updateProperSettingsForSelection() {
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
MyTreeNode node = (MyTreeNode)selectionPath.getLastPathComponent();
if (node.getUserObject()instanceof Descriptor) {
final boolean properSetting = mySelectedProfile.isProperSetting(((Descriptor)node.getUserObject()).getKey());
if (node.isProperSetting != properSetting) {
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
myTree.repaint();
}
}, 300);
node.isProperSetting = properSetting;
updateUpHierarchy(node, (MyTreeNode)node.getParent());
}
}
}
}
private void initDescriptors() {
if (mySelectedProfile == null) return;
myDescriptors.clear();
InspectionProfileEntry[] tools = mySelectedProfile.getInspectionTools();
final InspectionProfile profile = getSavedProfile();
for (InspectionProfileEntry tool : tools) {
myDescriptors.add(new Descriptor(tool, profile != null
? profile
: InspectionProfileImpl.getDefaultProfile())); //fix for new profile - isModified == true by default
}
}
public void resetToBaseAction() {
mySelectedProfile.resetToBase();
wereToolSettingsModified();
//resetup configs
for (Descriptor descriptor : myDescriptors) {
descriptor.resetConfigPanel();
}
fillTreeData(myProfileFilter.getFilter(), true);
repaintTableData();
updateOptionsAndDescriptionPanel(myTree.getSelectionPath());
}
@Nullable
public static ModifiableModel createNewProfile(final int initValue,
ModifiableModel selectedProfile,
Project project,
ProfileManager ideProfileManager,
ProfileManager currentProfileManager,
String profileName,
boolean isLocalProfile) {
InputDialog dlg = new InputDialog(ideProfileManager != null && !project.isDefault(), profileName, isLocalProfile ? InspectionsBundle
.message("profile.save.as.project.checkbox.title") : InspectionsBundle
.message("profile.save.as.ide.checkbox.title"), project);
dlg.show();
if (!dlg.isOK()) return null;
profileName = dlg.getName();
final boolean isLocal = isLocalProfile && !dlg.isChecked() || !isLocalProfile && dlg.isChecked();
ProfileManager profileManager = isLocal && ideProfileManager != null ? ideProfileManager : currentProfileManager;
if (ArrayUtil.find(currentProfileManager.getAvailableProfileNames(), profileName) != -1 ||
ideProfileManager != null && ArrayUtil.find(ideProfileManager.getAvailableProfileNames(), profileName) != -1) {
Messages.showErrorDialog(InspectionsBundle.message("inspection.unable.to.create.profile.message", profileName),
InspectionsBundle.message("inspection.unable.to.create.profile.dialog.title"));
return null;
}
try {
InspectionProfileImpl inspectionProfile =
new InspectionProfileImpl(profileName, profileManager.createUniqueProfileFile(profileName), InspectionToolRegistrar.getInstance(), profileManager);
final ModifiableModel profileModifiableModel = inspectionProfile.getModifiableModel();
if (selectedProfile != null) { //can be null for default or empty profile
profileModifiableModel.copyFrom(selectedProfile);
}
if (initValue == -1) {
final InspectionProfileEntry[] profileEntries = profileModifiableModel.getInspectionTools();
for (InspectionProfileEntry entry : profileEntries) {
profileModifiableModel.disableTool(entry.getShortName());
}
}
else if (initValue == 1) {
profileModifiableModel.resetToBase();
}
profileModifiableModel.setName(profileName);
profileModifiableModel.setLocal(isLocal);
return profileModifiableModel;
}
catch (IOException e) {
LOG.error(e);
}
return null;
}
public void filterTree(String filter) {
if (myTree != null) {
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().saveVisibleState(myTree);
fillTreeData(filter, true);
((DefaultTreeModel)myTree.getModel()).reload();
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().restoreVisibleState(myTree);
if (myTree.getSelectionPath() == null) {
TreeUtil.selectFirstNode(myTree);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myTree.requestFocus();
}
});
}
}
private ActionToolbar createTreeToolbarPanel() {
final CommonActionsManager actionManager = CommonActionsManager.getInstance();
DefaultActionGroup actions = new DefaultActionGroup();
actions.add(actionManager.createExpandAllAction(myTreeExpander, myTree));
actions.add(actionManager.createCollapseAllAction(myTreeExpander, myTree));
actions.add(new ToggleAction(InspectionsBundle.message("inspection.tools.action.show.global.inspections.text"),
InspectionsBundle.message("inspection.tools.action.show.global.inspections.description"),
SHOW_INSPECTION_SETTINGS) {
public boolean isSelected(AnActionEvent e) {
return !myShowInspections;
}
public void setSelected(AnActionEvent e, boolean state) {
myShowInspections = !state;
filterTree(myProfileFilter.getFilter());
}
});
actions.add(new AnAction(InspectionsBundle.message("what.s.new.in.idea.7"),
InspectionsBundle.message("what.s.new.in.idea.7.description"), IconLoader.getIcon("/actions/lightning.png")) {
public void actionPerformed(AnActionEvent e) {
setFilter("New in 7");
myProfileFilter.selectText();
myProfileFilter.requestFocusInWindow();
}
});
return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true);
}
private void repaintTableData() {
if (myTree != null) {
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().saveVisibleState(myTree);
((DefaultTreeModel)myTree.getModel()).reload();
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().restoreVisibleState(myTree);
}
}
public void selectInspectionTool(String name) {
MyTreeNode node = null;
for (int i = 0; i < myRoot.getChildCount(); i++) {
final MyTreeNode child = (MyTreeNode)myRoot.getChildAt(i);
for (int j = 0; j < child.getChildCount(); j++) {
if (((Descriptor)((DefaultMutableTreeNode)child.getChildAt(j)).getUserObject()).getKey().toString().equals(name)) {
node = (MyTreeNode)child.getChildAt(j);
break;
}
}
}
if (node != null) {
TreeUtil.showRowCentered(myTree, myTree.getRowForPath(new TreePath(node.getPath())) - 1, true);//myTree.isRootVisible ? 0 : 1;
TreeUtil.selectNode(myTree, node);
}
}
private JScrollPane initTreeScrollPane() {
fillTreeData(null, true);
final MyTreeCellRenderer renderer = new MyTreeCellRenderer();
myTree = new Tree(myRoot) {
public Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size = new Dimension(size.width + 10, size.height);
return size;
}
protected void processMouseEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
int row = myTree.getRowForLocation(e.getX(), e.getY());
if (row >= 0) {
Rectangle rowBounds = myTree.getRowBounds(row);
renderer.setBounds(rowBounds);
Rectangle checkBounds = renderer.myCheckbox.getBounds();
checkBounds.setLocation(rowBounds.getLocation());
if (checkBounds.contains(e.getPoint())) {
MyTreeNode node = (MyTreeNode)myTree.getPathForRow(row).getLastPathComponent();
toggleNode(node);
myTree.setSelectionRow(row);
}
}
}
super.processMouseEvent(e);
}
public int getToggleClickCount() {
return -1;
}
};
myTree.setCellRenderer(renderer);
myTree.setRootVisible(true);
myTree.setShowsRootHandles(true);
UIUtil.setLineStyleAngled(myTree);
TreeToolTipHandler.install(myTree);
TreeUtil.installActions(myTree);
myTree.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (!e.isConsumed() && e.getKeyCode() == KeyEvent.VK_SPACE && !SpeedSearchBase.hasActiveSpeedSearch(myTree)) {
final int selectionRow = myTree.getLeadSelectionRow();
final int[] rows = myTree.getSelectionRows();
for (int i = 0; rows != null && i < rows.length; i++) {
final TreePath path = myTree.getPathForRow(rows[i]);
final MyTreeNode node = (MyTreeNode)path.getLastPathComponent();
if (Arrays.binarySearch(rows, myTree.getRowForPath(path.getParentPath())) < 0) {
toggleNode(node);
}
}
myTree.setSelectionRow(selectionRow);
e.consume();
}
}
});
myTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
if (myTree.getSelectionPaths() != null && myTree.getSelectionPaths().length == 1) {
updateOptionsAndDescriptionPanel(myTree.getSelectionPaths()[0]);
}
else {
initOptionsAndDescriptionPanel();
}
}
});
myTree.addMouseListener(new PopupHandler() {
public void invokePopup(Component comp, int x, int y) {
if (myTree.getPathForLocation(x, y) != null && Arrays.binarySearch(myTree.getSelectionRows(), myTree.getRowForLocation(x, y)) > -1)
{
compoundPopup().show(comp, x, y);
}
}
});
new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
public String convert(TreePath o) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)o.getLastPathComponent();
final Object userObject = node.getUserObject();
if (userObject instanceof Descriptor) {
return getDisplayTextToSort(((Descriptor)userObject).getText());
}
return getDisplayTextToSort(userObject.toString());
}
});
myTree.setSelectionModel(new DefaultTreeSelectionModel());
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
TreeUtil.collapseAll(myTree, 1);
final Dimension preferredSize = new Dimension(myTree.getPreferredSize().width + 20, scrollPane.getPreferredSize().height);
scrollPane.setPreferredSize(preferredSize);
scrollPane.setMinimumSize(preferredSize);
myTree.addTreeExpansionListener(new TreeExpansionListener() {
private String getExpandedString(TreePath treePath) {
final Object userObject = ((DefaultMutableTreeNode)treePath.getLastPathComponent()).getUserObject();
if (userObject instanceof Descriptor) {
return ((Descriptor)userObject).getText();
}
else {
return (String)userObject;
}
}
public void treeCollapsed(TreeExpansionEvent event) {
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().collapseNode(getExpandedString(event.getPath()));
}
public void treeExpanded(TreeExpansionEvent event) {
((InspectionProfileImpl)mySelectedProfile).getExpandedNodes().expandNode(getExpandedString(event.getPath()));
}
});
myTreeExpander = new DefaultTreeExpander(myTree);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myTree.requestFocus();
}
});
myProfileFilter = new MyFilterComponent();
return scrollPane;
}
private JPopupMenu compoundPopup() {
final JPopupMenu popup = new JPopupMenu(InspectionsBundle.message("inspection.error.level.popup.menu.title"));
final SeverityRegistrar severityRegistrar = ((SeverityProvider)mySelectedProfile.getProfileManager()).getOwnSeverityRegistrar();
TreeSet<HighlightSeverity> severities = new TreeSet<HighlightSeverity>(severityRegistrar);
severities.add(HighlightSeverity.ERROR);
severities.add(HighlightSeverity.WARNING);
severities.add(HighlightSeverity.INFO);
final Collection<SeverityRegistrar.SeverityBasedTextAttributes> infoTypes =
severityRegistrar.getRegisteredHighlightingInfoTypes();
for (SeverityRegistrar.SeverityBasedTextAttributes info : infoTypes) {
severities.add(info.getSeverity());
}
for (HighlightSeverity severity : severities) {
final HighlightDisplayLevel level = HighlightDisplayLevel.find(severity);
final JMenuItem item = new JMenuItem(renderSeverity(level.getSeverity()));
item.setIcon(level.getIcon()); //todo correct position
item.addActionListener(new LevelSelection(level));
popup.add(item);
}
return popup;
}
private static String renderSeverity(HighlightSeverity severity) {
return InspectionsBundle.message("inspection.as", severity.toString().toLowerCase());
}
private void toggleNode(MyTreeNode node) {
List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myTree);
node.isEnabled = !node.isEnabled;
Object userObject = node.getUserObject();
final MyTreeNode parent = (MyTreeNode)node.getParent();
if (userObject instanceof Descriptor) {
toggleToolNode(node);
}
else {
final Enumeration children = node.children();
node.isProperSetting = false;
while (children.hasMoreElements()) {
MyTreeNode child = (MyTreeNode)children.nextElement();
child.isEnabled = node.isEnabled;
child.isProperSetting = false;
if (child.getUserObject()instanceof Descriptor) {
toggleToolNode(child);
}
else {
final Enumeration descriptorNodes = child.children();
while (descriptorNodes.hasMoreElements()) {
MyTreeNode descriptorNode = (MyTreeNode)descriptorNodes.nextElement();
descriptorNode.isEnabled = child.isEnabled;
if (descriptorNode.getUserObject()instanceof Descriptor) {
toggleToolNode(descriptorNode);
}
child.isProperSetting |= descriptorNode.isProperSetting;
}
}
node.isProperSetting |= child.isProperSetting;
}
}
updateUpHierarchy(node, parent);
((DefaultTreeModel)myTree.getModel()).reload();
updateOptionsAndDescriptionPanel(new TreePath(node.getPath()));
TreeUtil.restoreExpandedPaths(myTree, expandedPaths);
}
private void toggleToolNode(final MyTreeNode toolNode) {
final Descriptor descriptor = (Descriptor)toolNode.getUserObject();
final HighlightDisplayKey key = descriptor.getKey();
final String toolShortName = key.toString();
if (toolNode.isEnabled) {
mySelectedProfile.enableTool(toolShortName);
}
else {
mySelectedProfile.disableTool(toolShortName);
}
toolNode.isProperSetting = mySelectedProfile.isProperSetting(key);
}
private void updateUpHierarchy(final MyTreeNode node, final MyTreeNode parent) {
if (parent != null) {
if (node.isProperSetting) {
parent.isProperSetting = true;
myRoot.isProperSetting = true;
}
else {
parent.isProperSetting = wasModified(parent);
myRoot.isProperSetting = parent.isProperSetting || wasModified(myRoot);
}
}
}
private static boolean wasModified(MyTreeNode node) {
for (int i = 0; i < node.getChildCount(); i++) {
final MyTreeNode childNode = (MyTreeNode)node.getChildAt(i);
if (childNode.isProperSetting) {
return true;
}
}
return false;
}
private static boolean isDescriptorAccepted(Descriptor descriptor,
@NonNls String filter,
final boolean forceInclude,
final List<Set<String>> keySetList) {
filter = filter.toLowerCase();
if (descriptor.getText().toLowerCase().contains(filter)) {
return true;
}
if (descriptor.getGroup().toLowerCase().contains(filter)) {
return true;
}
for (Set<String> keySet : keySetList) {
if (keySet.contains(descriptor.getKey().toString())) {
if (!forceInclude) {
return true;
}
}
else {
if (forceInclude) {
return false;
}
}
}
return forceInclude;
}
private void fillTreeData(String filter, boolean forceInclude) {
if (mySelectedProfile == null) return;
myRoot.removeAllChildren();
myRoot.isEnabled = false;
myRoot.isProperSetting = false;
List<Set<String>> keySetList = new ArrayList<Set<String>>();
if (filter != null && filter.length() > 0) {
final SearchableOptionsRegistrar optionsRegistrar = SearchableOptionsRegistrar.getInstance();
final Set<String> words = optionsRegistrar.getProcessedWords(filter);
for (String word : words) {
final Set<OptionDescription> descriptions = ((SearchableOptionsRegistrarImpl)optionsRegistrar).getAcceptableDescriptions(word);
Set<String> keySet = new HashSet<String>();
if (descriptions != null) {
for (OptionDescription description : descriptions) {
keySet.add(description.getPath());
}
}
keySetList.add(keySet);
}
}
for (Descriptor descriptor : myDescriptors) {
if (descriptor.getTool() != null && !(descriptor.getTool()instanceof LocalInspectionToolWrapper) && !myShowInspections) continue;
if (filter != null && filter.length() > 0 && !isDescriptorAccepted(descriptor, filter, forceInclude, keySetList)) {
continue;
}
final HighlightDisplayKey key = descriptor.getKey();
final boolean enabled = mySelectedProfile.isToolEnabled(key);
final boolean properSetting = mySelectedProfile.isProperSetting(key);
final MyTreeNode node = new MyTreeNode(descriptor, enabled, properSetting);
final MyTreeNode groupNode = getGroupNode(myRoot, descriptor.getGroup());
groupNode.add(node);
groupNode.isEnabled |= enabled;
groupNode.isProperSetting |= properSetting;
myRoot.isEnabled |= enabled;
myRoot.isProperSetting |= properSetting;
}
if (filter != null && forceInclude && myRoot.getChildCount() == 0) {
final Set<String> filters = SearchableOptionsRegistrar.getInstance().getProcessedWords(filter);
if (filters.size() > 1) {
fillTreeData(filter, false);
}
}
sortInspections();
}
private void sortInspections() {
Comparator<MyTreeNode> comparator = new Comparator<MyTreeNode>() {
public int compare(MyTreeNode o1, MyTreeNode o2) {
String s1 = null;
String s2 = null;
Object userObject1 = o1.getUserObject();
Object userObject2 = o2.getUserObject();
if (userObject1 instanceof String && userObject2 instanceof String) {
s1 = (String)userObject1;
s2 = (String)userObject2;
}
if (userObject1 instanceof Descriptor && userObject2 instanceof Descriptor) {
s1 = ((Descriptor)userObject1).getText();
s2 = ((Descriptor)userObject2).getText();
}
if (s1 != null && s2 != null) {
return getDisplayTextToSort(s1).compareToIgnoreCase(getDisplayTextToSort(s2));
}
//can't be
return -1;
}
};
TreeUtil.sort(myRoot, comparator);
}
public static String getDisplayTextToSort(String s) {
if (s.length() == 0) {
return s;
}
while (!Character.isLetterOrDigit(s.charAt(0))) {
s = s.substring(1);
if (s.length() == 0) {
return s;
}
}
return s;
}
private void updateOptionsAndDescriptionPanel(TreePath path) {
if (path == null) return;
final MyTreeNode node = (MyTreeNode)path.getLastPathComponent();
final Object userObject = node.getUserObject();
if (userObject instanceof Descriptor) {
final Descriptor descriptor = (Descriptor)userObject;
if (descriptor.getDescriptorFileName() != null) {
// need this in order to correctly load plugin-supplied descriptions
final InspectionProfileEntry tool = descriptor.getTool();
try {
URL descriptionUrl = InspectionToolRegistrar.getDescriptionUrl(tool);
if (descriptionUrl == null) throw new IOException();
myBrowser.read(new StringReader(SearchUtil.markup(ResourceUtil.loadText(descriptionUrl), myProfileFilter.getFilter())), null);
}
catch (IOException e2) {
try {
//noinspection HardCodedStringLiteral
myBrowser.read(new StringReader("<html><body><b>" + UNDER_CONSTRUCTION + "</b></body></html>"), null);
}
catch (IOException e1) {
//Can't be
}
}
}
else {
try {
myBrowser.read(new StringReader(EMPTY_HTML), null);
}
catch (IOException e1) {
//Can't be
}
}
final LevelChooser chooser = new LevelChooser(((SeverityProvider)mySelectedProfile.getProfileManager()).getOwnSeverityRegistrar());
chooser.getComboBox().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean toUpdate = mySelectedProfile.getErrorLevel(descriptor.getKey()) != chooser.getLevel();
mySelectedProfile.setErrorLevel(descriptor.getKey(), chooser.getLevel());
if (toUpdate) node.isProperSetting = mySelectedProfile.isProperSetting(descriptor.getKey());
}
});
chooser.setLevel(mySelectedProfile.getErrorLevel(descriptor.getKey()));
final JPanel withSeverity = new JPanel(new GridBagLayout());
withSeverity.add(new JLabel(InspectionsBundle.message("inspection.severity")), new GridBagConstraints(0, 0, 1, 1, 0, 0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 5, 5, 10), 0, 0));
Dimension dimension = new Dimension(150, chooser.getPreferredSize().height);
chooser.setPreferredSize(dimension);
chooser.setMinimumSize(dimension);
withSeverity.add(chooser, new GridBagConstraints(1, 0, 1, 1, 1.0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 5, 0), 0, 0));
final JComponent config = descriptor.getAdditionalConfigPanel(mySelectedProfile);
if (config != null) {
withSeverity.add(config, new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
else {
withSeverity.add(new JPanel(), new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
myOptionsPanel.removeAll();
myOptionsPanel.add(withSeverity);
myOptionsPanel.validate();
GuiUtils.enableChildren(myOptionsPanel, node.isEnabled);
}
else {
initOptionsAndDescriptionPanel();
}
}
private void initOptionsAndDescriptionPanel() {
myOptionsPanel.removeAll();
myOptionsPanel.add(new JPanel());
try {
myBrowser.read(new StringReader(EMPTY_HTML), null);
}
catch (IOException e1) {
//Can't be
}
myOptionsPanel.validate();
}
private static MyTreeNode getGroupNode(MyTreeNode root, String group) {
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
MyTreeNode child = (MyTreeNode)root.getChildAt(i);
if (group.equals(child.getUserObject())) return child;
}
MyTreeNode child = new MyTreeNode(group, false, false);
root.add(child);
return child;
}
public boolean setSelectedProfileModified(boolean modified) {
mySelectedProfile.setModified(modified);
return modified;
}
private ModifiableModel getSelectedProfile() {
return mySelectedProfile;
}
public void setFilter(final String filter) {
myProfileFilter.setFilter(filter);
}
public boolean isResetEnabled() {
return myRoot.isProperSetting;
}
private void setSelectedProfile(final ModifiableModel modifiableModel) {
mySelectedProfile = modifiableModel;
myInitialProfile = mySelectedProfile.getName();
initDescriptors();
filterTree(myProfileFilter != null ? myProfileFilter.getFilter() : null);
}
@Nullable
private String getHint(Descriptor descriptor) {
if (!myShowInspections) return null;
if (descriptor.getTool() == null) {
return InspectionsBundle.message("inspection.tool.availability.in.tree.node");
}
if (descriptor.getTool()instanceof LocalInspectionToolWrapper) {
return null;
}
return InspectionsBundle.message("inspection.tool.availability.in.tree.node1");
}
public Dimension getPreferredSize() {
return new Dimension(700, -1);
}
public void disposeUI() {
if (mySelectedProfile != null && getSavedProfile() != null) {
ModifiableModel profile = mySelectedProfile.getParentProfile().getModifiableModel();
((InspectionProfileImpl)profile).getExpandedNodes().saveVisibleState(myTree);
try {
profile.save();
}
catch (IOException e) {
LOG.error(e);
}
profile.getProfileManager().updateProfile(profile);
}
myAlarm.cancelAllRequests();
myProfileFilter.dispose();
mySelectedProfile = null;
}
private InspectionProfile getSavedProfile() {
return (InspectionProfile)mySelectedProfile.getProfileManager().getProfiles().get(mySelectedProfile.getName());
}
private JPanel createInspectionProfileSettingsPanel() {
myBrowser = new JEditorPane(UIUtil.HTML_MIME, EMPTY_HTML);
myBrowser.setEditable(false);
initDescriptors();
fillTreeData(myProfileFilter != null ? myProfileFilter.getFilter() : null, true);
JPanel descriptionPanel = new JPanel();
descriptionPanel.setBorder(IdeBorderFactory.createTitledBorder(InspectionsBundle.message("inspection.description.title")));
descriptionPanel.setLayout(new BorderLayout());
descriptionPanel.add(ScrollPaneFactory.createScrollPane(myBrowser), BorderLayout.CENTER);
JPanel rightPanel = new JPanel(new GridLayout(2, 1, 0, 5));
rightPanel.add(descriptionPanel);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.setBorder(IdeBorderFactory.createTitledBorder(InspectionsBundle.message("inspection.export.options.panel.title")));
myOptionsPanel = panel1;
initOptionsAndDescriptionPanel();
rightPanel.add(myOptionsPanel);
final JPanel treePanel = new JPanel(new BorderLayout());
treePanel.add(initTreeScrollPane(), BorderLayout.CENTER);
final JPanel northPanel = new JPanel(new BorderLayout());
northPanel.setBorder(IdeBorderFactory.createEmptyBorder(2, 0, 2, 0));
northPanel.add(createTreeToolbarPanel().getComponent(), BorderLayout.WEST);
northPanel.add(myProfileFilter, BorderLayout.EAST);
treePanel.add(northPanel, BorderLayout.NORTH);
Splitter splitter = new Splitter(false);
splitter.setShowDividerControls(false);
splitter.setFirstComponent(treePanel);
splitter.setSecondComponent(rightPanel);
splitter.setProportion((float)treePanel.getPreferredSize().width/getPreferredSize().width);
splitter.setHonorComponentsMinimumSize(true);
myInspectionProfilePanel.add(splitter, BorderLayout.CENTER);
myInspectionProfilePanel.setBorder(IdeBorderFactory.createEmptyBorder(2, 2, 0, 2));
return myInspectionProfilePanel;
}
public boolean isModified() {
if (myModified) return true;
if (mySelectedProfile.isChanged()) return true;
if (!Comparing.strEqual(myInitialProfile, mySelectedProfile.getName())) return true;
for (Descriptor descriptor : myDescriptors) {
if (mySelectedProfile.isToolEnabled(descriptor.getKey()) != descriptor.isEnabled()) {
return setSelectedProfileModified(true);
}
if (mySelectedProfile.getErrorLevel(descriptor.getKey()) != descriptor.getLevel()) {
return setSelectedProfileModified(true);
}
}
setSelectedProfileModified(false);
return false;
}
public void reset() {
myModified = false;
setSelectedProfile(mySelectedProfile);
final String filter = myProfileFilter.getFilter();
myProfileFilter.reset();
myProfileFilter.setSelectedItem(filter);
}
public void apply() throws ConfigurationException {
final ModifiableModel selectedProfile = getSelectedProfile();
final InspectionProfile parentProfile = selectedProfile.getParentProfile();
try {
selectedProfile.commit();
}
catch (IOException e) {
throw new ConfigurationException(e.getMessage());
}
setSelectedProfile(parentProfile.getModifiableModel());
setSelectedProfileModified(false);
myModified = false;
}
private static class InputDialog extends DialogWrapper {
private JCheckBox myCheckBox;
private JPanel myPanel;
private JTextField myTextField;
protected InputDialog(boolean showCheckBox, String initial, String checkBoxLabel, Project project) {
super(project, true);
myCheckBox.setVisible(showCheckBox);
myCheckBox.setText(checkBoxLabel);
myTextField.setText(initial);
setTitle(InspectionsBundle.message("inspection.new.profile.dialog.title"));
init();
}
@Nullable
protected JComponent createCenterPanel() {
return myPanel;
}
public boolean isChecked() {
return myCheckBox.isSelected();
}
public String getName() {
return myTextField.getText();
}
public JComponent getPreferredFocusedComponent() {
return myTextField;
}
}
public static class MyTreeNode extends DefaultMutableTreeNode {
public boolean isEnabled;
public boolean isProperSetting;
public MyTreeNode(Object userObject, boolean enabled, boolean properSetting) {
super(userObject);
isEnabled = enabled;
isProperSetting = properSetting;
}
public boolean equals(Object obj) {
if (!(obj instanceof MyTreeNode)) return false;
MyTreeNode node = (MyTreeNode)obj;
return isEnabled == node.isEnabled &&
(getUserObject() != null ? node.getUserObject().equals(getUserObject()) : node.getUserObject() == null);
}
public int hashCode() {
return getUserObject() != null ? getUserObject().hashCode() : 0;
}
}
public static class LevelChooser extends ComboboxWithBrowseButton {
private final MyRenderer ourRenderer = new MyRenderer();
public LevelChooser(final SeverityRegistrar severityRegistrar) {
final JComboBox comboBox = getComboBox();
final DefaultComboBoxModel model = new DefaultComboBoxModel();
comboBox.setModel(model);
fillModel(model, severityRegistrar);
comboBox.setRenderer(ourRenderer);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final SeverityEditorDialog dlg = new SeverityEditorDialog(LevelChooser.this, (HighlightSeverity)getComboBox().getSelectedItem(), severityRegistrar);
dlg.show();
if (dlg.isOK()) {
fillModel(model, severityRegistrar);
final HighlightInfoType type = dlg.getSelectedType();
if (type != null) {
getComboBox().setSelectedItem(type.getSeverity(null));
}
}
}
});
}
private static void fillModel(DefaultComboBoxModel model, final SeverityRegistrar severityRegistrar) {
model.removeAllElements();
final TreeSet<HighlightSeverity> severities = new TreeSet<HighlightSeverity>(severityRegistrar);
for (SeverityRegistrar.SeverityBasedTextAttributes type : severityRegistrar.getRegisteredHighlightingInfoTypes()) {
severities.add(type.getSeverity());
}
severities.add(HighlightSeverity.ERROR);
severities.add(HighlightSeverity.WARNING);
severities.add(HighlightSeverity.INFO);
severities.add(HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING);
for (HighlightSeverity severity : severities) {
model.addElement(severity);
}
}
public HighlightDisplayLevel getLevel() {
HighlightSeverity severity = (HighlightSeverity)getComboBox().getSelectedItem();
if (severity == null) return HighlightDisplayLevel.WARNING;
return HighlightDisplayLevel.find(severity);
}
public void setLevel(HighlightDisplayLevel level) {
getComboBox().setSelectedItem(level.getSeverity());
}
private static class MyRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof HighlightSeverity) {
HighlightSeverity severity = (HighlightSeverity)value;
setText(renderSeverity(severity));
setIcon(HighlightDisplayLevel.find(severity).getIcon());
}
return this;
}
}
}
private class LevelSelection implements ActionListener {
private final HighlightDisplayLevel myLevel;
public LevelSelection(HighlightDisplayLevel level) {
myLevel = level;
}
public void actionPerformed(ActionEvent e) {
final int[] rows = myTree.getSelectionRows();
final boolean showOptionsAndDescriptorPanels = rows != null && rows.length == 1;
for (int i = 0; rows != null && i < rows.length; i++) {
final MyTreeNode node = (MyTreeNode)myTree.getPathForRow(rows[i]).getLastPathComponent();
final MyTreeNode parent = (MyTreeNode)node.getParent();
if (node.getUserObject()instanceof Descriptor) {
updateErrorLevel(node, showOptionsAndDescriptorPanels);
updateUpHierarchy(node, parent);
}
else {
node.isProperSetting = false;
for (int j = 0; j < node.getChildCount(); j++) {
final MyTreeNode child = (MyTreeNode)node.getChildAt(j);
if (child.getUserObject()instanceof Descriptor) { //group node
updateErrorLevel(child, showOptionsAndDescriptorPanels);
}
else { //root node
child.isProperSetting = false;
for (int k = 0; k < child.getChildCount(); k++) {
final MyTreeNode descriptorNode = (MyTreeNode)child.getChildAt(k);
if (descriptorNode.getUserObject()instanceof Descriptor) {
updateErrorLevel(descriptorNode, showOptionsAndDescriptorPanels);
}
child.isProperSetting |= descriptorNode.isProperSetting;
}
}
node.isProperSetting |= child.isProperSetting;
}
updateUpHierarchy(node, parent);
}
}
if (rows != null && rows.length == 1) {
updateOptionsAndDescriptionPanel(myTree.getPathForRow(rows[0]));
}
else {
initOptionsAndDescriptionPanel();
}
repaintTableData();
}
private void updateErrorLevel(final MyTreeNode child, final boolean showOptionsAndDescriptorPanels) {
final HighlightDisplayKey key = ((Descriptor)child.getUserObject()).getKey();
mySelectedProfile.setErrorLevel(key, myLevel);
child.isProperSetting = mySelectedProfile.isProperSetting(key);
if (showOptionsAndDescriptorPanels) {
updateOptionsAndDescriptionPanel(new TreePath(child.getPath()));
}
}
}
private class MyTreeCellRenderer extends JPanel implements TreeCellRenderer {
private final ColoredTreeCellRenderer myTextRenderer;
public final JCheckBox myCheckbox;
public MyTreeCellRenderer() {
super(new BorderLayout());
myCheckbox = new JCheckBox();
myTextRenderer = new ColoredTreeCellRenderer() {
public void customizeCellRenderer(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
}
};
myTextRenderer.setOpaque(true);
add(myCheckbox, BorderLayout.WEST);
add(myTextRenderer, BorderLayout.CENTER);
}
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
invalidate();
MyTreeNode node = (MyTreeNode)value;
Object object = node.getUserObject();
setOpaque(true);
final Color background = selected ? UIUtil.getTreeSelectionBackground() : UIUtil.getTreeTextBackground();
setBackground(background);
myCheckbox.setSelected(node.isEnabled);
myCheckbox.setOpaque(true);
myCheckbox.setBackground(background);
@NonNls String text = null;
int style = Font.PLAIN;
String hint = null;
if (object instanceof String) {
text = (String)object;
style = Font.BOLD;
}
else if (object instanceof Descriptor) {
final Descriptor descriptor = (Descriptor)object;
text = descriptor.getText();
hint = getHint(descriptor);
}
Color foreground =
selected ? UIUtil.getTreeSelectionForeground() : node.isProperSetting ? Color.BLUE : UIUtil.getTreeTextForeground();
myTextRenderer.clear();
if (text != null) {
SearchUtil.appendFragments(myProfileFilter != null ? myProfileFilter.getFilter() : null, text, style, foreground, background,
myTextRenderer);
}
if (hint != null) {
myTextRenderer
.append(" " + hint, selected ? new SimpleTextAttributes(Font.PLAIN, foreground) : SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
setForeground(foreground);
myCheckbox.setForeground(foreground);
myTextRenderer.setForeground(foreground);
return this;
}
}
private class MyFilterComponent extends FilterComponent {
private final TreeExpansionMonitor<DefaultMutableTreeNode> myExpansionMonitor = TreeExpansionMonitor.install(myTree);
public MyFilterComponent() {
super(INSPECTION_FILTER_HISTORY, 10);
}
public void filter() {
final String filter = getFilter();
if (filter != null && filter.length() > 0) {
if (!myExpansionMonitor.isFreeze()) {
myExpansionMonitor.freeze();
}
}
filterTree(getFilter());
TreeUtil.expandAll(myTree);
if (filter == null || filter.length() == 0) {
TreeUtil.collapseAll(myTree, 0);
myExpansionMonitor.restore();
}
}
protected void onlineFilter() {
if (mySelectedProfile == null) return;
final String filter = getFilter();
if (filter != null && filter.length() > 0) {
if (!myExpansionMonitor.isFreeze()) {
myExpansionMonitor.freeze();
}
}
fillTreeData(filter, true);
((DefaultTreeModel)myTree.getModel()).reload();
TreeUtil.expandAll(myTree);
if (filter == null || filter.length() == 0) {
TreeUtil.collapseAll(myTree, 0);
myExpansionMonitor.restore();
}
}
}
}
|
package com.ecyrd.jspwiki.plugin;
import org.apache.oro.text.*;
import org.apache.oro.text.regex.*;
import org.apache.log4j.Category;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;
import java.util.Map;
import java.util.HashMap;
import com.ecyrd.jspwiki.WikiContext;
/**
* Manages plugin classes.
*
* @author Janne Jalkanen
* @since 1.6.1
*/
public class PluginManager
{
private static Category log = Category.getInstance( PluginManager.class );
public PluginManager()
{
}
/**
* Returns true if the link is really command to insert
* a plugin.
*/
public static boolean isPluginLink( String link )
{
return link.startsWith("{INSERT");
}
/**
* Executes a plugin class in the given context.
*/
private String execute( WikiContext context,
String classname,
Map params )
throws PluginException
{
try
{
ClassLoader loader = getClass().getClassLoader();
WikiPlugin plugin = (WikiPlugin)loader.loadClass( classname ).newInstance();
return plugin.execute( context, params );
}
catch( InstantiationException e )
{
throw new PluginException( "Cannot instantiate plugin "+classname, e );
}
catch( ClassNotFoundException e )
{
throw new PluginException( "Could not find plugin "+classname, e );
}
catch( IllegalAccessException e )
{
throw new PluginException( "Not allowed to access plugin "+classname, e );
}
catch( ClassCastException e )
{
throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e );
}
}
/**
* Parses a plugin. Plugin commands are of the form:
* [{INSERT myplugin WHERE param1=value1, param2=value2}]
* myplugin may either be a class name or a plugin alias.
*/
public String execute( WikiContext context,
String commandline )
throws PluginException
{
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
try
{
Pattern ptrn = compiler.compile( "\\{?INSERT\\s*([\\w\\._]+)\\s*(WHERE)?\\s*([^\\}]*)\\}?$" );
if( matcher.contains( commandline, ptrn ) )
{
MatchResult res = matcher.getMatch();
String plugin = res.group(1);
String args = res.group(3);
HashMap arglist = new HashMap();
// I am too tired to think of a proper regexp.
StringTokenizer tok = new StringTokenizer( args, " ,=" );
while( tok.hasMoreTokens() )
{
String param = tok.nextToken();
String value = tok.nextToken();
arglist.put( param, value );
}
return execute( context, plugin, arglist );
}
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: someone messed with pluginmanager patterns.", e );
throw new PluginException( "PluginManager patterns are broken", e );
}
catch( NoSuchElementException e )
{
String msg = "Missing parameter in plugin definition: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
// FIXME: We could either return an empty string "", or
// the original line. If we want unsuccessful requests
// to be invisible, then we should return an empty string.
return commandline;
}
}
|
package net.java.sip.communicator.impl.gui;
import java.util.Hashtable;
import net.java.sip.communicator.impl.gui.main.CommunicatorMain;
import net.java.sip.communicator.service.configuration.ConfigurationService;
import net.java.sip.communicator.service.contactlist.MetaContact;
import net.java.sip.communicator.service.contactlist.MetaContactGroup;
import net.java.sip.communicator.service.contactlist.MetaContactListException;
import net.java.sip.communicator.service.contactlist.MetaContactListService;
import net.java.sip.communicator.service.contactlist.event.MetaContactListListener;
import net.java.sip.communicator.service.gui.UIService;
import net.java.sip.communicator.service.protocol.AccountID;
import net.java.sip.communicator.service.protocol.AccountManager;
import net.java.sip.communicator.service.protocol.AccountProperties;
import net.java.sip.communicator.service.protocol.Contact;
import net.java.sip.communicator.service.protocol.ProtocolNames;
import net.java.sip.communicator.service.protocol.ProtocolProviderService;
import net.java.sip.communicator.slick.protocol.icq.IcqSlickFixture;
import net.java.sip.communicator.util.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
public class Activator implements BundleActivator
{
private Logger logger = Logger.getLogger(Activator.class.getName());
private UIService uiService = null;
private AccountManager icqAccountManager = null;
private CommunicatorMain communicatorMain = new CommunicatorMain();
private AccountID icqAccountID;
public void start(BundleContext bundleContext) throws Exception
{
try
{
logger.logEntry();
//Create the ui service
this.uiService =
new UIServiceImpl();
ServiceReference clistReference
= bundleContext.getServiceReference(MetaContactListService.class.getName());
//MetaContactListService contactListService
//= (MetaContactListService)bundleContext.getService(clistReference);
MetaContactListService contactListService = new MetaContactListServiceImpl();
ServiceReference[] serRefs = null;
String osgiFilter = "(" + AccountManager.PROTOCOL_PROPERTY_NAME
+ "="+ProtocolNames.ICQ+")";
serRefs = bundleContext.getServiceReferences(
AccountManager.class.getName(), osgiFilter);
icqAccountManager = (AccountManager)bundleContext.getService(serRefs[0]);
Hashtable icqAccountProperties = new Hashtable();
icqAccountProperties.put(AccountProperties.PASSWORD, "parolata");
icqAccountID = icqAccountManager.installAccount(
bundleContext, "85450845", icqAccountProperties);
osgiFilter =
"(&("+AccountManager.PROTOCOL_PROPERTY_NAME +"="+ProtocolNames.ICQ+")"
+"(" + AccountManager.ACCOUNT_ID_PROPERTY_NAME
+ "=" + icqAccountID.getAccountID() + "))";
serRefs = bundleContext.getServiceReferences(
ProtocolProviderService.class.getName(),
osgiFilter);
Object icqProtocolProvider
= bundleContext.getService(serRefs[0]);
logger.info("UI Service...[ STARTED ]");
bundleContext.registerService(
UIService.class.getName(), this.uiService, null);
logger.info("UI Service ...[REGISTERED]");
communicatorMain.setContactList(contactListService);
communicatorMain.show();
}
finally
{
logger.logExit();
}
}
public void stop(BundleContext bundleContext) throws Exception
{
logger.info("UI Service ...[STOPED]");
}
private class MetaContactListServiceImpl
implements MetaContactListService {
public MetaContactGroup getRoot() {
// TODO Auto-generated method stub
return null;
}
public MetaContact findMetaContactByContact(Contact contact) {
// TODO Auto-generated method stub
return null;
}
public MetaContact findMetaContactByID(String metaContactID) {
// TODO Auto-generated method stub
return null;
}
public void addContactListListener(MetaContactListListener l) {
// TODO Auto-generated method stub
}
public void removeContactListListener(MetaContactListListener l) {
// TODO Auto-generated method stub
}
public void moveContact(Contact contact, MetaContact newParent) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void removeContact(Contact contact) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void addNewContactToMetaContact(ProtocolProviderService provider, MetaContact metaContact, String contactID) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void createMetaContact(ProtocolProviderService provider, MetaContactGroup contactGroup, String contactID) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void moveMetaContact(MetaContact metaContact, MetaContactGroup newGroup) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void removeMetaContact(MetaContact metaContact) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void createMetaContactGroup(String groupName) throws MetaContactListException {
// TODO Auto-generated method stub
}
public void removeMetaContactGroup(MetaContactGroup groupToRemove) throws MetaContactListException {
// TODO Auto-generated method stub
}
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Solution {
public static boolean aboveAverageSpeed(long speedLimit, long distance, long delay) {
double speedLimitInKmPerSecond = speedLimit / 3600.0;
double average = (double) distance / (double) delay;
System.err.println("Computed average speed : " + Double.toString(average) + " versus speed limit in km/s : " + Double.toString(speedLimitInKmPerSecond));
return average > speedLimitInKmPerSecond;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int maxAuthorizedSpeed = in.nextInt();
System.err.println("Speed Limit : " + maxAuthorizedSpeed);
int N = in.nextInt();
if (in.hasNextLine()) {
in.nextLine();
}
String[] rows = new String[N];
String licencePlate = null;
String[] elements = null;
String currentLicencePlate = null;
Long currentDistance = null;
Long currentTimestamp = null;
List<Result> results = new ArrayList<>();
for (int i = 0; i < N; i++) {
rows[i] = in.nextLine();
elements = rows[i].split(" ");
if (currentLicencePlate != null && currentLicencePlate.equals(elements[0])) {
Long newDistance = Long.parseLong(elements[1]);
Long newTimestamp = Long.parseLong(elements[2]);
if (aboveAverageSpeed(maxAuthorizedSpeed, newDistance - currentDistance, newTimestamp - currentTimestamp)) {
results.add(new Result(newDistance, currentLicencePlate));
}
currentDistance = newDistance;
currentTimestamp = newTimestamp;
} else {
currentLicencePlate = elements[0];
currentDistance = Long.parseLong(elements[1]);
currentTimestamp = Long.parseLong(elements[2]);
System.err.println("New Licence plate " + currentLicencePlate);
}
System.err.println(rows[i]);
}
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
if (results.isEmpty()) {
System.out.println("OK");
} else {
for (Result result : results) {
System.out.println(result.toString());
}
}
}
}
class Result {
private final long distance;
private final String licencePlate;
public Result(long distance, String licencePlate) {
this.distance = distance;
this.licencePlate = licencePlate;
}
public long getDistance() {
return this.distance;
}
public String getLicencePlate() {
return licencePlate;
}
public String toString() {
return licencePlate + " " + Long.toString(this.distance);
}
}
|
package net.mchs_u.mc.aiwolf.nlp.agito;
import java.util.List;
import org.aiwolf.common.data.Agent;
import org.aiwolf.common.data.Player;
import org.aiwolf.common.data.Talk;
import org.aiwolf.common.net.GameInfo;
import org.aiwolf.common.net.GameSetting;
import net.mchs_u.mc.aiwolf.nlp.common.GameInfoTranslater;
public class McreNlpPlayer implements Player {
private Player player = null;
private GameInfo gameInfo = null;
private Mouth mouth;
private Ear ear;
private int printHead; // print
public McreNlpPlayer() {
player = new net.mchs_u.mc.aiwolf.curry.McrePlayer();
mouth = new Mouth();
ear = new Ear();
}
public void update(GameInfo gameInfo) {
GameInfo prGameInfo = new GameInfoTranslater(gameInfo, ear);
player.update(prGameInfo);
List<Talk> talkList = gameInfo.getTalkList();
List<Talk> prTalkList = prGameInfo.getTalkList();
for(int i = printHead; i < talkList.size(); i++){
System.out.println("log : " + gameInfo.getAgent() + " " + getName() + "\t" + talkList.get(i) + " ( -> " + prTalkList.get(i).getText() + " ) ");
printHead++;
}
}
public String talk() {
String pr = player.talk();
String nl = mouth.toNaturalLanguageForTalk(gameInfo, pr);
System.out.println("talk: " + gameInfo.getAgent() + " " + getName() + "\t" + nl + " ( <- " + pr + " ) ");
return nl;
}
public String whisper() {
String pr = player.whisper();
String nl = mouth.toNaturalLanguageForWhisper(gameInfo, pr);
System.out.println("whis: " + gameInfo.getAgent() + " " + getName() + "\t" + nl + " ( <- " + pr + " ) ");
return nl;
}
public void initialize(GameInfo gameInfo, GameSetting gameSetting) {
this.gameInfo = gameInfo;
player.initialize(gameInfo, gameSetting);
}
public void dayStart() {
printHead = 0;
player.dayStart();
}
public Agent attack() {
return player.attack();
}
public Agent divine() {
return player.divine();
}
public void finish() {
ear.save();
player.finish();
}
public String getName() {
return player.getName();
}
public Agent guard() {
return player.guard();
}
public Agent vote() {
return player.vote();
}
}
|
package com.intellij.java.codeInsight;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import org.intellij.lang.regexp.inspection.AnonymousGroupInspection;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* @author Bas Leijdekkers
*/
public class RegExpHighlightingTest extends LightJavaCodeInsightFixtureTestCase {
public void testDuplicateNamedGroup() {
doTest("(?<name>abc)(?<<error descr=\"Group with name 'name' already defined\">name</error>>xyz)");
}
public void testAnonymousCapturingGroupInspection() {
myFixture.enableInspections(new AnonymousGroupInspection());
doTest("<warning descr=\"Anonymous capturing group\">(</warning>moo)<warning descr=\"Numeric back reference\">\\1</warning>");
}
public void testSingleRepetition() {
doTest("a<weak_warning descr=\"Single repetition\">{1}</weak_warning>");
}
public void testRedundantEscape1() {
doTest("\\;");
}
public void testBoundaries() {
doTest("\\b <error descr=\"This boundary is not supported in this regex dialect\">\\b{g}</error> \\B \\A \\z \\Z \\G");
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_9, myFixture.getModule(), myFixture.getTestRootDisposable());
doTest("\\b \\b{g} \\B \\A \\z \\Z \\G");
}
public void testSimplifiableRange1() {
doTest("a<weak_warning descr=\"Repetition range replaceable by '?'\">{0,1}</weak_warning>");
}
public void testSimplifiableRange2() {
doTest("a<weak_warning descr=\"Repetition range replaceable by '+'\">{1,}</weak_warning>");
}
public void testSimplifiableRange3() {
doTest("a<weak_warning descr=\"Repetition range replaceable by '*'\">{0,}</weak_warning>");
}
public void testFixedRepetitionRange() {
doTest("a<weak_warning descr=\"Fixed repetition range\">{3,3}</weak_warning>");
}
public void testDuplicateCharacterClass() {
doTest("[\\w-<warning descr=\"Duplicate predefined character class '\\w' inside character class\">\\w</warning>]");
}
public void testNoRange() {
doTest("[\\w-a]");
}
public void testUnicodeGrapheme() {
doTest("<error descr=\"Illegal/unsupported escape sequence\">\\X</error>");
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_9, myFixture.getModule(), myFixture.getTestRootDisposable());
doTest("\\X");
}
public void testRedundantEscape2() {
doTest("\\-[\\*\\-\\[\\]\\\\\\+]");
}
public void testBoundaryInsideCharacterClass() {
doTest("[<error descr=\"Illegal/unsupported escape sequence\">\\b</error>]");
}
public void testEmptyGroup1() {
doTest("<warning descr=\"Empty group\">()</warning>");
}
public void testEmptyGroup2() {
doTest("<warning descr=\"Empty group\">(|)</warning>");
}
public void testRedundantGroup() {
doTest("<warning descr=\"Redundant group nesting\">((a))</warning>");
}
public void testNamedGroup() {
doTest("(?<asdf>[a-c])\\1");
}
public void testNamedGroupReference() {
doTest("(?<asdf>;[a-c])\\k<asdf>");
}
public void testUnresolvedNamedGroupReference() {
doTest("\\k<<error descr=\"Unresolved named group reference\">adsf</error>>");
}
public void testInvalidGroupName() {
doTest("(?<<error descr=\"Invalid group name\">important_value1</error>>\\d\\d)");
}
public void testValidGroupName() {
doTest("(?<importantValue1>\\d\\d)");
}
public void testRedundantCharacterRange() {
doTest("[<warning descr=\"Redundant character range\">a-a</warning>]");
}
public void testIllegalCharacterRange1() {
doTest("[<error descr=\"Illegal character range (to < from)\">\\x4a-\\x3f</error>]");
}
public void testIllegalCharacterRange2() {
doTest("[<error descr=\"Illegal character range (to < from)\">\\udbff\\udfff-\\ud800\\udc00</error>]");
}
public void testIllegalCharacterRange3() {
doTest("[<error descr=\"Illegal character range (to < from)\">z-a</error>]");
}
public void testIllegalCharacterRange4() {
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_9, myFixture.getModule(), myFixture.getTestRootDisposable());
doTest("[<error descr=\"Illegal character range (to < from)\">\\N{LATIN SMALL LETTER Z}-\\N{LATIN SMALL LETTER A}</error>]");
}
public void testLegalCharacterRange() {
// Cyrillic Capital Letter Zemlya - Unicode Han Character 'to peel, pare' (Unicode Supplementary Character)
doTest("[\\x{A640}-\\x{20731}]");
}
public void testQuoted() {
doTest("[\\Qabc?*+.)<warning descr=\"Duplicate character ')' inside character class\">)</warning>]<warning descr=\"Duplicate character ']' inside character class\">]</warning>[<warning descr=\"Duplicate character ']' inside character class\">]</warning>\\E]");
}
public void testValidDanglingMetacharacters() {
doTest("]}");
}
public void testRedundantlyEscapedClosingBrace() {
doTest("\\]\\}");
}
public void testBadEscape1() {
doTest("<error descr=\"Illegal/unsupported escape sequence\">\\q</error>");
}
public void testBadEscape2() {
doTest("<error descr=\"Illegal/unsupported escape sequence\">\\</error>");
}
public void testBadEscape3() {
doTest("<error descr=\"Illegal/unsupported escape sequence\">\\E</error>");
}
public void testBackspaceChar() {
doTest("\\x08");
}
public void testUnicodeEscape() {
doTest("\\x{100000}");
}
public void testBadUnicodeEscape() {
doTest("<error descr=\"Illegal unicode escape sequence\">\\x{1000000}</error>");
}
public void testProperty1() {
doTest("^\\p{javaJavaIdentifierStart}+\\p{javaJavaIdentifierPart}+$");
}
public void testProperty2() {
doTest("\\p{InArabiC}\\p{IsTitleCase}\\p{IsAlphabetic}\\p{all}\\p{IsGreeK}");
}
public void testPosixCharacterClass() {
// posix character classes are not available in java regex patterns
doTest("[:xdig<warning descr=\"Duplicate character 'i' inside character class\">i</warning>t<warning descr=\"Duplicate character ':' inside character class\">:</warning>]+");
}
public void testNestedBackReference() {
doTest("([ab]+=<warning descr=\"Back reference is nested into the capturing group it refers to\">\\1</warning>)");
}
public void testNoNPE() {
doTest("(<error descr=\"Unclosed group\">\"</error>);}}
}
public void testBadInlineOption() {
doTest("(?i<error descr=\"Unknown inline option flag\">Z</error>m)abc");
}
public void testEscapedWhitespace() {
doTest("a\\ b\\ c");
}
public void testEscapedWhitespaceCommentMode() {
doTest("(?x)a\\ b\\ c");
}
public void testCountedQuantifier() {
doTest("a{2147483647}");
doTest("a{<error descr=\"Repetition value too large\">2147483648</error>}");
doTest("a{<error descr=\"Illegal repetition range (min > max)\">1,0</error>}");
doTest("a<weak_warning descr=\"Repetition range replaceable by '*'\">{<error descr=\"Number expected\">,</error>}</weak_warning>");
}
public void testOptions() {
doTest("(?i)<error descr=\"Dangling metacharacter\">+</error>");
doTest("(?i)<error descr=\"Dangling metacharacter\">*</error>");
doTest("(?i)<error descr=\"Dangling metacharacter\">{5,6}</error>");
}
public void testLookbehind() {
doTest("(?<!(aa)<error descr=\"* repetition not allowed inside lookbehind\">*</error>)");
doTest("(?<!(aa)<error descr=\"+ repetition not allowed inside lookbehind\">+</error>)");
doTest("(?<!(aa)?)");
doTest("(?<!(aa){2,6})");
doTest("(one)(?<!<error descr=\"Group reference not allowed inside lookbehind\">\\1</error>)");
}
public void testNamedProperties() {
doTest("\\p{<error descr=\"Unknown character category\">Block</error>}+");
doTest("\\p{Block=<error descr=\"Property value expected\">}</error>+");
doTest("\\p{Block=CombiningDiacriticalMarks}+");
doTest("\\p{blk=CombiningDiacriticalMarks}+");
doTest("\\p{blk=<error descr=\"Unknown property value\">XXX</error>}+");
doTest("\\p{script=Cyrillic}+");
doTest("\\p{SC=Cyrillic}+");
doTest("\\p{Sc=<error descr=\"Unknown property value\">YYY</error>}+");
doTest("\\p{general_Category=javaWhitespace}+");
doTest("\\p{GC=LD}+");
doTest("\\p{gc=<error descr=\"Unknown property value\">ZZZ</error>}+");
}
private void doTest(@NonNls String code) {
code = StringUtil.escapeBackSlashes(code);
myFixture.configureByText(JavaFileType.INSTANCE, "class X {{ java.util.regex.Pattern.compile(\"" + code + "\"); }}");
myFixture.testHighlighting();
}
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
return JAVA_8;
}
}
|
package net.openid.server;
import net.openid.association.Association;
import net.openid.association.AssociationException;
import net.openid.server.ServerAssociationStore;
import java.util.*;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
/**
* JDBC implementation for the ServerAssociationStore interface.
* <p>
* The JdbcServerAssociation store requires a javax.sql.DataSource to be
* configured and passed in to it with the setDataSource setter method.
* The table name also needs to be specified, either through the constructor,
* or through the setTableName setter.
* <p>
* The specified table must have the following structure:
* <ul>
* <li>handle : string : primary key</li>
* <li>type : string</li>
* <li>mackey : string</li>
* <li>expdate : date</li>
* </ul>
*
* @author Marius Scurtescu, Johnny Bufu
*/
public class JdbcServerAssociationStore extends JdbcDaoSupport
implements ServerAssociationStore
{
private static Logger _log = Logger.getLogger(JdbcServerAssociationStore.class);
private static final boolean DEBUG = _log.isDebugEnabled();
private static Random _random = new Random(System.currentTimeMillis());
private String _tableName;
// todo: removeExpired();
public JdbcServerAssociationStore()
{
}
public JdbcServerAssociationStore(String tableName)
{
_tableName = tableName;
}
public String getTableName()
{
return _tableName;
}
public void setTableName(String tableName)
{
this._tableName = tableName;
}
public Association generate(String type, int expiryIn)
throws AssociationException
{
String sql = "INSERT INTO " + _tableName +
" (handle, type, mackey, expdate) VALUES (?,?,?,?)";
JdbcTemplate jdbcTemplate = getJdbcTemplate();
int attemptsLeft = 5;
while (attemptsLeft > 0)
{
try
{
String handle = Long.toHexString(_random.nextLong());
Association association =
Association.generate(type, handle, expiryIn);
int cnt = jdbcTemplate.update(sql,
new Object[] {
association.getHandle(),
association.getType(),
new String(Base64.encodeBase64(
association.getMacKey().getEncoded())),
association.getExpiry()
});
if (cnt == 1)
{
if (DEBUG)
_log.debug("Generated association, handle: " + handle +
" type: " + type +
" expires in: " + expiryIn + " seconds.");
return association;
}
}
catch (DataAccessException e)
{
_log.error("Error generating association; attempts left: "
+ (attemptsLeft-1), e);
}
attemptsLeft
}
throw new AssociationException(
"JDBCServerAssociationStore: Error generating association.");
}
public Association load(String handle)
{
try
{
String sql = "SELECT type,mackey,expdate FROM " + _tableName +
" WHERE handle=?";
JdbcTemplate jdbcTemplate = getJdbcTemplate();
Map res = jdbcTemplate.queryForMap(sql, new Object[] {handle});
String type = (String) res.get("type");
String macKey = (String) res.get("mackey");
Date expDate = (Date) res.get("expdate");
if (type == null || macKey == null || expDate == null)
throw new AssociationException("Invalid association data " +
"retrived from database; cannot create Association " +
"object for handle: " + handle);
Association assoc;
if (Association.TYPE_HMAC_SHA1.equals(type))
assoc = Association.createHmacSha1(handle,
Base64.decodeBase64(macKey.getBytes() ), expDate);
else if (Association.TYPE_HMAC_SHA256.equals(type))
assoc = Association.createHmacSha256(handle,
Base64.decodeBase64(macKey.getBytes() ), expDate);
else
throw new AssociationException("Invalid association type " +
"retrieved from database: " + type);
if (DEBUG)
_log.debug("Retrieved association from database, handle: " + handle);
return assoc;
}
catch (AssociationException ase )
{
_log.error("Error rerieving association from database.", ase);
return null;
}
catch (IncorrectResultSizeDataAccessException rse)
{
_log.warn("Association not found in the database for handle: " + handle);
return null;
}
catch (DataAccessException dae)
{
_log.error("Error retrieving association from database, handle: "
+ handle, dae);
return null;
}
}
public void remove(String handle)
{
try
{
String sql = "DELETE FROM " + _tableName + " WHERE handle=?";
JdbcTemplate jdbcTemplate = getJdbcTemplate();
int cnt = jdbcTemplate.update(sql, new Object[] { handle } );
if (cnt == 1 && DEBUG)
_log.debug("Removed association, handle: " + handle);
if (cnt != 1)
_log.warn("Trying to remove handle: " + handle +
" from database; affected entries: " + cnt);
}
catch (Exception e)
{
_log.error("Error removing association from database.", e);
}
}
}
|
package org.jboss.forge.addon.javaee.faces;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.facets.FacetFactory;
import org.jboss.forge.addon.facets.FacetIsAmbiguousException;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.ProjectFactory;
import org.jboss.forge.addon.projects.facets.PackagingFacet;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.descriptor.api.facesconfig21.WebFacesConfigDescriptor;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author <a href="ggastald@redhat.com">George Gastaldi</a>
*/
@RunWith(Arquillian.class)
public class FacesFacetTest
{
@Deployment
@Dependencies({
@AddonDependency(name = "org.jboss.forge.addon:javaee"),
@AddonDependency(name = "org.jboss.forge.addon:maven")
})
public static ForgeArchive getDeployment()
{
return ShrinkWrap.create(ForgeArchive.class)
.addBeansXML()
.addAsAddonDependencies(
AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi"),
AddonDependencyEntry.create("org.jboss.forge.addon:projects"),
AddonDependencyEntry.create("org.jboss.forge.addon:javaee")
);
}
@Inject
private ProjectFactory projectFactory;
@Inject
private FacetFactory facetFactory;
@Test(expected = FacetIsAmbiguousException.class)
public void testCannotInstallAmbiguousFacetType() throws Exception
{
Project project = projectFactory.createTempProject();
Assert.assertNotNull(project);
facetFactory.install(project, FacesFacet.class);
}
@Test
public void testConfigDescriptorCreation_2_0() throws Exception
{
Project project = projectFactory.createTempProject();
Assert.assertNotNull(project);
PackagingFacet packaging = project.getFacet(PackagingFacet.class);
packaging.setPackagingType("war");
FacesFacet_2_0 facet = facetFactory.install(project, FacesFacet_2_0.class);
Assert.assertNotNull(facet);
FileResource<?> configFile = facet.getConfigFile();
Assert.assertTrue(configFile.exists());
org.jboss.shrinkwrap.descriptor.api.facesconfig20.WebFacesConfigDescriptor config = facet.getConfig();
config.createApplication().defaultRenderKitId("foo");
Assert.assertTrue(configFile.exists());
facet.saveConfig(config);
Assert.assertTrue(configFile.exists());
Assert.assertEquals("2.0", facet.getSpecVersion().toString());
Assert.assertTrue(project.hasFacet(FacesFacet.class));
}
@Test
public void testConfigDescriptorCreation_2_1() throws Exception
{
Project project = projectFactory.createTempProject();
Assert.assertNotNull(project);
PackagingFacet packaging = project.getFacet(PackagingFacet.class);
packaging.setPackagingType("war");
FacesFacet_2_1 facet = facetFactory.install(project, FacesFacet_2_1.class);
Assert.assertNotNull(facet);
FileResource<?> configFile = facet.getConfigFile();
Assert.assertTrue(configFile.exists());
WebFacesConfigDescriptor config = facet.getConfig();
config.createApplication().defaultRenderKitId("foo");
Assert.assertTrue(configFile.exists());
facet.saveConfig(config);
Assert.assertTrue(configFile.exists());
Assert.assertEquals("2.1", facet.getSpecVersion().toString());
Assert.assertTrue(project.hasFacet(FacesFacet.class));
}
@Test
public void testConfigDescriptorCreation_2_2() throws Exception
{
Project project = projectFactory.createTempProject();
Assert.assertNotNull(project);
PackagingFacet packaging = project.getFacet(PackagingFacet.class);
packaging.setPackagingType("war");
FacesFacet_2_2 facet = facetFactory.install(project, FacesFacet_2_2.class);
Assert.assertNotNull(facet);
FileResource<?> configFile = facet.getConfigFile();
Assert.assertTrue(configFile.exists());
org.jboss.shrinkwrap.descriptor.api.facesconfig22.WebFacesConfigDescriptor config = facet.getConfig();
config.createApplication().defaultRenderKitId("foo");
Assert.assertTrue(configFile.exists());
facet.saveConfig(config);
Assert.assertTrue(configFile.exists());
Assert.assertEquals("2.2", facet.getSpecVersion().toString());
Assert.assertTrue(project.hasFacet(FacesFacet.class));
}
@Test
public void testComponentLibraryConfigDescriptorCreation() throws Exception
{
// Create a temporary project of type JAR that acts as a component library instead of a web app and verify if
// Faces 2.0
Project faces20Project = projectFactory.createTempProject();
Assert.assertNotNull(faces20Project);
FacesFacet_2_0 faces20Facet = facetFactory.install(faces20Project, FacesFacet_2_0.class);
Assert.assertNotNull(faces20Facet);
FileResource<?> configFile = faces20Facet.getConfigFile();
Assert.assertFalse(configFile.exists());
// Faces 2.1
Project faces21Project = projectFactory.createTempProject();
Assert.assertNotNull(faces21Project);
FacesFacet_2_1 faces21Facet = facetFactory.install(faces21Project, FacesFacet_2_1.class);
Assert.assertNotNull(faces21Facet);
configFile = faces21Facet.getConfigFile();
Assert.assertFalse(configFile.exists());
// Faces 2.2
Project project = projectFactory.createTempProject();
Assert.assertNotNull(project);
FacesFacet_2_2 facet = facetFactory.install(project, FacesFacet_2_2.class);
Assert.assertNotNull(facet);
configFile = facet.getConfigFile();
Assert.assertFalse(configFile.exists());
}
@Test
public void testFacesFacetInstalledAfterProjectIsEvictedFromCache()
{
Project project = projectFactory.createTempProject();
facetFactory.install(project, FacesFacet_2_2.class);
projectFactory.invalidateCaches();
project = projectFactory.findProject(project.getRootDirectory());
Assert.assertTrue(project.hasFacet(FacesFacet.class));
Assert.assertTrue(project.hasFacet(FacesFacet_2_2.class));
}
}
|
package com.jeesuite.kafka.consumer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.DefaultManagedAwareThreadFactory;
import com.jeesuite.common.util.ResourceUtils;
import com.jeesuite.kafka.handler.MessageHandler;
import com.jeesuite.kafka.message.DefaultMessage;
import com.jeesuite.kafka.serializer.MessageDecoder;
import com.jeesuite.kafka.utils.KafkaConst;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;
/**
* @description <br>
* @author <a href="mailto:vakinge@gmail.com">vakin</a>
* @date 201671
*/
public class OldApiTopicConsumer implements TopicConsumer {
private final static Logger logger = LoggerFactory.getLogger(OldApiTopicConsumer.class);
private ConsumerConnector connector;
private Map<String, MessageHandler> topics;
private ThreadPoolExecutor fetchExecutor;
private ThreadPoolExecutor defaultProcessExecutor;
private static final int DEFAULT_PROCESS_THREADS = 50;
private AtomicBoolean runing = new AtomicBoolean(false);
private Map<String, AtomicLong> notProcessMessageCounts = new HashMap<>();
public OldApiTopicConsumer(ConsumerConnector connector, Map<String, MessageHandler> topics) {
Validate.notNull(connector);
this.connector = connector;
this.topics = topics;
int poolSize = topics.size();
this.fetchExecutor = new ThreadPoolExecutor(poolSize, poolSize, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new DefaultManagedAwareThreadFactory()) {
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
printException(r, t);
}
};
int processPoolSize = Integer.parseInt(ResourceUtils.get(KafkaConst.PROP_PROCESS_THREADS,String.valueOf(DEFAULT_PROCESS_THREADS)));
this.defaultProcessExecutor = new ThreadPoolExecutor(processPoolSize, processPoolSize, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new DefaultManagedAwareThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy()) {
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
printException(r, t);
}
};
logger.info("Kafka Conumer ThreadPool initialized,fetchPool Size:{},defalutProcessPool Size:{} ",poolSize,processPoolSize);
}
@Override
public void start() {
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
for (String topicName : topics.keySet()) {
int nThreads = 1;
topicCountMap.put(topicName, nThreads);
notProcessMessageCounts.put(topicName, new AtomicLong(0));
logger.info("topic[{}] assign fetch Threads {}",topicName,nThreads);
}
StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
MessageDecoder valueDecoder = new MessageDecoder();
Map<String, List<KafkaStream<String, Object>>> consumerMap = this.connector.createMessageStreams(topicCountMap,
keyDecoder, valueDecoder);
for (String topicName : topics.keySet()) {
final List<KafkaStream<String, Object>> streams = consumerMap.get(topicName);
for (final KafkaStream<String, Object> stream : streams) {
MessageProcessor processer = new MessageProcessor(topicName, stream);
this.fetchExecutor.execute(processer);
}
}
runing.set(true);
}
/**
*
* @param r
* @param t
*/
private static void printException(Runnable r, Throwable t) {
if (t == null && r instanceof Future<?>) {
try {
Future<?> future = (Future<?>) r;
if (future.isDone())
future.get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
logger.error(t.getMessage(), t);
}
class MessageProcessor implements Runnable {
KafkaStream<String, Object> stream;
private String topicName;
private MessageHandler messageHandler;
private String processorName;
public MessageProcessor(String topicName, KafkaStream<String, Object> stream) {
this.stream = stream;
this.topicName = topicName;
this.messageHandler = topics.get(topicName);
this.processorName = this.messageHandler.getClass().getName();
}
@Override
public void run() {
if (logger.isInfoEnabled()) {
logger.info("MessageProcessor [{}] start, topic:{}",Thread.currentThread().getName(),topicName);
}
ConsumerIterator<String, Object> it = stream.iterator();
while (it.hasNext()) {
long taskCount = notProcessMessageCounts.get(topicName).get();
// 100,30
int sleepSec = ( sleepSec = (int) (taskCount/100)) > 30 ? 30 : sleepSec;
if(sleepSec > 0){
try {Thread.sleep(TimeUnit.SECONDS.toMillis(sleepSec));} catch (Exception e) {}
}
try {
final DefaultMessage message = (DefaultMessage) it.next().message();
submitMessageToProcess(topicName,message);
} catch (Exception e) {
logger.error("received_topic_error,topic:"+topicName,e);
}
}
}
/**
*
* @param message
*/
private void submitMessageToProcess(final String topicName,final DefaultMessage message) {
notProcessMessageCounts.get(topicName).incrementAndGet();
defaultProcessExecutor.submit(new Runnable() {
@Override
public void run() {
try {
long start = logger.isDebugEnabled() ? System.currentTimeMillis() : 0;
messageHandler.process(message);
if(logger.isDebugEnabled()){
long useTime = System.currentTimeMillis() - start;
if(useTime > 1000)logger.debug("received_topic_useTime [{}]process topic:{} use time {} ms",processorName,topicName,useTime);
}
} catch (Exception e) {
logger.error("received_topic_process_error ["+processorName+"]processMessage error,topic:"+topicName,e);
}
notProcessMessageCounts.get(topicName).decrementAndGet();
}
});
}
}
@Override
public void close() {
if(!runing.get())return;
this.fetchExecutor.shutdownNow();
this.defaultProcessExecutor.shutdown();
this.connector.commitOffsets();
this.connector.shutdown();
runing.set(false);
logger.info("KafkaTopicSubscriber shutdown ok...");
}
}
|
package openblocks.common.tileentity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import openblocks.OpenBlocks;
import openblocks.network.ISyncableObject;
import openblocks.network.ISyncedTile;
import openblocks.network.SyncMap;
import openblocks.network.SyncableFlags;
import openblocks.network.SyncableInt;
import openblocks.network.SyncableIntArray;
import openblocks.network.SyncableManager;
import openblocks.utils.Coord;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet132TileEntityData;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.ITankContainer;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.liquids.LiquidTank;
public class TileEntityValve extends TileEntity implements ITankContainer, ISyncedTile {
public static enum Keys {
tankAmount,
tankCapacity,
flags,
linkedTiles,
liquidId,
liquidMeta
}
public static final int FLAG_ENABLED = 0;
public static final int CAPACITY_PER_TANK = LiquidContainerRegistry.BUCKET_VOLUME * 16;
private ForgeDirection direction = ForgeDirection.EAST;
private int checkTicker = 0;
private boolean needsRecheck = false;
private HashMap<Integer, Double> spread = new HashMap<Integer, Double>();
private HashMap<Integer, Integer> levelCapacity = new HashMap<Integer, Integer>();
public final LiquidTank tank = new LiquidTank(CAPACITY_PER_TANK);
private SyncMap syncMap = new SyncMap();
private SyncableInt tankAmount = new SyncableInt(0);
private SyncableInt tankCapacity = new SyncableInt(0);
private SyncableInt tankLiquidId = new SyncableInt(0);
private SyncableInt tankLiquidMeta = new SyncableInt(0);
private SyncableFlags flags = new SyncableFlags();
private SyncableIntArray linkedTiles = new SyncableIntArray();
public TileEntityValve() {
syncMap.put(Keys.tankAmount.ordinal(), tankAmount);
syncMap.put(Keys.tankCapacity.ordinal(), tankCapacity);
syncMap.put(Keys.flags.ordinal(), flags);
syncMap.put(Keys.linkedTiles.ordinal(), linkedTiles);
syncMap.put(Keys.liquidId.ordinal(), tankLiquidId);
syncMap.put(Keys.liquidMeta.ordinal(), tankLiquidMeta);
}
public int[] getLinkedCoords() {
return (int[])linkedTiles.getValue();
}
public void destroyTank() {
if (!linkedTiles.isEmpty()) {
int[] coords = (int[])linkedTiles.getValue();
for (int i = 0; i < coords.length; i += 3) {
int x = xCoord + coords[i];
int y = yCoord + coords[i+1];
int z = zCoord + coords[i+2];
if (worldObj.getBlockId(x, y, z) == OpenBlocks.Config.blockTankId) {
worldObj.setBlockToAir(x, y, z);
}
}
}
linkedTiles.clear();
}
@Override
public void updateEntity() {
if (!worldObj.isRemote) {
LiquidStack liquid = tank.getLiquid();
tankAmount.setValue(liquid == null ? 0 : liquid.amount);
if (liquid != null) {
tankLiquidId.setValue(liquid.itemID);
tankLiquidMeta.setValue(liquid.itemMeta);
}
if (checkTicker++ % 10 == 0) {
if (needsRecheck) {
checkTank();
}
syncMap.syncNearbyUsers(this);
}
}
}
public void markForRecheck() {
needsRecheck = true;
}
public HashMap<Integer, Double> getSpread() {
return spread;
}
public void checkTank() {
if (!worldObj.isRemote) {
HashMap<Integer, Coord> validAreas = new HashMap<Integer, Coord>();
HashMap<Integer, Coord> checkedAreas = new HashMap<Integer, Coord>();
Queue<Coord> queue = new LinkedBlockingQueue<Coord>();
queue.add(new Coord(direction.offsetX, direction.offsetY,
direction.offsetZ));
while (queue.size() > 0 && validAreas.size() < 100) {
Coord coord = queue.poll();
int blockId = worldObj.getBlockId(xCoord + coord.x, yCoord + coord.y, zCoord + coord.z);
if (blockId == 0 || blockId == OpenBlocks.Config.blockTankId) {
validAreas.put(coord.getHash(), coord);
if (coord.x > -127 && coord.x < 127 && coord.y > -127
&& coord.y < 127 && coord.z > -127 && coord.z < 127) {
int x = coord.x + 1;
int y = coord.y;
int z = coord.z;
if (!checkedAreas.containsKey(Coord.getHash(x, y, z))) {
queue.add(new Coord(x, y, z));
}
x
if (!checkedAreas.containsKey(Coord.getHash(x, y, z))) {
queue.add(new Coord(x, y, z));
}
y
if (!checkedAreas.containsKey(Coord.getHash(x, y, z))) {
queue.add(new Coord(x, y, z));
}
x
if (!checkedAreas.containsKey(Coord.getHash(x, y, z))) {
queue.add(new Coord(x, y, z));
}
y
if (!checkedAreas.containsKey(Coord.getHash(x, y, z))) {
queue.add(new Coord(x, y, z));
}
z
if (!checkedAreas.containsKey(Coord.getHash(x, y, z))) {
queue.add(new Coord(x, y, z));
}
}
}
checkedAreas.put(coord.getHash(), coord);
}
if (queue.size() == 0) {
flags.on(FLAG_ENABLED);
for (Coord coord : validAreas.values()) {
int x = xCoord + coord.x;
int y = yCoord + coord.y;
int z = zCoord + coord.z;
worldObj.setBlock(x, y, z, OpenBlocks.Config.blockTankId);
TileEntity te = worldObj.getBlockTileEntity(x, y, z);
if (te != null && te instanceof TileEntityTank) {
TileEntityTank tankBlock = (TileEntityTank) te;
tankBlock.setValve(this);
}
}
} else {
flags.off(FLAG_ENABLED);
destroyTank();
return;
}
if (!linkedTiles.isEmpty()) {
int[] alreadyLinked = (int[]) linkedTiles.getValue();
for (int i = 0; i < alreadyLinked.length; i+= 3) {
int x = alreadyLinked[i];
int y = alreadyLinked[i+1];
int z = alreadyLinked[i+2];
int hash = Coord.getHash(x, y, z);
if (!validAreas.containsKey(hash)) {
x += xCoord;
y += yCoord;
z += zCoord;
if (worldObj.getBlockId(x, y, z) == OpenBlocks.Config.blockTankId) {
worldObj.setBlockToAir(x, y, z);
}
}
}
}
int[] newLinkedTiles = new int[validAreas.size() * 3];
int i = 0;
for (Coord coord : validAreas.values()) {
newLinkedTiles[i++] = coord.x;
newLinkedTiles[i++] = coord.y;
newLinkedTiles[i++] = coord.z;
}
linkedTiles.setValue(newLinkedTiles);
int capacity = newLinkedTiles.length * (CAPACITY_PER_TANK);
tankCapacity.setValue(capacity);
tank.setCapacity(capacity);
}
}
public void setDirection(ForgeDirection direction) {
this.direction = direction;
}
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
tank.writeToNBT(tag);
tankCapacity.writeToNBT(tag, "tankCapacity");
System.out.println("tank capacity = "+ tankCapacity.getValue());
linkedTiles.writeToNBT(tag, "linkedTiles");
flags.writeToNBT(tag, "flags");
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
tank.readFromNBT(tag);
tankCapacity.readFromNBT(tag, "tankCapacity");
tank.setCapacity((Integer)tankCapacity.getValue());
System.out.println("tank capacity = "+ tankCapacity.getValue());
flags.readFromNBT(tag, "flags");
linkedTiles.readFromNBT(tag, "linkedTiles");
}
@Override
public int fill(ForgeDirection from, LiquidStack resource, boolean doFill) {
return fill(0, resource, doFill);
}
@Override
public int fill(int tankIndex, LiquidStack resource, boolean doFill) {
int filled = tank.fill(resource, doFill);
return filled;
}
@Override
public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
return drain(0, maxDrain, doDrain);
}
@Override
public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain) {
return tank.drain(maxDrain, doDrain);
}
@Override
public ILiquidTank[] getTanks(ForgeDirection direction) {
return new ILiquidTank[] { tank };
}
@Override
public ILiquidTank getTank(ForgeDirection direction, LiquidStack type) {
return tank;
}
public LiquidStack getLiquid() {
return tank.getLiquid();
}
public boolean isEnabled() {
return flags.get(FLAG_ENABLED);
}
@Override
public void onSynced(List<ISyncableObject> changes) {
if (worldObj.isRemote){
LiquidStack liquid = tank.getLiquid();
boolean recreateLiquid = false;
if (liquid == null || !tankLiquidId.equals(liquid.itemID) || !tankLiquidMeta.equals(liquid.itemMeta)) {
recreateLiquid = true;
}
tank.setCapacity((Integer)tankCapacity.getValue());
if (recreateLiquid) {
LiquidStack newLiquid = new LiquidStack(
(Integer)tankLiquidId.getValue(),
(Integer)tankCapacity.getValue(),
(Integer)tankLiquidMeta.getValue());
tank.setLiquid(newLiquid);
}
int[] tiles = (int[]) linkedTiles.getValue();;
HashMap<Integer, Integer> levelCapacity = new HashMap<Integer, Integer>();
for (int i = 0; i < tiles.length; i+=3) {
int f = 0;
int y = tiles[i + 1];
if (levelCapacity.containsKey(y)) {
f = levelCapacity.get(y);
}
f++;
levelCapacity.put(y, f);
}
List<Integer> sortedKeys = new ArrayList<Integer>(levelCapacity.keySet());
Collections.sort(sortedKeys);
spread.clear();
int remaining = (Integer)tankAmount.getValue();
for (Integer level : sortedKeys) {
int tanksOnLevel = levelCapacity.get(level);
int capacityForLevel = CAPACITY_PER_TANK * tanksOnLevel;
int usedByLevel = 0;
if (remaining > 0) {
usedByLevel = Math.min(remaining, capacityForLevel);
}
// System.out.println("Used by level " + level + " = "+ usedByLevel);
// System.out.println(((double) usedByLevel / (double) capacityForLevel));
remaining -= usedByLevel;
spread.put(level, ((double) usedByLevel / (double) capacityForLevel));
}
// System.out.println("linked tiles value = "+ linkedTiles.size());
}
}
@Override
public SyncMap getSyncMap() {
return syncMap;
}
}
|
package org.TexasTorque.TorqueLib.util;
import java.util.Hashtable;
public class TorqueLogging extends Thread
{
private static TorqueLogging instance;
private static String fileName = "TorqueLog.txt";
private static boolean logToDashboard = false;
private Hashtable table;
private String keys;
private String values;
private int numValues;
public static void setFileName(String fileNm)
{
fileName = fileNm;
}
public static void setDashboardLogging(boolean log)
{
logToDashboard = log;
}
public synchronized static TorqueLogging getInstance()
{
return (instance == null) ? instance = new TorqueLogging() : instance;
}
public TorqueLogging()
{
table = new Hashtable();
numValues = 0;
}
public void start()
{
}
public void run()
{
}
public synchronized void logValue(String name, int value)
{
if(table.get(name) == null)
{
keys += name;
numValues++;
}
table.put(name, "" + value);
}
public synchronized void logValue(String name, boolean value)
{
if(table.get(name) == null)
{
keys += name;
numValues++;
}
table.put(name, "" + value);
}
public synchronized void logValue(String name, double value)
{
if(table.get(name) == null)
{
keys += name;
numValues++;
}
table.put(name, "" + value);
}
public synchronized void logValue(String name, String value)
{
if(table.get(name) == null)
{
keys += name;
numValues++;
}
table.put(name, value);
}
public void writeKeysToFile()
{
}
public void calculateValueString()
{
}
public void writeValuesToFile()
{
}
public void writeToDashboard()
{
}
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.Argument;
import com.maddyhome.idea.vim.command.Command;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.command.SelectionType;
import com.maddyhome.idea.vim.common.Register;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.handler.CaretOrder;
import com.maddyhome.idea.vim.helper.EditorHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* This group works with command associated with copying and pasting text
*/
public class CopyGroup {
/**
* Creates the group
*/
public CopyGroup() {
}
/**
* This yanks the text moved over by the motion command argument.
*
* @param editor The editor to yank from
* @param context The data context
* @param count The number of times to yank
* @param rawCount The actual count entered by the user
* @param argument The motion command argument
* @return true if able to yank the text, false if not
*/
public boolean yankMotion(@NotNull Editor editor, DataContext context, int count, int rawCount,
@NotNull Argument argument) {
final Command motion = argument.getMotion();
if (motion == null) return false;
final CaretModel caretModel = editor.getCaretModel();
final List<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount());
final Map<Caret, Integer> startOffsets = new HashMap<>(caretModel.getCaretCount());
for (Caret caret : caretModel.getAllCarets()) {
final TextRange motionRange = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, true);
if (motionRange == null) continue;
assert motionRange.size() == 1;
ranges.add(Pair.createNonNull(motionRange.getStartOffset(), motionRange.getEndOffset()));
startOffsets.put(caret, motionRange.normalize().getStartOffset());
}
final SelectionType type = SelectionType.fromCommandFlags(motion.getFlags());
final TextRange range = getTextRange(ranges, type);
final SelectionType selectionType =
type == SelectionType.CHARACTER_WISE && range.isMultiple() ? SelectionType.BLOCK_WISE : type;
return yankRange(editor, range, selectionType, startOffsets);
}
/**
* This yanks count lines of text
*
* @param editor The editor to yank from
* @param count The number of lines to yank
* @return true if able to yank the lines, false if not
*/
public boolean yankLine(@NotNull Editor editor, int count) {
final CaretModel caretModel = editor.getCaretModel();
final List<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount());
for (Caret caret : caretModel.getAllCarets()) {
final int start = VimPlugin.getMotion().moveCaretToLineStart(editor, caret);
final int end = Math.min(VimPlugin.getMotion().moveCaretToLineEndOffset(editor, caret, count - 1, true) + 1,
EditorHelper.getFileSize(editor));
if (end == -1) continue;
ranges.add(Pair.createNonNull(start, end));
}
final TextRange range = getTextRange(ranges, SelectionType.LINE_WISE);
return yankRange(editor, range, SelectionType.LINE_WISE, null);
}
/**
* This yanks a range of text
*
* @param editor The editor to yank from
* @param range The range of text to yank
* @param type The type of yank
* @return true if able to yank the range, false if not
*/
public boolean yankRange(@NotNull Editor editor,
@Nullable TextRange range,
@NotNull SelectionType type,
boolean moveCursor) {
if (range == null) return false;
final SelectionType selectionType =
type == SelectionType.CHARACTER_WISE && range.isMultiple() ? SelectionType.BLOCK_WISE : type;
final CaretModel caretModel = editor.getCaretModel();
final int[] rangeStartOffsets = range.getStartOffsets();
final int[] rangeEndOffsets = range.getEndOffsets();
if (selectionType == SelectionType.LINE_WISE) {
final ArrayList<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount());
for (int i = 0; i < caretModel.getCaretCount(); i++) {
ranges.add(Pair.createNonNull(EditorHelper.getLineStartForOffset(editor, rangeStartOffsets[i]),
EditorHelper.getLineEndForOffset(editor, rangeEndOffsets[i]) + 1));
}
range = getTextRange(ranges, selectionType);
}
if (moveCursor) {
final Map<Caret, Integer> startOffsets = new HashMap<>(caretModel.getCaretCount());
if (type == SelectionType.BLOCK_WISE) {
startOffsets.put(caretModel.getPrimaryCaret(), range.normalize().getStartOffset());
}
else {
final List<Caret> carets = caretModel.getAllCarets();
for (int i = 0; i < carets.size(); i++) {
startOffsets
.put(carets.get(i), new TextRange(rangeStartOffsets[i], rangeEndOffsets[i]).normalize().getStartOffset());
}
}
return yankRange(editor, range, selectionType, startOffsets);
}
else {
return yankRange(editor, range, selectionType, null);
}
}
/**
* Pastes text from the last register into the editor.
*
* @param editor The editor to paste into
* @param context The data context
* @param count The number of times to perform the paste
* @return true if able to paste, false if not
*/
public boolean putText(@NotNull Editor editor,
@NotNull DataContext context,
int count,
boolean indent,
boolean cursorAfter,
boolean beforeCursor) {
final Register register = VimPlugin.getRegister().getLastRegister();
if (register == null) return false;
final SelectionType selectionType = register.getType();
if (selectionType == SelectionType.LINE_WISE && editor.isOneLineMode()) return false;
final String text = register.getText();
for (Caret caret : EditorHelper.getOrderedCaretsList(editor, CaretOrder.DECREASING_OFFSET)) {
final int startOffset = getStartOffset(editor, caret, selectionType, beforeCursor);
if (text == null) {
VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, startOffset);
VimPlugin.getMark().setChangeMarks(editor, new TextRange(startOffset, startOffset));
continue;
}
putText(editor, caret, context, text, selectionType, CommandState.SubMode.NONE, startOffset, count, indent,
cursorAfter);
}
return true;
}
public boolean putVisualRange(@NotNull Editor editor,
@NotNull DataContext context,
@NotNull TextRange range,
int count,
boolean indent,
boolean cursorAfter) {
final Register register = VimPlugin.getRegister().getLastRegister();
VimPlugin.getRegister().resetRegister();
if (register == null) return false;
final SelectionType type = register.getType();
if (type == SelectionType.LINE_WISE && editor.isOneLineMode()) return false;
final CaretModel caretModel = editor.getCaretModel();
final ArrayList<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount());
final List<Integer> endLines = new ArrayList<>(caretModel.getCaretCount());
for (int i = 0; i < range.size(); i++) {
final int start = range.getStartOffsets()[i];
final int end = range.getEndOffsets()[i];
ranges.add(Pair.createNonNull(start, end));
endLines.add(editor.offsetToLogicalPosition(end).line);
}
final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode();
if (subMode == CommandState.SubMode.VISUAL_LINE) {
final int[] starts = new int[caretModel.getCaretCount()];
final int[] ends = new int[caretModel.getCaretCount()];
for (int i = 0; i < ranges.size(); i++) {
final Pair.NonNull<Integer, Integer> subRange = ranges.get(i);
starts[i] = subRange.first;
ends[i] = Math.min(subRange.second + 1, EditorHelper.getFileSize(editor));
}
range = new TextRange(starts, ends);
}
final List<Caret> carets = EditorHelper.getOrderedCaretsList(editor, CaretOrder.DECREASING_OFFSET);
for (int i = 0; i < carets.size(); i++) {
final Caret caret = carets.get(i);
final int index = carets.size() - i - 1;
VimPlugin.getChange()
.deleteRange(editor, caret, new TextRange(range.getStartOffsets()[index], range.getEndOffsets()[index]),
SelectionType.fromSubMode(subMode), false);
final int start = ranges.get(index).first;
caret.moveToOffset(start);
int startOffset = start;
if (type == SelectionType.LINE_WISE) {
if (subMode == CommandState.SubMode.VISUAL_BLOCK) {
startOffset = editor.getDocument().getLineEndOffset(endLines.get(index)) + 1;
}
else if (subMode != CommandState.SubMode.VISUAL_LINE) {
editor.getDocument().insertString(start, "\n");
startOffset = start + 1;
}
}
else if (type != SelectionType.CHARACTER_WISE) {
if (subMode == CommandState.SubMode.VISUAL_LINE) {
editor.getDocument().insertString(start, "\n");
}
}
final String text = register.getText();
if (text == null) {
VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, startOffset);
VimPlugin.getMark().setChangeMarks(editor, new TextRange(startOffset, startOffset));
continue;
}
putText(editor, caret, context, text, type, subMode, startOffset, count,
indent && type == SelectionType.LINE_WISE, cursorAfter);
}
return true;
}
/**
* This performs the actual insert of the paste
*
* @param editor The editor to paste into
* @param context The data context
* @param startOffset The location within the file to paste the text
* @param text The text to paste
* @param type The type of paste
* @param count The number of times to paste the text
* @param indent True if pasted lines should be autoindented, false if not
* @param cursorAfter If true move cursor to just after pasted text
* @param mode The type of highlight prior to the put.
* @param caret The caret to insert to
*/
public void putText(@NotNull Editor editor,
@NotNull Caret caret,
@NotNull DataContext context,
@NotNull String text,
@NotNull SelectionType type,
@NotNull CommandState.SubMode mode,
int startOffset,
int count,
boolean indent,
boolean cursorAfter) {
if (mode == CommandState.SubMode.VISUAL_LINE && editor.isOneLineMode()) return;
if (indent && type != SelectionType.LINE_WISE && mode != CommandState.SubMode.VISUAL_LINE) indent = false;
if (type == SelectionType.LINE_WISE && text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
text = text + '\n';
}
final int endOffset = putTextInternal(editor, caret, context, text, type, mode, startOffset, count, indent);
moveCaret(editor, caret, type, mode, startOffset, cursorAfter, endOffset);
VimPlugin.getMark().setChangeMarks(editor, new TextRange(startOffset, endOffset));
}
private int putTextInternal(@NotNull Editor editor,
@NotNull Caret caret,
@NotNull DataContext context,
@NotNull String text,
@NotNull SelectionType type,
@NotNull CommandState.SubMode mode,
int startOffset,
int count,
boolean indent) {
final int endOffset = type != SelectionType.BLOCK_WISE
? putTextInternal(editor, caret, text, startOffset, count)
: putTextInternal(editor, caret, context, text, mode, startOffset, count);
if (indent) return doIndent(editor, caret, context, startOffset, endOffset);
return endOffset;
}
private int putTextInternal(@NotNull Editor editor,
@NotNull Caret caret,
@NotNull DataContext context,
@NotNull String text,
@NotNull CommandState.SubMode mode,
int startOffset,
int count) {
final LogicalPosition startPosition = editor.offsetToLogicalPosition(startOffset);
final int currentColumn = mode == CommandState.SubMode.VISUAL_LINE ? 0 : startPosition.column;
int currentLine = startPosition.line;
final int lineCount = StringUtil.getLineBreakCount(text) + 1;
if (currentLine + lineCount >= EditorHelper.getLineCount(editor)) {
final int limit = currentLine + lineCount - EditorHelper.getLineCount(editor);
for (int i = 0; i < limit; i++) {
MotionGroup.moveCaret(editor, caret, EditorHelper.getFileSize(editor, true));
VimPlugin.getChange().insertText(editor, caret, "\n");
}
}
final int maxLen = getMaxSegmentLength(text);
final StringTokenizer tokenizer = new StringTokenizer(text, "\n");
int endOffset = startOffset;
while (tokenizer.hasMoreTokens()) {
String segment = tokenizer.nextToken();
String origSegment = segment;
if (segment.length() < maxLen) {
segment += StringUtil.repeat(" ", maxLen - segment.length());
if (currentColumn != 0 && currentColumn < EditorHelper.getLineLength(editor, currentLine)) {
origSegment = segment;
}
}
final String pad = EditorHelper.pad(editor, context, currentLine, currentColumn);
final int insertOffset = editor.logicalPositionToOffset(new LogicalPosition(currentLine, currentColumn));
MotionGroup.moveCaret(editor, caret, insertOffset);
final String insertedText = origSegment + StringUtil.repeat(segment, count - 1);
VimPlugin.getChange().insertText(editor, caret, insertedText);
endOffset += insertedText.length();
if (mode == CommandState.SubMode.VISUAL_LINE) {
MotionGroup.moveCaret(editor, caret, endOffset);
VimPlugin.getChange().insertText(editor, caret, "\n");
++endOffset;
}
else {
if (pad.length() > 0) {
MotionGroup.moveCaret(editor, caret, insertOffset);
VimPlugin.getChange().insertText(editor, caret, pad);
endOffset += pad.length();
}
}
++currentLine;
}
return endOffset;
}
private int putTextInternal(@NotNull Editor editor, @NotNull Caret caret, @NotNull String text, int startOffset, int count) {
MotionGroup.moveCaret(editor, caret, startOffset);
final String insertedText = StringUtil.repeat(text, count);
VimPlugin.getChange().insertText(editor, caret, insertedText);
return startOffset + insertedText.length();
}
private int getStartOffset(@NotNull Editor editor, @NotNull Caret caret, SelectionType type, boolean beforeCursor) {
if (beforeCursor) {
return type == SelectionType.LINE_WISE
? VimPlugin.getMotion().moveCaretToLineStart(editor, caret)
: caret.getOffset();
}
int startOffset;
if (type == SelectionType.LINE_WISE) {
startOffset =
Math.min(editor.getDocument().getTextLength(), VimPlugin.getMotion().moveCaretToLineEnd(editor, caret) + 1);
if (startOffset > 0 &&
startOffset == editor.getDocument().getTextLength() &&
editor.getDocument().getCharsSequence().charAt(startOffset - 1) != '\n') {
editor.getDocument().insertString(startOffset, "\n");
startOffset++;
}
}
else {
startOffset = caret.getOffset();
if (!EditorHelper.isLineEmpty(editor, caret.getLogicalPosition().line, false)) {
startOffset++;
}
}
if (startOffset > 0 && startOffset > editor.getDocument().getTextLength()) return startOffset - 1;
return startOffset;
}
private void moveCaret(@NotNull Editor editor,
@NotNull Caret caret,
@NotNull SelectionType type,
@NotNull CommandState.SubMode mode,
int startOffset,
boolean cursorAfter,
int endOffset) {
int cursorMode;
if (type == SelectionType.BLOCK_WISE) {
if (mode == CommandState.SubMode.VISUAL_LINE) {
cursorMode = cursorAfter ? 4 : 1;
}
else {
cursorMode = cursorAfter ? 5 : 1;
}
}
else if (type == SelectionType.LINE_WISE) {
cursorMode = cursorAfter ? 4 : 3;
}
else /* Characterwise */ {
if (mode == CommandState.SubMode.VISUAL_LINE) {
cursorMode = cursorAfter ? 4 : 1;
}
else {
cursorMode = cursorAfter ? 5 : 2;
}
}
switch (cursorMode) {
case 1:
MotionGroup.moveCaret(editor, caret, startOffset);
break;
case 2:
MotionGroup.moveCaret(editor, caret, endOffset - 1);
break;
case 3:
MotionGroup.moveCaret(editor, caret, startOffset);
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, caret));
break;
case 4:
MotionGroup.moveCaret(editor, caret, endOffset + 1);
break;
case 5:
int pos = Math.min(endOffset, EditorHelper.getLineEndForOffset(editor, endOffset - 1) - 1);
MotionGroup.moveCaret(editor, caret, pos);
break;
}
}
private int doIndent(@NotNull Editor editor,
@NotNull Caret caret,
@NotNull DataContext context,
int startOffset,
int endOffset) {
final int startLine = editor.offsetToLogicalPosition(startOffset).line;
final int endLine = editor.offsetToLogicalPosition(endOffset - 1).line;
final int startLineOffset = editor.getDocument().getLineStartOffset(startLine);
final int endLineOffset = editor.getDocument().getLineEndOffset(endLine);
VimPlugin.getChange().autoIndentRange(editor, caret, context, new TextRange(startLineOffset, endLineOffset));
return EditorHelper.getLineEndOffset(editor, endLine, true);
}
private int getMaxSegmentLength(@NotNull String text) {
final StringTokenizer tokenizer = new StringTokenizer(text, "\n");
int maxLen = 0;
while (tokenizer.hasMoreTokens()) {
final String s = tokenizer.nextToken();
maxLen = Math.max(s.length(), maxLen);
}
return maxLen;
}
@NotNull
private TextRange getTextRange(@NotNull List<Pair.NonNull<Integer, Integer>> ranges, @NotNull SelectionType type) {
final int size = ranges.size();
final int[] starts = new int[size];
final int[] ends = new int[size];
switch (type) {
case LINE_WISE:
starts[size - 1] = ranges.get(size - 1).first;
ends[size - 1] = ranges.get(size - 1).second;
for (int i = 0; i < size - 1; i++) {
final Pair.NonNull<Integer, Integer> range = ranges.get(i);
starts[i] = range.first;
ends[i] = range.second - 1;
}
break;
case CHARACTER_WISE:
for (int i = 0; i < size; i++) {
final Pair.NonNull<Integer, Integer> range = ranges.get(i);
starts[i] = range.first;
ends[i] = range.second;
}
break;
case BLOCK_WISE:
assert ranges.size() == 1;
}
return new TextRange(starts, ends);
}
private boolean yankRange(@NotNull Editor editor,
@NotNull TextRange range,
@NotNull SelectionType type,
@Nullable Map<Caret, Integer> startOffsets) {
if (startOffsets != null) startOffsets.forEach((caret, offset) -> MotionGroup.moveCaret(editor, caret, offset));
return VimPlugin.getRegister().storeText(editor, range, type, false);
}
}
|
package ru.job4j.tracker;
public final class MenuActions {
static final int ADD = 0;
static final int SHOW = 1;
static final int EDIT = 2;
static final int DELETE = 3;
static final int FINDBYID = 4;
static final int FINDBYNAME = 5;
static final int EXIT = 6;
private MenuActions() {
}
}
|
package org.aikodi.chameleon.workspace;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.aikodi.chameleon.util.Util;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import be.kuleuven.cs.distrinet.rejuse.action.Nothing;
import be.kuleuven.cs.distrinet.rejuse.action.SafeAction;
import be.kuleuven.cs.distrinet.rejuse.association.OrderedMultiAssociation;
import be.kuleuven.cs.distrinet.rejuse.association.SingleAssociation;
/**
* A class for elements in XML files that can process themselves.
*
* @author Marko van Dooren
*
*/
public abstract class ConfigElement {
protected ConfigElement() {
initChildCache();
initAttributeCache();
}
/**
* Return the text of this configuration element. The default
* implementation return the empty string "".
*/
public String $getText() {
return _text;
}
public void $setText(String text) throws ConfigException {
_text = text;
}
private String _text;
public String nodeName() {
return Util.getLastPart(getClass().getName().replace('$', '.')).toLowerCase();
}
protected void readFromXML(File xmlFile) throws ConfigException {
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = fac.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
read(doc.getDocumentElement());
} catch (Exception e) {
throw new ConfigException(e);
}
}
public void writeToXML(File xmlFile) throws ConfigException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new ConfigException(e);
}
Document doc = docBuilder.newDocument();
// doc must be passed as an argument because it is the factory of the XML nodes
doc.appendChild(toElement(doc));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(xmlFile);
transformer.transform(source, result);
} catch (TransformerException e) {
throw new ConfigException(e);
}
}
protected Element toElement(Document doc) {
Element result = wrap(doc.createElement(nodeName()),doc);
addImplicitChildren(result, doc);
String text = $getText();
if(text != null) {
result.setTextContent(text);
}
// Add the attributes.
for(Method method: _attributeGetters) {
try {
String attributeName = attributeKey(method.getName());
// Attr attr = doc.createAttribute(attributeName);
String value = (String) method.invoke(this);
// attr.setValue(value);
result.setAttribute(attributeName, value);
// result.appendChild(attr);
} catch (Exception e) {
e.printStackTrace();
}
}
// Add the child elements.
for(ConfigElement cfg: _children.getOtherEnds()) {
result.appendChild(cfg.toElement(doc));
}
return result;
}
protected Element wrap(Element original, Document doc) {
return original;
}
protected void addImplicitChildren(Element result, Document doc) {
}
private void read(Element node) throws ConfigException {
$before();
// 1. Set the text
$setText(node.getTextContent());
// 2. Set the attributes
NamedNodeMap attributeMap = node.getAttributes();
int nbAttributes = attributeMap.getLength();
for(int i = 0; i < nbAttributes; i++) {
processAttribute((Attr)attributeMap.item(i));
}
NodeList nodes = node.getChildNodes();
int size = nodes.getLength();
for(int i = 0; i < size; i++) {
Node childNode = nodes.item(i);
if(childNode instanceof Element) {
processChild((Element)childNode);
}
}
$after();
}
protected void $before() throws ConfigException {}
protected void $after() throws ConfigException {}
/**
* A map from lower case elements names to the corresponding classes.
*/
protected Map<String, Class> _childClassMap;
protected Map<Class, String> _reverseChildClassMap;
protected void processChild(Element child) throws ConfigException {
String name = child.getNodeName();
Class childClass = getChildClass(name);
if(childClass != null) {
ConfigElement childConfig = createChild(childClass);
addChild(childConfig);
childConfig.read(child);
} else {
_unprocessed.add(child);
}
}
private <T extends ConfigElement> T createChild(Class<T> c) {
Class childClass = bind(c);
try {
T childConfig;
@SuppressWarnings("unused")
boolean inner = childClass.isMemberClass();
if(inner) {
// java.lang.reflect.Constructor[] cs = childClass.getConstructors();
@SuppressWarnings("unchecked")
java.lang.reflect.Constructor ctor = childClass.getConstructors()[0];
childConfig = (T) ctor.newInstance(this);
} else {
childConfig = (T) childClass.getDeclaredConstructor().newInstance();
}
addChild(childConfig);
return childConfig;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Map class 'c' to the most specific inner class that is its subclass. If there
* is more than one, an arbitrary class will be chosen (you should avoid this, though).
* @param c
* @return
*/
private Class bind(Class c) {
Class result = c;
Class[] classes = getClass().getClasses();
for(Class k: classes) {
if(result.isAssignableFrom(k)) {
result = k;
}
}
return result;
}
private List<Element> _unprocessed = new ArrayList<Element>();
private OrderedMultiAssociation<ConfigElement,ConfigElement> _children = new OrderedMultiAssociation<ConfigElement,ConfigElement>(this);
private SingleAssociation<ConfigElement,ConfigElement> _parent = new SingleAssociation<ConfigElement,ConfigElement>(this);
public ConfigElement parent() {
return _parent.getOtherEnd();
}
public void addChild(ConfigElement element) {
if(element != null) {
_children.add(element._parent);
}
}
public void removeChild(ConfigElement element) {
if(element != null) {
_children.remove(element._parent);
}
}
protected List<Element> unprocessedElements() {
return new ArrayList<Element>(_unprocessed);
}
protected Class getChildClass(String childName) {
return _childClassMap.get(childName.toLowerCase());
}
/**
* This is inefficient (on purpose!) as it is done for every element while it
* is a class-level property. I don't want to use static code to make it efficient
* because config files are typically small.
*/
private void initChildCache() {
_childClassMap = new HashMap<String, Class>();
_reverseChildClassMap = new HashMap<Class, String>();
for(Class c : getClass().getClasses()) {
String name = c.getName();
name = Util.getLastPart(name.replace('$', '.'));
String key = name.toLowerCase();
Class existing = _childClassMap.get(key);
if((existing == null) || existing.isAssignableFrom(c)) {
_childClassMap.put(key, c);
_reverseChildClassMap.put(c,key);
}
}
}
/**
* A map from lower case attribute names to the corresponding setter methods.
*/
protected Map<String, Method> _attributeMethodMap;
protected List<Method> _attributeGetters;
protected Method attributeSetter(String attributeName) {
return _attributeMethodMap.get(attributeName.toLowerCase());
}
protected void initAttributeCache() {
_attributeMethodMap = new HashMap<String, Method>();
_attributeGetters = new ArrayList<Method>();
Method[] methods = getClass().getMethods();
for(Method method: methods) {
String methodName = method.getName();
if(methodName.startsWith("set")) {
Type[] types = method.getGenericParameterTypes();
if(types.length == 1 && types[0] instanceof Class) {
Class c = (Class) types[0];
if(isString(c)) {
// cut of "set" from the start of the name
String key = attributeKey(methodName);
_attributeMethodMap.put(key, method);
}
}
}
}
// Look for getters that have a corresponding setter.
for(Method method: methods) {
String methodName = method.getName();
if(methodName.startsWith("get")) {
Type[] types = method.getGenericParameterTypes();
Type genericReturnType = method.getGenericReturnType();
if(types.length == 0 && genericReturnType.equals(String.class)) {
if(_attributeMethodMap.containsKey(attributeKey(methodName))) {
_attributeGetters.add(method);
}
}
}
}
}
protected boolean isString(Class c) {
return c.getCanonicalName().equals("java.lang.String");
}
protected String attributeKey(String methodName) {
return methodName.toLowerCase().substring(3,methodName.length());
}
protected void processAttribute(Attr attribute) {
try {
String name = attribute.getName();
String value = attribute.getValue();
Method attributeSetter = attributeSetter(name);
if(attributeSetter != null) {
attributeSetter.invoke(this, value);
}
} catch (IllegalAccessException e) {
// We ignore this to stop errors in a config file from preventing loading the configuration file.
e.printStackTrace();
} catch (InvocationTargetException e) {
// We ignore this to stop errors in a config file from preventing loading the configuration file.
e.printStackTrace();
}
}
public <T extends ConfigElement> T createOrGetChild(Class<T> type) {
for(ConfigElement element: _children.getOtherEnds()) {
if(type.isInstance(element)) {
return (T) element;
}
}
// If we reach this point, no element of the given type was found.
return createChild(type);
}
public <T extends ConfigElement> T createOrUpdateChild(Class<T> type, Object object) throws ConfigException {
ConfigElement element = childFor(object);
if(element == null) {
element = createChild(type);
element.setModelElement(object);
addChild(element);
}
element.$update();
return (T) element;
}
protected void $update() throws ConfigException {}
public ConfigElement childFor(Object object) {
for(ConfigElement element: _children.getOtherEnds()) {
if(element.modelElement() == object) {
return element;
}
}
return null;
}
public void removeChildFor(Object object) {
ConfigElement element = childFor(object);
if(element != null) {
element.disconnect();
}
}
public void disconnect() {
_parent.clear();
_children.apply(new SafeAction<ConfigElement>(ConfigElement.class) {
@Override
public void doPerform(ConfigElement object) throws Nothing {
object.disconnect();
}
});
// for(ConfigElement child: _children.getOtherEnds()) {
// child.disconnect();
}
private Object _modelElement;
public Object modelElement() {
return _modelElement;
}
public void setModelElement(Object m) {
_modelElement = m;
}
}
|
package org.junit.platform.engine;
import static org.junit.platform.commons.meta.API.Usage.Experimental;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import org.junit.platform.commons.meta.API;
/**
* Mutable descriptor for a test or container that has been discovered by a
* {@link TestEngine}.
*
* @see TestEngine
* @since 1.0
*/
@API(Experimental)
public interface TestDescriptor {
/**
* Get the unique identifier (UID) for this descriptor.
*
* <p>Uniqueness must be guaranteed across an entire test plan,
* regardless of how many engines are used behind the scenes.
*
* @return the {@code UniqueId} for this descriptor; never {@code null}
*/
UniqueId getUniqueId();
/**
* Get the display name for this descriptor.
*
* <p>A <em>display name</em> is a human-readable name for a test or
* container that is typically used for test reporting in IDEs and build
* tools. Display names may contain spaces, special characters, and emoji,
* and the format may be customized by {@link TestEngine TestEngines} or
* potentially by end users as well. Consequently, display names should
* never be parsed; rather, they should be used for display purposes only.
*
* @return the display name for this descriptor; never {@code null} or blank
* @see #getSource()
*/
String getDisplayName();
/**
* Get the name of this descriptor in a format that is suitable for legacy
* reporting infrastructure — for example, for reporting systems built
* on the Ant-based XML reporting format for JUnit 4.
*
* <p>The default implementation simply delegates to {@link #getDisplayName()}.
*
* @return the legacy reporting name; never {@code null}
*/
default String getLegacyReportingName() {
return getDisplayName();
}
/**
* Get the set of {@linkplain TestTag tags} associated with this descriptor.
*
* @return the set of tags associated with this descriptor; never {@code null}
* but potentially empty
* @see TestTag
*/
Set<TestTag> getTags();
/**
* Get the {@linkplain TestSource source} of the test or container described
* by this descriptor, if available.
*
* @see TestSource
*/
Optional<TestSource> getSource();
/**
* Get the <em>parent</em> of this descriptor, if available.
*/
Optional<TestDescriptor> getParent();
/**
* Set the <em>parent</em> of this descriptor.
*
* @param parent the new parent of this descriptor; may be {@code null}.
*/
void setParent(TestDescriptor parent);
/**
* Get the immutable set of <em>children</em> of this descriptor.
*
* @return the set of children of this descriptor; neither {@code null}
* nor mutable, but potentially empty
* @see #getDescendants()
*/
Set<? extends TestDescriptor> getChildren();
/**
* Get the immutable set of all <em>descendants</em> of this descriptor.
*
* <p>A <em>descendant</em> is a child of this descriptor or a child of one of
* its children, recursively.
*
* @see #getChildren()
*/
default Set<? extends TestDescriptor> getDescendants() {
Set<TestDescriptor> descendants = new LinkedHashSet<>();
descendants.addAll(getChildren());
for (TestDescriptor child : getChildren()) {
descendants.addAll(child.getDescendants());
}
return Collections.unmodifiableSet(descendants);
}
/**
* Add a <em>child</em> to this descriptor.
*
* @param descriptor the child to add to this descriptor; never {@code null}
*/
void addChild(TestDescriptor descriptor);
/**
* Remove a <em>child</em> from this descriptor.
*
* @param descriptor the child to remove from this descriptor; never
* {@code null}
*/
void removeChild(TestDescriptor descriptor);
/**
* Remove this non-root descriptor from its parent and remove all the
* children from this descriptor.
*
* <p>If this method is invoked on a {@linkplain #isRoot root} descriptor,
* this method must throw a {@link org.junit.platform.commons.JUnitException
* JUnitException} explaining that a root cannot be removed from the
* hierarchy.
*/
void removeFromHierarchy();
/**
* Determine if this descriptor is a <em>root</em> descriptor.
*
* <p>A <em>root</em> descriptor is a descriptor without a parent.
*/
default boolean isRoot() {
return !getParent().isPresent();
}
/**
* Determine the {@link Type} of this descriptor.
*
* @return the descriptor type; never {@code null}.
* @see #isContainer()
* @see #isTest()
*/
Type getType();
/**
* Determine if this descriptor describes a container.
*
* <p>The default implementation delegates to {@link Type#isContainer()}.
*/
default boolean isContainer() {
return getType().isContainer();
}
/**
* Determine if this descriptor describes a test.
*
* <p>The default implementation delegates to {@link Type#isTest()}.
*/
default boolean isTest() {
return getType().isTest();
}
/**
* Determine if this descriptor or any of its descendants describes a test.
*
* <p>The default implementation returns {@code true} if {@link #isTest()}
* returns {@code true} and otherwise recurses through this descriptor's
* {@linkplain #getChildren() children} to determine if they have tests.
*/
default boolean hasTests() {
return isTest() || getChildren().stream().anyMatch(TestDescriptor::hasTests);
}
/**
* Remove this descriptor from the hierarchy unless it is a root or has tests.
*
* <p>An concrete {@link TestEngine} may override this method in order to implement
* a different algorithm or to skip pruning altogether.
*
* @see #isRoot()
* @see #hasTests()
* @see #removeFromHierarchy()
*/
default void prune() {
if (isRoot() || hasTests()) {
return;
}
removeFromHierarchy();
}
/**
* Remove this descriptor and its descendants from the hierarchy.
*
* <p>The default implementation supplies the {@link #prune()} method as a
* {@link Visitor} to this descriptor, thereby effectively removing this
* descriptor and all of its descendants.
*
* @see #accept(Visitor)
* @see #prune()
*/
default void pruneTree() {
accept(TestDescriptor::prune);
}
/**
* Find the descriptor with the supplied unique ID.
*
* <p>The search algorithm begins with this descriptor and then searches
* through its descendants.
*
* @param uniqueId the {@code UniqueId} to search for; never {@code null}
*/
Optional<? extends TestDescriptor> findByUniqueId(UniqueId uniqueId);
/**
* Accept a visitor to the subtree starting with this descriptor.
*
* @param visitor the {@code Visitor} to accept; never {@code null}
*/
default void accept(Visitor visitor) {
visitor.visit(this);
// Create a copy of the set in order to avoid a ConcurrentModificationException
new LinkedHashSet<>(this.getChildren()).forEach(child -> child.accept(visitor));
}
/**
* Visitor for the tree-like {@link TestDescriptor} structure.
*
* @see TestDescriptor#accept
*/
@FunctionalInterface
interface Visitor {
/**
* Visit a {@link TestDescriptor}.
*
* @param descriptor the {@code TestDescriptor} to visit; never {@code null}
*/
void visit(TestDescriptor descriptor);
}
/**
* Supported types for {@link TestDescriptor TestDescriptors}.
*/
enum Type {
/**
* Denotes that the {@link TestDescriptor} is for a {@link TestEngine}.
*/
ENGINE,
/**
* Denotes that the {@link TestDescriptor} is for a <em>container</em>.
*/
CONTAINER,
/**
* Denotes that the {@link TestDescriptor} is for a <em>test</em>.
*/
TEST,
/**
* Denotes that the {@link TestDescriptor} is for a <em>test</em>
* that may potentially also be a <em>container</em>.
*/
CONTAINER_AND_TEST;
/**
* @return {@code true} if this type represents a descriptor that can
* contain other descriptors
*/
public boolean isContainer() {
return this == ENGINE || this == CONTAINER || this == CONTAINER_AND_TEST;
}
/**
* @return {@code true} if this type represents a descriptor for a test
*/
public boolean isTest() {
return this == TEST || this == CONTAINER_AND_TEST;
}
}
}
|
package com.meizhuo.etips.net.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import com.meizhuo.etips.common.Elog;
import com.meizhuo.etips.common.PathBuilder;
import com.meizhuo.etips.model.BookBorrowRecord;
import com.meizhuo.etips.model.BookInfo;
import com.meizhuo.etips.model.BookStatus;
import com.meizhuo.etips.model.SearchBookResult;
/**
* API 1) 2)
*
*
* APIAndroidApache HttpClient my eclipse Lib Android
* http client my eclipse lib 302my
* eclipse HttpClient 4.25 200ElipseAndroid
* android StatusCode 200302
*
*
* @author Jayin Ton
*
*/
public class LibraryAPI {
private String userid = null;
private String userpsw = null;
/**
* CookieStore cookie comment()cookie
* URLuseridcookie~
*/
private CookieStore mCookieStore = null;
private SearchBookResult searchBookResult;
public LibraryAPI() {
this("0", "0");
}
/**
*
*
* @param _userid
*
* @param _userpsw
*
*/
public LibraryAPI(String _userid, String _userpsw) {
userid = _userid;
userpsw = _userpsw;
searchBookResult = new SearchBookResult();
}
/**
*
* @param _userID
* @param _userPSW
*/
public void setUserData(String _userID, String _userPSW) {
userid = _userID;
userpsw = _userPSW;
}
/**
*
* @return true if login successfully
* @throws IOException
* @throws ClientProtocolException
*/
public boolean Login() throws ClientProtocolException, IOException {
// httpClient
HttpParams httpParams = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParams, false);
DefaultHttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://lib.wyu.edu.cn/opac/login.aspx");
HttpResponse response = null;
String __EVENTTARGET = "";
String __EVENTVALIDATION = "/wEWBQL99Iu/DwKOmK5RApX9wcYGAsP9wL8JAqW86pcI4PPe9nq/n81bkQRHtZ4j0i2bqXg=";
String __VIEWSTATE = "/wEPDwULLTE0MjY3MDAxNzcPZBYCZg9kFgoCAQ8PFgIeCEltYWdlVXJsBRt+XGltYWdlc1xoZWFkZXJvcGFjNGdpZi5naWZkZAICDw8WAh4EVGV4dAUn5LqU6YKR5aSn5a2m5Zu+5Lmm6aaG5Lmm55uu5qOA57Si57O757ufZGQCAw8PFgIfAQUcMjAxM+W5tDA35pyIMDbml6UgIOaYn+acn+WFrWRkAgQPZBYEZg9kFgQCAQ8WAh4LXyFJdGVtQ291bnQCCBYSAgEPZBYCZg8VAwtzZWFyY2guYXNweAAM55uu5b2V5qOA57SiZAICD2QWAmYPFQMOY2xzYnJvd3NlLmFzcHgADOWIhuexu+WvvOiIqmQCAw9kFgJmDxUDDmJvb2tfcmFuay5hc3B4AAzor7vkuabmjIflvJVkAgQPZBYCZg8VAwl4c3RiLmFzcHgADOaWsOS5pumAmuaKpWQCBQ9kFgJmDxUDFHJlYWRlcnJlY29tbWVuZC5hc3B4AAzor7vogIXojZDotK1kAgYPZBYCZg8VAxNvdmVyZHVlYm9va3NfZi5hc3B4AAzmj5DphpLmnI3liqFkAgcPZBYCZg8VAxJ1c2VyL3VzZXJpbmZvLmFzcHgAD+aIkeeahOWbvuS5pummhmQCCA9kFgJmDxUDFWh0dHA6Ly9saWIud3l1LmVkdS5jbgAP5Zu+5Lmm6aaG6aaW6aG1ZAIJD2QWAgIBDxYCHgdWaXNpYmxlaGQCAw8WAh8CZmQCAQ9kFgQCAw9kFgQCAQ8PZBYCHgxhdXRvY29tcGxldGUFA29mZmQCBw8PFgIfAWVkZAIFD2QWBgIBDxBkZBYBZmQCAw8QZGQWAWZkAgUPD2QWAh8EBQNvZmZkAgUPDxYCHwEF/gFDb3B5cmlnaHQgJmNvcHk7MjAwOC0yMDA5LiBTVUxDTUlTIE9QQUMgNC4wMS4gIEFsbCByaWdodHMgcmVzZXJ2ZWQuPGJyIC8+PHNjcmlwdCBsYW5ndWFnZT0iamF2YXNjcmlwdCIgdHlwZT0idGV4dC9qYXZhc2NyaXB0IiBzcmM9Imh0dHA6Ly9qcy51c2Vycy41MS5sYS8zMjI2ODYwLmpzIj48L3NjcmlwdD7niYjmnYPmiYDmnInvvJrkupTpgpHlpKflrablm77kuabppoYgRS1tYWlsOmhsaEB3eXUuZWR1LmNu77yM6IGU57O755S16K+d77yaNjYxMWRkZMkvhDEg7qh+n+8HSV6Wc9VY9MHo";
String ctl00$ContentPlaceHolder1$btnLogin_Lib = "";
String ctl00$ContentPlaceHolder1$txtlogintype = "0";
String ctl00$ContentPlaceHolder1$txtPas_Lib = userpsw; // psw
String ctl00$ContentPlaceHolder1$txtUsername_Lib = userid;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("__EVENTTARGET", __EVENTTARGET));
params.add(new BasicNameValuePair("__EVENTVALIDATION",
__EVENTVALIDATION));
params.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
params.add(new BasicNameValuePair(
"ctl00$ContentPlaceHolder1$btnLogin_Lib",
ctl00$ContentPlaceHolder1$btnLogin_Lib));
params.add(new BasicNameValuePair(
"ctl00$ContentPlaceHolder1$txtlogintype",
ctl00$ContentPlaceHolder1$txtlogintype));
params.add(new BasicNameValuePair(
"ctl00$ContentPlaceHolder1$txtPas_Lib",
ctl00$ContentPlaceHolder1$txtPas_Lib));
params.add(new BasicNameValuePair(
"ctl00$ContentPlaceHolder1$txtUsername_Lib",
ctl00$ContentPlaceHolder1$txtUsername_Lib));
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// may not
// decode?
post.setEntity(entity);
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 302) {
String s = EntityUtils.toString(response.getEntity(), "utf-8");
mCookieStore = client.getCookieStore();
System.out.println("Library Login successfully");
client.getConnectionManager().shutdown();
return true;
} else {
mCookieStore = client.getCookieStore();
System.out.println("Library login faild!");
}
client.getConnectionManager().shutdown();
return false;
}
/**
*
*
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public List<BookBorrowRecord> getBookBorrowRecord()
throws ClientProtocolException, IOException {
List<BookBorrowRecord> list = new ArrayList<BookBorrowRecord>();
DefaultHttpClient client = new DefaultHttpClient();
client.setCookieStore(mCookieStore);
HttpResponse response = client.execute(new HttpGet(
"http://lib.wyu.edu.cn/opac/user/bookborrowed.aspx"));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String html = EntityUtils.toString(response.getEntity(), "utf-8");
client.getConnectionManager().shutdown();
return HtmlParser.parseHtmlForBookBorrowRecord(html, list);
}
client.getConnectionManager().shutdown();
return list;
}
/**
*
*
* @param keyword
*
* @param page
* 1
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public List<BookInfo> searchBook(String keyword, int page)
throws ClientProtocolException, IOException {
int flag = 0;
if (searchBookResult.keyword.equals(keyword)) {
if (searchBookResult.getResultList(page) != null) {
return searchBookResult.getResultList(page);
} else
flag = 1;
} else {
flag = 2;
}
if (flag == 2)
searchBookResult = new SearchBookResult();
searchBookResult.keyword = keyword;
List<BookInfo> list = new ArrayList<BookInfo>();
String url = PathBuilder.getSearchPath(keyword, page);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String html = EntityUtils.toString(response.getEntity(), "utf-8");
client.getConnectionManager().shutdown();
int totalResult = HtmlParser.parseHtmlForSearch(html, list);
searchBookResult.addList(page, list);
searchBookResult.setTotalResult(totalResult);
return list;
} else {
client.getConnectionManager().shutdown();
// searchBookResult.addList(page, list);
return list;
}
}
/**
*
*
* @param keyword
*
* @return
*/
public int getTotalPage(String keyword) {
if (searchBookResult.keyword.equals(keyword))
return searchBookResult.getTotalPage();
return 0;
}
/**
* ->
*
* @param bookID
* ID
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public List<BookStatus> getBookStatus(String bookID)
throws ClientProtocolException, IOException {
List<BookStatus> list = new ArrayList<BookStatus>();
String url = PathBuilder.getBookInfoPath(bookID);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(url));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String html = EntityUtils.toString(response.getEntity(), "utf-8");
client.getConnectionManager().shutdown();
return HtmlParser.parseHtmlForBookStatus(html, list);
} else {
client.getConnectionManager().shutdown();
return list;
}
}
/**
* CookieStore cookie comment()cookie
* URLuseridcookie~ or
* 1) 2
*
* @param bookID
* ID
* @param userID
* ID
* @param comment
* comment_words
* @return true if comment successfully
* @throws IOException
* @throws ClientProtocolException
*/
public boolean comment(String bookID, String userID, String comment)
throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(PathBuilder.getCommetPath(bookID, userID));
System.out.println(PathBuilder.getCommetPath(bookID, userID));
List<NameValuePair> params = new ArrayList<NameValuePair>();
String __EVENTVALIDATION = "/wEWAwLeh4bkDwK21ooMAoznisYG0dvuv3jZRwNjVQ6uPzp8XTGJWGk=";
String __VIEWSTATE = "/wEPDwUKLTQ5MDA4NzU5MmRksMQZ9kEaRpoquE02WFkOgeYwiBg=";
String Button1 = "";
String txtreasons = comment;
params.add(new BasicNameValuePair("__EVENTVALIDATION",
__EVENTVALIDATION));
params.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
params.add(new BasicNameValuePair("Button1", Button1));
params.add(new BasicNameValuePair("txtreasons", txtreasons));
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
client.setCookieStore(mCookieStore); // key step
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
mCookieStore = client.getCookieStore();
System.out.println("comment successfully!");
client.getConnectionManager().shutdown();
return true;
} else {
System.out.println("comment faild!");
client.getConnectionManager().shutdown();
return false;
}
}
/**
* userID=0 ! CookieStore cookie comment()cookie
* URLuseridcookie~
*
* @param bookID
* ID
* @param comment
* comment_words
* @return true if comment successfully
* @throws IOException
* @throws ClientProtocolException
*/
public boolean comment(String bookID, String comment)
throws ClientProtocolException, IOException {
return comment(bookID, "0", comment);
}
/**
* ~
*
* @param list
*
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public List<BookBorrowRecord> getBorrowHistroy(List<BookBorrowRecord> list)
throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
if (mCookieStore != null)
client.setCookieStore(mCookieStore);
HttpResponse response = client.execute(new HttpGet(
"http://lib.wyu.edu.cn/opac/user/bookborrowedhistory.aspx"));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String html = EntityUtils.toString(response.getEntity());
client.getConnectionManager().shutdown();
return HtmlParser.parseHtmlForBorrowHistroy(html, list);
}
client.getConnectionManager().shutdown();
return list;
}
}
|
package org.anddev.andengine.opengl.font;
import org.anddev.andengine.opengl.texture.Texture;
import android.content.Context;
import android.graphics.Typeface;
/**
* @author Nicolas Gramlich
* @since 17:17:28 - 16.06.2010
*/
public class FontFactory {
// Constants
// Fields
private static String sAssetBasePath = "";
// Constructors
// Getter & Setter
public static void setAssetBasePath(final String pAssetBasePath) {
FontFactory.sAssetBasePath = pAssetBasePath;
}
// Methods for/from SuperClass/Interfaces
// Methods
public static Font create(final Texture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) {
return new Font(pTexture, pTypeface, pSize, pAntiAlias, pColor);
}
public static Font createFromAsset(final Texture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) {
return new Font(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor);
}
// Inner and Anonymous Classes
}
|
package se.kth.karamel.webservice;
import icons.TrayUI;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jetty.MutableServletContextHandler;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.SystemTray;
import java.io.Console;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import se.kth.karamel.client.api.KaramelApi;
import se.kth.karamel.client.api.KaramelApiImpl;
import se.kth.karamel.common.exception.KaramelException;
import se.kth.karamel.webservicemodel.*;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.EnumSet;
import java.util.Scanner;
import javax.swing.ImageIcon;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.eclipse.jetty.server.AbstractNetworkConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import se.kth.karamel.client.model.yaml.YamlCluster;
import se.kth.karamel.client.model.yaml.YamlUtil;
public class KaramelServiceApplication extends Application<KaramelServiceConfiguration> {
private static KaramelApi karamelApiHandler;
public static TrayUI trayUi;
private TemplateHealthCheck healthCheck;
private static final Options options = new Options();
private static final CommandLineParser parser = new GnuParser();
static {
// options.addOption("y", false, "Do not prompt for user-supplied parameters. Accept default param values.");
options.addOption("help", false, "Print help message.");
options.addOption(OptionBuilder.withArgName("yamlFile")
.hasArg()
.withDescription("Dropwizard configuration in a YAML file")
.create("server"));
options.addOption(OptionBuilder.withArgName("yamlFile")
.hasArg()
.withDescription("Karamel cluster definition in a YAML file")
.create("launch"));
}
public static void usage(int exitValue) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("karamel", options);
System.exit(exitValue);
}
static String readFile(String path)
throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded);
}
public static void main(String[] args) throws Exception {
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "9191";
}
boolean cli = false;
boolean launch = false;
String yamlTxt;
// These args are sent to the Dropwizard app (thread)
String[] modifiedArgs = new String[2];
modifiedArgs[0] = "server";
karamelApiHandler = new KaramelApiImpl();
try {
CommandLine line = parser.parse(options, args);
if (line.getOptions().length == 0) {
usage(0);
}
if (line.hasOption("help")) {
usage(0);
}
if (line.hasOption("server")) {
modifiedArgs[1] = line.getOptionValue("server");
}
if (line.hasOption("launch")) {
cli = true;
}
if (cli) {
// Try to open and read the yaml file.
// Print error msg if invalid file or invalid YAML.
try {
yamlTxt = readFile(line.getOptionValue("launch"));
YamlCluster cluster = YamlUtil.loadCluster(yamlTxt);
String jsonTxt = karamelApiHandler.yamlToJson(yamlTxt);
boolean valid = false;
String ec2Key = System.getenv("AWS_ACCESS_KEY");
String ec2SecretKey = System.getenv("AWS_SECRET_KEY");
Console c = null;
if (ec2Key == null || ec2Key.isEmpty() || ec2SecretKey == null || ec2SecretKey.isEmpty()) {
c = System.console();
if (c == null) {
System.err.println("No console available.");
System.exit(1);
}
}
while (!valid) {
if (ec2Key == null || ec2Key.isEmpty()) {
ec2Key = c.readLine("Enter your AWS_ACCESS_KEY:");
}
if (ec2SecretKey == null || ec2SecretKey.isEmpty()) {
char[] secretKeyChars = c.readPassword("Enter your AWS_SECRET_KEY:");
ec2SecretKey = new String(secretKeyChars);
}
valid = karamelApiHandler.updateEc2CredentialsIfValid(ec2Key, ec2SecretKey);
if (!valid) {
System.out.println("Invalid Ec2 Credentials. Try again.");
ec2Key = null;
ec2SecretKey = null;
}
}
karamelApiHandler.startCluster(jsonTxt);
long ms1 = System.currentTimeMillis();
while (ms1 + 6000000 > System.currentTimeMillis()) {
String clusterStatus = karamelApiHandler.getClusterStatus(cluster.getName());
System.out.println(clusterStatus);
Thread.currentThread().sleep(30000);
}
} catch (KaramelException e) {
System.err.println("Inalid yaml file; " + e.getMessage());
System.exit(-1);
} catch (IOException e) {
System.err.println("Could not find or parse yaml file.");
System.exit(-1);
}
}
} catch (ParseException e) {
usage(-1);
}
if (!cli) {
new KaramelServiceApplication().run(modifiedArgs);
}
}
// Name of the application displayed when application boots up.
@Override
public String getName() {
return "caramel-core";
}
// Pre start of the dropwizard to plugin with separate bundles.
@Override
public void initialize(Bootstrap<KaramelServiceConfiguration> bootstrap) {
System.out.println("Executing any initialization tasks.");
// bootstrap.addBundle(new ConfiguredAssetsBundle("/assets/", "/dashboard/"));
bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
}
@Override
public void run(KaramelServiceConfiguration configuration, Environment environment) throws Exception {
healthCheck = new TemplateHealthCheck("%s");
/*
* To allow cross orign resource request from angular js client
*/
FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class
);
// Allow cross origin requests.
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class
/**
* For the cluster yml supplied by the UI, convert it into JSON Object and
* return.
*/
@Path("/fetchJson")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static class ConvertYamlToJSON {
@PUT
public Response getJSONForYaml(KaramelBoardYaml cluster) {
Response response = null;
try {
String jsonClusterString = karamelApiHandler.yamlToJson(cluster.getYml());
response = Response.status(Response.Status.OK).entity(jsonClusterString).build();
} catch (KaramelException e) {
e.printStackTrace();
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, e.getMessage())).build();
}
return response;
}
}
@Path("/fetchYaml")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static class ConvertJSONToYaml {
@PUT
public Response getYamlForJSON(KaramelBoardJSON karamelBoardJSON) {
Response response = null;
System.out.println("Fetch Yaml Called ... ");
try {
String yml = karamelApiHandler.jsonToYaml(karamelBoardJSON.getJson());
KaramelBoardYaml karamelBoardYaml = new KaramelBoardYaml(yml);
response = Response.status(Response.Status.OK).entity(karamelBoardYaml).build();
} catch (KaramelException e) {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, e.getMessage())).build();
e.printStackTrace();
}
return response;
}
}
@Path("/fetchCookbook")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static class Cookbook {
@PUT
public Response getCookbook(CookbookJSON cookbookJSON) {
Response response = null;
System.out.println("Received Call For the cookbook.");
System.out.println(cookbookJSON.getUrl());
try {
String cookbookDetails = karamelApiHandler.getCookbookDetails(cookbookJSON.getUrl(), cookbookJSON.isRefresh());
response = Response.status(Response.Status.OK).entity(cookbookDetails).build();
} catch (KaramelException e) {
e.printStackTrace();
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, e.getMessage())).build();
}
return response;
}
}
@Path("/validateProvider")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static class ProviderValidation {
/**
* Validating the Provider based on the supplied credentials..
*
* @param providerJSON
* @return
*/
@PUT
public Response validateProvider(ProviderJSON providerJSON) {
Response response = null;
System.out.println(" Received request to validate the ec2 account.");
try {
if (karamelApiHandler.updateEc2CredentialsIfValid(providerJSON.getAccountId(), providerJSON.getAccountKey())) {
response = Response.status(Response.Status.OK).entity(new StatusResponseJSON(StatusResponseJSON.SUCCESS_STRING, "success")).build();
} else {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, "Invalid Credentials")).build();
}
} catch (KaramelException e) {
e.printStackTrace();
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, e.getMessage())).build();
}
return response;
}
}
/**
* Place holder class dealing with separate cluster state handling.
*/
public static class Cluster {
@Path("/startCluster")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static class StartCluster {
@PUT
public Response startCluster(KaramelBoardJSON boardJSON) {
Response response = null;
System.out.println(" Received request to start the cluster. ");
try {
karamelApiHandler.startCluster(boardJSON.getJson());
response = Response.status(Response.Status.OK).entity(new StatusResponseJSON(StatusResponseJSON.SUCCESS_STRING, "success")).build();
} catch (KaramelException e) {
e.printStackTrace();
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, e.getMessage())).build();
}
return response;
}
}
@Path("/viewCluster")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static class ViewCluster {
@PUT
public Response viewCluster(ClusterJSON clusterJSON) {
Response response = null;
System.out.println(" Received request to view the cluster.... ");
try {
String clusterInfo = karamelApiHandler.getClusterStatus(clusterJSON.getClusterName());
response = Response.status(Response.Status.OK).entity(clusterInfo).build();
} catch (KaramelException e) {
e.printStackTrace();
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new StatusResponseJSON(StatusResponseJSON.ERROR_STRING, e.getMessage())).build();
}
return response;
}
}
}
}
|
package entities;
import java.awt.Graphics2D;
import java.util.Random;
public class Entity {
public Random r;
protected int cellX, cellY;
public Entity() {
this.r = new Random();
}
public Entity(int cellX, int cellY) {
this.r = new Random();
this.cellX = cellX;
this.cellY = cellY;
}
public void setPosition(int cellX, int cellY) {
this.cellX = cellX;
this.cellY = cellY;
}
public void update() {}
public void update(boolean[] keys) {}
public void draw(Graphics2D g2d) {}
public boolean collide(Entity entity) {
if (entity.cellX == this.cellX && entity.cellY == this.cellY)
return true;
return false;
}
}
|
package com.namelessmc.java_api;
import com.github.mizosoft.methanol.Methanol;
import com.github.mizosoft.methanol.MutableRequest;
import com.google.common.base.Ascii;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.namelessmc.java_api.exception.ApiDisabledException;
import com.namelessmc.java_api.logger.ApiLogger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class RequestHandler {
private final @NonNull URL apiUrl;
private final @NonNull Methanol httpClient;
private final @Nullable ApiLogger debugLogger;
private final @NonNull Gson gson;
private final int responseLengthLimit;
RequestHandler(final @NonNull URL apiUrl,
final @NonNull Methanol httpClient,
final @NonNull Gson gson,
final @Nullable ApiLogger debugLogger,
final int responseLengthLimit) {
this.apiUrl = Objects.requireNonNull(apiUrl, "API URL is null");
this.httpClient = Objects.requireNonNull(httpClient, "http client is null");
this.gson = gson;
this.debugLogger = debugLogger;
this.responseLengthLimit = responseLengthLimit;
}
@NonNull Gson gson() {
return this.gson;
}
public @NonNull JsonObject post(final @NonNull String route,
final @NonNull JsonObject postData) throws NamelessException {
return makeConnection(route, postData);
}
public @NonNull JsonObject get(final @NonNull String route,
final @NonNull Object @NonNull... parameters) throws NamelessException {
final StringBuilder urlBuilder = new StringBuilder(route);
if (parameters.length > 0) {
if (parameters.length % 2 != 0) {
final String paramString = Arrays.stream(parameters).map(Object::toString).collect(Collectors.joining("|"));
throw new IllegalArgumentException(String.format("Parameter string varargs array length must be even (length is %s - %s)", parameters.length, paramString));
}
for (int i = 0; i < parameters.length; i++) {
if (i % 2 == 0) {
urlBuilder.append("&");
urlBuilder.append(parameters[i]);
} else {
urlBuilder.append("=");
try {
urlBuilder.append(URLEncoder.encode(parameters[i].toString(), StandardCharsets.UTF_8.toString()));
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
}
return makeConnection(urlBuilder.toString(), null);
}
private void debug(final @NonNull String message) {
if (this.debugLogger != null) {
this.debugLogger.log(message);
}
}
private void debug(final @NonNull Supplier<String> messageSupplier) {
if (this.debugLogger != null) {
this.debugLogger.log(messageSupplier.get());
}
}
private @NonNull JsonObject makeConnection(final @NonNull String route,
final @Nullable JsonObject postBody) throws NamelessException {
Preconditions.checkArgument(!route.startsWith("/"), "Route must not start with a slash");
final URI uri = URI.create(this.apiUrl + route);
if (uri.getHost() == null) {
throw new NamelessException("URI has empty host, does it contain invalid characters? Please note that although underscores are legal in subdomains, the Java URI class does not accept them.");
}
final MutableRequest request = MutableRequest.create(uri);
debug(() -> "Making connection " + (postBody != null ? "POST" : "GET") + " to " + request.uri());
if (postBody != null) {
byte[] postBytes = gson.toJson(postBody).getBytes(StandardCharsets.UTF_8);
request.POST(HttpRequest.BodyPublishers.ofByteArray(postBytes));
request.header("Content-Type", "application/json");
debug("Post body below\n
debug(() -> new String(postBytes, StandardCharsets.UTF_8));
debug("\n
} else {
request.GET();
}
int statusCode;
String responseBody;
try {
HttpResponse<InputStream> httpResponse = httpClient.send(request,
HttpResponse.BodyHandlers.ofInputStream());
statusCode = httpResponse.statusCode();
responseBody = getBodyAsString(httpResponse);
} catch (final IOException e) {
final @Nullable String exceptionMessage = e.getMessage();
final StringBuilder message = new StringBuilder("Network connection error (not a Nameless issue).");
if (exceptionMessage != null &&
exceptionMessage.contains("unable to find valid certification path to requested target")) {
message.append("\nHINT: Your certificate is invalid or incomplete. Ensure your website uses a valid *full chain* SSL/TLS certificate.");
}
message.append(" IOException: ");
message.append(e.getMessage());
throw new NamelessException(message.toString(), e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
debug("Website response below\n
debug(() -> regularAsciiOnly(responseBody));
debug("\n
if (responseBody.length() == 0) {
throw new NamelessException("Website sent empty response with status code " + statusCode);
}
if (responseBody.equals("API is disabled")) {
throw new ApiDisabledException();
}
JsonObject json;
try {
json = JsonParser.parseString(responseBody).getAsJsonObject();
} catch (final JsonSyntaxException | IllegalStateException e) {
StringBuilder message = new StringBuilder();
message.append("Website returned invalid response with code ");
message.append(statusCode);
message.append(".\n");
if (statusCode >= 301 && statusCode <= 303) {
message.append("HINT: The URL results in a redirect. If your URL uses http:
} else if (statusCode == 520 || statusCode == 521) {
message.append("HINT: Status code 520/521 is sent by CloudFlare when the backend webserver is down or having issues.\n");
} else if (responseBody.contains("/aes.js")) {
message.append("HINT: It looks like requests are being blocked by your web server or a proxy. ");
message.append("This is a common occurrence with free web hosting services; they usually don't allow API access.\n");
} else if (responseBody.contains("<title>Please Wait... | Cloudflare</title>")) {
message.append("HINT: CloudFlare is blocking our request. Please see https://docs.namelessmc.com/cloudflare-apis\n");
} else if (responseBody.startsWith("\ufeff")) {
message.append("HINT: The website response contains invisible unicode characters. This seems to be caused by Partydragen's Store module, we have no idea why.\n");
}
message.append("Website response:\n");
message.append("
int totalLengthLimit = 1950; // fit in a Discord message with safety margin
String printableResponse = regularAsciiOnly(responseBody);
message.append(Ascii.truncate(printableResponse, totalLengthLimit, "[truncated]\n"));
if (message.charAt(message.length() - 1) != '\n') {
message.append('\n');
}
throw new NamelessException(message.toString(), e);
}
if (!json.has("error")) {
throw new NamelessException("Unexpected response from website (missing json key 'error')");
}
if (json.get("error").getAsBoolean()) {
@Nullable String meta = null;
if (json.has("meta") && !json.get("meta").isJsonNull()) {
meta = json.get("meta").toString();
}
throw new ApiError(json.get("code").getAsInt(), meta);
}
return json;
}
private String getBodyAsString(HttpResponse<InputStream> response) throws IOException {
try (InputStream in = response.body();
InputStream limited = ByteStreams.limit(in, this.responseLengthLimit)) {
byte[] bytes = limited.readAllBytes();
if (bytes.length == this.responseLengthLimit) {
throw new IOException("Response larger than limit of " + this.responseLengthLimit + " bytes.");
}
return new String(bytes, StandardCharsets.UTF_8);
}
}
private static @NonNull String regularAsciiOnly(@NonNull String message) {
char[] chars = message.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
// only allow standard symbols, letters, numbers
// look up an ascii table if you don't understand this if statement
if (c >= ' ' && c <= '~' || c == '\n') {
chars[i] = c;
} else {
chars[i] = '.';
}
}
return new String(chars);
}
}
|
package com.opencms.file;
import com.opencms.core.*;
//import com.opencms.template.*;
//import com.opencms.util.*;
import java.util.*;
import java.io.*;
//import org.w3c.dom.*;
import com.opencms.file.genericSql.*;
//import com.opencms.file.genericSql.linkmanagement.*;
/**
* Access class for resources of the type "Folder".
*
* @author
* @version 1.0
*/
public class CmsResourceTypeFolder implements I_CmsResourceType, I_CmsConstants, Serializable, com.opencms.workplace.I_CmsWpConstants {
/**
* The id of resource type.
*/
private int m_resourceType;
/**
* The id of the launcher used by this resource.
*/
private int m_launcherType;
/**
* The resource type name.
*/
private String m_resourceTypeName;
/**
* The class name of the Java class launched by the launcher.
*/
private String m_launcherClass;
/**
* init a new CmsResourceType object.
*
* @param resourceType The id of the resource type.
* @param launcherType The id of the required launcher.
* @param resourceTypeName The printable name of the resource type.
* @param launcherClass The Java class that should be invoked by the launcher.
* This value is <b> null </b> if the default invokation class should be used.
*/
public void init(int resourceType, int launcherType,
String resourceTypeName, String launcherClass){
m_resourceType=resourceType;
m_launcherType=launcherType;
m_resourceTypeName=resourceTypeName;
m_launcherClass=launcherClass;
}
/**
* Returns the name of the Java class loaded by the launcher.
* This method returns <b>null</b> if the default class for this type is used.
*
* @return the name of the Java class.
*/
public String getLauncherClass() {
if ((m_launcherClass == null) || (m_launcherClass.length()<1)) {
return C_UNKNOWN_LAUNCHER;
} else {
return m_launcherClass;
}
}
/**
* Returns the launcher type needed for this resource-type.
*
* @return the launcher type for this resource-type.
*/
public int getLauncherType() {
return m_launcherType;
}
/**
* Returns the name for this resource-type.
*
* @return the name for this resource-type.
*/
public String getResourceTypeName() {
return m_resourceTypeName;
}
/**
* Returns the type of this resource-type.
*
* @return the type of this resource-type.
*/
public int getResourceType() {
return m_resourceType;
}
/**
* Returns a string-representation for this object.
* This can be used for debugging.
*
* @return string-representation for this object.
*/
public String toString() {
StringBuffer output=new StringBuffer();
output.append("[ResourceType]:");
output.append(m_resourceTypeName);
output.append(" , Id=");
output.append(m_resourceType);
output.append(" , launcherType=");
output.append(m_launcherType);
output.append(" , launcherClass=");
output.append(m_launcherClass);
return output.toString();
}
/**
* Changes the group of a resource.
* <br>
* Only the group of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not existing in the offline project already,
* it is read from the online project and written into the offline project.
* <p>
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param filename the complete path to the resource.
* @param newGroup the name of the new group for this resource.
* @param chRekursive shows if the subResources (of a folder) should be changed too.
*
* @exception CmsException if operation was not successful.
*/
public void chgrp(CmsObject cms, String filename, String newGroup, boolean chRekursive) throws CmsException{
CmsFolder folder = cms.readFolder(filename);
// check if the current user has the right to change the group of the
// resource. Only the owner of a file and the admin are allowed to do this.
if((cms.getRequestContext().currentUser().equals(cms.readOwner(folder)))
|| (cms.userInGroup(cms.getRequestContext().currentUser().getName(),
C_GROUP_ADMIN))) {
cms.doChgrp(filename, newGroup);
// now change the bodyfolder if exists
String bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + folder.getAbsolutePath();
try {
cms.readFolder(bodyFolder);
cms.doChgrp(bodyFolder, newGroup);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
// the rekursive flag was set do a recursive chown on all files and subfolders
if(chRekursive) {
// get all subfolders and files
Vector allFolders = new Vector();
Vector allFiles = new Vector();
getAllResources(cms, filename, allFiles, allFolders);
// now modify all subfolders
for(int i = 0;i < allFolders.size();i++) {
CmsFolder curfolder = (CmsFolder)allFolders.elementAt(i);
if(curfolder.getState() != C_STATE_DELETED) {
cms.doChgrp(curfolder.getAbsolutePath(), newGroup);
// check if there is a corresponding directory in the content body folder
bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + curfolder.getAbsolutePath();
try {
cms.readFolder(bodyFolder);
cms.doChgrp(bodyFolder, newGroup);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
}
}
// now modify all files in the subfolders
for(int i = 0;i < allFiles.size();i++) {
CmsFile newfile = (CmsFile)allFiles.elementAt(i);
if(newfile.getState() != C_STATE_DELETED) {
cms.chgrp(newfile.getAbsolutePath(), newGroup);
}
}
}
}else{
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the flags of a resource.
* <br>
* Only the flags of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not existing in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change the flags, if he is admin of the resource.
* <p>
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param filename the complete path to the resource.
* @param flags the new flags for the resource.
* @param chRekursive shows if the subResources (of a folder) should be changed too.
*
* @exception CmsException if operation was not successful.
* for this resource.
*/
public void chmod(CmsObject cms, String filename, int flags, boolean chRekursive) throws CmsException{
CmsFolder folder = cms.readFolder(filename);
// check if the current user has the right to change the group of the
// resource. Only the owner of a file and the admin are allowed to do this.
if((cms.getRequestContext().currentUser().equals(cms.readOwner(folder)))
|| (cms.userInGroup(cms.getRequestContext().currentUser().getName(),
C_GROUP_ADMIN))) {
// modify the access flags
cms.doChmod(filename, flags);
// now change the bodyfolder if exists
String bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + folder.getAbsolutePath();
try {
cms.readFolder(bodyFolder);
cms.doChmod(bodyFolder, flags);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
// the rekursive flag was set do a recursive chmod on all files and subfolders
if(chRekursive) {
// get all subfolders and files
Vector allFolders = new Vector();
Vector allFiles = new Vector();
getAllResources(cms, filename, allFiles, allFolders);
// now modify all subfolders
for(int i = 0;i < allFolders.size();i++) {
CmsFolder curfolder = (CmsFolder)allFolders.elementAt(i);
if(curfolder.getState() != C_STATE_DELETED) {
cms.doChmod(curfolder.getAbsolutePath(), flags);
// check if there is a corresponding directory in the content body folder
bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + curfolder.getAbsolutePath();
try {
cms.readFolder(bodyFolder);
cms.doChmod(bodyFolder, flags);
}catch(CmsException ex) {
// no folder is there, so do nothing
}
}
}
// now modify all files in the subfolders
for(int i = 0;i < allFiles.size();i++) {
CmsFile newfile = (CmsFile)allFiles.elementAt(i);
if(newfile.getState() != C_STATE_DELETED) {
cms.chmod(newfile.getAbsolutePath(), flags);
}
}
}
}else{
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the owner of a resource.
* <br>
* Only the owner of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not existing in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource.
* <p>
* <B>Security:</B>
* Access is cranted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or the user is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param filename the complete path to the resource.
* @param newOwner the name of the new owner for this resource.
* @param chRekursive shows if the subResources (of a folder) should be changed too.
*
* @exception CmsException if operation was not successful.
*/
public void chown(CmsObject cms, String filename, String newOwner, boolean chRekursive) throws CmsException{
CmsFolder folder = cms.readFolder(filename);
// check if the current user has the right to change the owner of the
// resource. Only the owner of a file and the admin are allowed to do this.
if((cms.getRequestContext().currentUser().equals(cms.readOwner(folder)))
|| (cms.userInGroup(cms.getRequestContext().currentUser().getName(), C_GROUP_ADMIN))) {
// change the owner
cms.doChown(filename, newOwner);
String bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + folder.getAbsolutePath();
try {
cms.readFolder(bodyFolder);
cms.doChown(bodyFolder, newOwner);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
// the rekursive flag was set do a recursive chmod on all files and subfolders
if(chRekursive) {
// get all subfolders and files
Vector allFolders = new Vector();
Vector allFiles = new Vector();
getAllResources(cms, filename, allFiles, allFolders);
// now modify all subfolders
for(int i = 0;i < allFolders.size();i++) {
CmsFolder curfolder = (CmsFolder)allFolders.elementAt(i);
if(curfolder.getState() != C_STATE_DELETED) {
cms.doChown(curfolder.getAbsolutePath(), newOwner);
// check if there is a corresponding directory in the content body folder
bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + curfolder.getAbsolutePath();
try {
cms.readFolder(bodyFolder);
cms.doChown(bodyFolder, newOwner);
}catch(CmsException ex) {
// no folder is there, so do nothing
}
}
}
// now modify all files in the subfolders
for(int i = 0;i < allFiles.size();i++) {
CmsFile newfile = (CmsFile)allFiles.elementAt(i);
if(newfile.getState() != C_STATE_DELETED) {
cms.chown(newfile.getAbsolutePath(), newOwner);
}
}
}
}else{
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the resourcetype of a resource.
* <br>
* Only the resourcetype of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource.
* <p>
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param filename the complete path to the resource.
* @param newType the name of the new resourcetype for this resource.
*
* @exception CmsException if operation was not successful.
*/
public void chtype(CmsObject cms, String filename, String newType) throws CmsException{
// it is not possible to change the type of a folder
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_ACCESS_DENIED);
}
/**
* Copies a Resource.
*
* @param source the complete path of the sourcefile.
* @param destination the complete path of the destinationfolder.
* @param keepFlags <code>true</code> if the copy should keep the source file's flags,
* <code>false</code> if the copy should get the user's default flags.
*
* @exception CmsException if the file couldn't be copied, or the user
* has not the appropriate rights to copy the file.
*/
public void copyResource(CmsObject cms, String source, String destination, boolean keepFlags) throws CmsException{
// we have to copy the folder and all resources in the folder
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, source, allSubFiles, allSubFolders);
if (!destination.endsWith("/")){
destination = destination +"/";
}
// first the folder
cms.doCopyFolder(source, destination);
if(!keepFlags){
setDefaultFlags(cms, destination);
}
// now the subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() != C_STATE_DELETED){
String curDestination = destination + curFolder.getAbsolutePath().substring(source.length());
cms.doCopyFolder(curFolder.getAbsolutePath(), curDestination );
if(!keepFlags){
setDefaultFlags(cms, curDestination);
}
}
}
// now all the little files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() != C_STATE_DELETED){
String curDest = destination + curFile.getAbsolutePath().substring(source.length());
cms.copyResource(curFile.getAbsolutePath(), curDest, keepFlags);
}
}
// finaly lock the copy in content bodys if it exists.
try{
cms.lockResource(C_CONTENTBODYPATH + destination.substring(1));
}catch(CmsException e){
}
}
/**
* Copies a resource from the online project to a new, specified project.
* <br>
* Copying a resource will copy the file header or folder into the specified
* offline project and set its state to UNCHANGED.
*
* @param resource the name of the resource.
* @exception CmsException if operation was not successful.
*/
//public byte[] copyResourceToProject(CmsObject cms, I_CmsLinkManager linkManager, int resourceId, byte[] content) throws CmsException {
public byte[] copyResourceToProject(CmsObject cms, String resourceName, byte[] content) throws CmsException {
return content;
}
/**
* Copies a resource from the online project to a new, specified project.
* <br>
* Copying a resource will copy the file header or folder into the specified
* offline project and set its state to UNCHANGED.
*
* @param resource the name of the resource.
* @exception CmsException if operation was not successful.
*/
public void copyResourceToProject(CmsObject cms, String resourceName) throws CmsException {
// copy the folder to the current project
cms.doCopyResourceToProject(resourceName);
// try to copy the corresponding folder in /content/bodys/ to the project
try{
CmsResource contentFolder = (CmsResource)cms.readFolder(C_CONTENTBODYPATH.substring(0, C_CONTENTBODYPATH.lastIndexOf("/"))+resourceName, true);
if (contentFolder != null){
cms.doCopyResourceToProject(contentFolder.getAbsolutePath());
}
} catch(CmsException e){
// cannot read the folder in /content/bodys/ so do nothing
}
}
/**
* Creates a new resource.<br>
*
* @param folder the complete path to the folder in which the file will be created.
* @param filename the name of the new resource.
* @param contents the contents of the new file.
* @param type the resourcetype of the new file.
*
* @return file a <code>CmsFile</code> object representing the newly created file.
*
* @exception CmsException or if the resourcetype is set to folder. The CmsException is also thrown, if the
* filename is not valid or if the user has not the appropriate rights to create a new file.
*/
public CmsResource createResource(CmsObject cms, String folder, String name, Hashtable properties, byte[] contents) throws CmsException{
CmsFolder res = cms.doCreateFolder(folder, name, properties);
cms.lockResource(folder+name+"/");
res.setLocked(cms.getRequestContext().currentUser().getId());
return res;
}
/**
* Deletes a resource.
*
* @param folder the complete path of the folder.
*
* @exception CmsException if the file couldn't be deleted, or if the user
* has not the appropriate rights to delete the file.
*/
public void deleteResource(CmsObject cms, String folder) throws CmsException{
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, folder, allSubFiles, allSubFolders);
// first delete all the files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() != C_STATE_DELETED){
cms.deleteResource(curFile.getAbsolutePath());
}
}
// now all the empty subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() != C_STATE_DELETED){
cms.doDeleteFolder(curFolder.getAbsolutePath());
}
}
// finaly the folder
cms.doDeleteFolder(folder);
// delete the corresponding folder in /content/bodys/
String bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + folder;
try {
cms.readFolder(bodyFolder);
cms.deleteResource(bodyFolder);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
}
/**
* Uneletes a resource.
*
* @param folder the complete path of the folder.
*
* @exception CmsException if the file couldn't be undeleted, or if the user
* has not the appropriate rights to undelete the file.
*/
public void undeleteResource(CmsObject cms, String folder) throws CmsException{
// we have to undelete the folder and all resources in the folder
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, folder, allSubFiles, allSubFolders);
// first undelete all the files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() == C_STATE_DELETED){
cms.undeleteResource(curFile.getAbsolutePath());
}
}
// now all the empty subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() == C_STATE_DELETED){
cms.doUndeleteFolder(curFolder.getAbsolutePath());
}
}
// finally the folder
cms.doUndeleteFolder(folder);
// undelete the corresponding folder in /content/bodys/
String bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + folder;
try {
cms.readFolder(bodyFolder,true);
cms.undeleteResource(bodyFolder);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
}
/**
* Does the Linkmanagement when a resource will be exported.
* When a resource has to be exported, the IDs inside the
* Linkmanagement-Tags have to be changed to the corresponding URLs
*
* @param file is the file that has to be changed
*/
public CmsFile exportResource(CmsObject cms, CmsFile file) throws CmsException {
// nothing to do here, because there couldnt be any Linkmanagement-Tags inside a folder-resource
return file;
}
/**
* Imports a Folder.
* Does the Linkmanagement when a resource is imported.
* When a resource has to be imported, the URLs of the
* Links inside the resources have to be saved and changed to the corresponding IDs
*
* @param file is the file that has to be changed
*/
public CmsResource importResource(CmsObject cms, String source, String destination, String type, String user, String group, String access, Hashtable properties, String launcherStartClass, byte[] content, String importPath) throws CmsException {
CmsResource cmsfolder = null;
String path = importPath + destination.substring(0, destination.lastIndexOf("/") + 1);
String name = destination.substring((destination.lastIndexOf("/") + 1), destination.length());
String fullname = null;
try {
cmsfolder = createResource(cms, path, name, properties, content);
if(cmsfolder != null){
fullname = cmsfolder.getAbsolutePath();
lockResource(cms, fullname, true);
}
} catch (CmsException e) {
// an exception is thrown if the folder already exists
}
if(fullname == null){
//the folder exists, check if properties has to be updated
cmsfolder = cms.readFolder(path, name + "/");
Hashtable oldProperties = cms.readAllProperties(cmsfolder.getAbsolutePath());
if(oldProperties == null){
oldProperties = new Hashtable();
}
if(properties == null){
properties = new Hashtable();
}
if( !oldProperties.equals(properties)){
fullname = cmsfolder.getAbsolutePath();
lockResource(cms, fullname, true);
cms.writeProperties(fullname, properties);
}
if(fullname == null){
// properties are the same but what about the owner, group and access?
if(cmsfolder.getFlags() != Integer.parseInt(access) ||
cmsfolder.getOwnerId() != cms.readUser(user).getId() ||
cmsfolder.getGroupId() != cms.readGroup(group).getId() ){
fullname = cmsfolder.getAbsolutePath();
lockResource(cms, fullname, true);
}
}
}
if(fullname != null){
try{
cms.chmod(fullname, Integer.parseInt(access));
}catch(CmsException e){
System.out.println("chmod(" + access + ") failed ");
}
try{
cms.chgrp(fullname, group);
}catch(CmsException e){
System.out.println("chgrp(" + group + ") failed ");
}
try{
cms.chown(fullname, user);
}catch(CmsException e){
System.out.println("chown((" + user + ") failed ");
}
}
return cmsfolder;
}
public void linkmanagementSaveImportedResource(CmsObject cms, String importedResource) throws CmsException {
// nothing to do here
}
/**
* Locks a given resource.
* <br>
* A user can lock a resource, so he is the only one who can write this
* resource.
*
* @param resource the complete path to the resource to lock.
* @param force if force is <code>true</code>, a existing locking will be overwritten.
*
* @exception CmsException if the user has not the rights to lock this resource.
* It will also be thrown, if there is a existing lock and force was set to false.
*/
public void lockResource(CmsObject cms, String resource, boolean force) throws CmsException{
// first lock the folder in the /content/bodys/ path if it exists.
try{
cms.doLockResource(C_CONTENTBODYPATH + resource.substring(1), force);
}catch(CmsException e){
// ignore the error. this folder doesent exist.
}
// now lock the folder
cms.doLockResource(resource, force);
}
/**
* Moves a file to the given destination.
*
* @param source the complete path of the sourcefile.
* @param destination the complete path of the destinationfile.
*
* @exception CmsException if the user has not the rights to move this resource,
* or if the file couldn't be moved.
*/
public void moveResource(CmsObject cms, String source, String destination) throws CmsException{
// it is a folder so we need the end /
destination = destination +"/";
// we have to copy the folder and all resources in the folder
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, source, allSubFiles, allSubFolders);
if(!cms.accessWrite(source)){
throw new CmsException(source, CmsException.C_NO_ACCESS);
}
// first copy the folder
cms.doCopyFolder(source, destination);
// now copy the subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() != C_STATE_DELETED){
String curDestination = destination + curFolder.getAbsolutePath().substring(source.length());
cms.doCopyFolder(curFolder.getAbsolutePath(), curDestination );
}
}
// now move the files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() != C_STATE_DELETED){
String curDest = destination + curFile.getAbsolutePath().substring(source.length());
cms.moveResource(curFile.getAbsolutePath(), curDest);
}
}
// finaly remove the original folders
deleteResource(cms, source);
}
//public byte[] publishResource(I_CmsLinkManager linkManager, int resourceId, byte[] content) throws CmsException {
public byte[] publishResource(String resourceName, byte[] content) throws CmsException {
// nothing to do here in terms of the linkmanagement
// return null. the content of the resource will not be changed
return null;
}
/**
* Renames the file to the new name.
*
* @param oldname the complete path to the file which will be renamed.
* @param newname the new name of the file.
*
* @exception CmsException if the user has not the rights
* to rename the file, or if the file couldn't be renamed.
*/
public void renameResource(CmsObject cms, String oldname, String newname) throws CmsException{
// first of all check the new name
validResourcename(newname);
// we have to copy the folder and all resources in the folder
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, oldname, allSubFiles, allSubFolders);
String parent = ((CmsResource)cms.readFileHeader(oldname)).getParent();
if(!cms.accessWrite(oldname)){
throw new CmsException(oldname, CmsException.C_NO_ACCESS);
}
// first copy the folder
cms.doCopyFolder(oldname, parent + newname + "/");
// now copy the subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() != C_STATE_DELETED){
String curDestination = parent + newname + "/"
+ curFolder.getAbsolutePath().substring(oldname.length());
cms.doCopyFolder(curFolder.getAbsolutePath(), curDestination );
}
}
// now move the files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() != C_STATE_DELETED){
String curDest = parent + newname + "/"
+ curFile.getAbsolutePath().substring(oldname.length());
cms.moveResource(curFile.getAbsolutePath(), curDest);
}
}
// finaly remove the original folders
deleteResource(cms, oldname);
}
/**
* Restores a file in the current project with a version in the backup
*
* @param cms The CmsObject
* @param versionId The version id of the resource
* @param filename The name of the file to restore
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void restoreResource(CmsObject cms, int versionId, String filename) throws CmsException{
throw new CmsException("[" + this.getClass().getName() + "] Cannot restore folders.",CmsException.C_ACCESS_DENIED);
}
/**
* Undo changes in a resource.
* <br>
*
* @param resource the complete path to the resource to be restored.
*
* @exception CmsException if the user has not the rights
* to write this resource.
*/
public void undoChanges(CmsObject cms, String resource) throws CmsException{
// we have to undo changes of the folder and all resources in the folder
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, resource, allSubFiles, allSubFolders);
String parent = ((CmsResource)cms.readFileHeader(resource)).getParent();
if(!cms.accessWrite(resource)){
throw new CmsException("[" + this.getClass().getName() + "]"+resource, CmsException.C_NO_ACCESS);
}
// first undo changes of the folder
cms.doUndoChanges(resource);
// now undo changes of the subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() != C_STATE_NEW){
if(curFolder.getState() == C_STATE_DELETED){
undeleteResource(cms, curFolder.getAbsolutePath());
lockResource(cms, curFolder.getAbsolutePath(), true);
}
undoChanges(cms, curFolder.getAbsolutePath());
} else {
// if it is a new folder then delete the folder
try{
deleteResource(cms, curFolder.getAbsolutePath());
} catch (CmsException ex){
// do not throw exception when resource not exists
if(ex.getType() != CmsException.C_NOT_FOUND){
throw ex;
}
}
}
}
// now undo changes in the files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() != C_STATE_NEW){
if(curFile.getState() == C_STATE_DELETED){
cms.undeleteResource(curFile.getAbsolutePath());
cms.lockResource(curFile.getAbsolutePath(), true);
}
cms.undoChanges(curFile.getAbsolutePath());
} else {
// if it is a new file then delete the file
try{
cms.deleteResource(curFile.getAbsolutePath());
} catch (CmsException ex){
// do not throw exception when resource not exists
if(ex.getType() != CmsException.C_NOT_FOUND){
throw ex;
}
}
}
}
}
/**
* Unlocks a resource.
* <br>
* A user can unlock a resource, so other users may lock this file.
*
* @param resource the complete path to the resource to be unlocked.
*
* @exception CmsException if the user has not the rights
* to unlock this resource.
*/
public void unlockResource(CmsObject cms, String resource) throws CmsException{
// first unlock the folder in the /content/bodys/ path if it exists.
try{
cms.doUnlockResource(C_CONTENTBODYPATH + resource.substring(1));
}catch(CmsException e){
// ignore the error. this folder doesent exist.
}
// now unlock the folder
cms.doUnlockResource(resource);
}
/**
* Set the access flags of the copied Folder to the default values.
* @param cms The CmsObject.
* @param foldername The name of the folder.
* @exception Throws CmsException if something goes wrong.
*/
private void setDefaultFlags(CmsObject cms, String foldername)
throws CmsException {
Hashtable startSettings=null;
Integer accessFlags=null;
startSettings=(Hashtable)cms.getRequestContext().currentUser().getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS);
if (startSettings != null) {
accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS);
}
if (accessFlags == null) {
accessFlags = new Integer(C_ACCESS_DEFAULT_FLAGS);
}
chmod(cms, foldername, accessFlags.intValue(), false);
}
/**
* Gets all resources - files and subfolders - of a given folder.
* @param cms The CmsObject.
* @param rootFolder The name of the given folder.
* @param allFiles Vector containing all files found so far. All files of this folder
* will be added here as well.
* @param allolders Vector containing all folders found so far. All subfolders of this folder
* will be added here as well.
* @exception Throws CmsException if something goes wrong.
*/
private void getAllResources(CmsObject cms, String rootFolder, Vector allFiles,
Vector allFolders) throws CmsException {
Vector folders = new Vector();
Vector files = new Vector();
// get files and folders of this rootFolder
folders = cms.getSubFolders(rootFolder, true);
files = cms.getFilesInFolder(rootFolder, true);
//copy the values into the allFiles and allFolders Vectors
for(int i = 0;i < folders.size();i++) {
allFolders.addElement((CmsFolder)folders.elementAt(i));
getAllResources(cms, ((CmsFolder)folders.elementAt(i)).getAbsolutePath(),
allFiles, allFolders);
}
for(int i = 0;i < files.size();i++) {
allFiles.addElement((CmsFile)files.elementAt(i));
}
}
/**
* Checks if there are at least one character in the resourcename
*
* @param resourcename String to check
*
* @exception throws a exception, if the check fails.
*/
protected void validResourcename( String resourcename )
throws CmsException {
if (resourcename == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + resourcename,
CmsException.C_BAD_NAME);
}
int l = resourcename.trim().length();
if (l == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + resourcename,
CmsException.C_BAD_NAME);
}
}
/**
* Changes the project-id of the resource to the new project
* for publishing the resource directly
*
* @param newProjectId The Id of the new project
* @param resourcename The name of the resource to change
*/
public void changeLockedInProject(CmsObject cms, int newProjectId, String resourcename)
throws CmsException{
// we have to change the folder and all resources in the folder
Vector allSubFolders = new Vector();
Vector allSubFiles = new Vector();
getAllResources(cms, resourcename, allSubFiles, allSubFolders);
// first change all the files
for (int i=0; i<allSubFiles.size(); i++){
CmsFile curFile = (CmsFile)allSubFiles.elementAt(i);
if(curFile.getState() != C_STATE_UNCHANGED){
cms.changeLockedInProject(newProjectId, curFile.getAbsolutePath());
}
}
// now all the subfolders
for (int i=0; i<allSubFolders.size(); i++){
CmsFolder curFolder = (CmsFolder) allSubFolders.elementAt(i);
if(curFolder.getState() != C_STATE_UNCHANGED){
changeLockedInProject(cms, newProjectId, curFolder.getAbsolutePath());
}
}
// finally the folder
cms.doChangeLockedInProject(newProjectId, resourcename);
// change the corresponding folder in /content/bodys/
String bodyFolder = C_CONTENTBODYPATH.substring(0,
C_CONTENTBODYPATH.lastIndexOf("/")) + resourcename;
try {
cms.readFolder(bodyFolder,true);
changeLockedInProject(cms, newProjectId, bodyFolder);
}
catch(CmsException ex) {
// no folder is there, so do nothing
}
}
}
|
package com.artursworld.nccn.model.persistence.manager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.util.Log;
import com.artursworld.nccn.controller.config.App;
import com.artursworld.nccn.model.entity.FearOfProgressionQuestionnaire;
import com.artursworld.nccn.model.persistence.contracts.DBContracts;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class FearOfProgressionManager extends EntityDbManager {
private String CLASS_NAME = FearOfProgressionManager.class.getSimpleName();
public FearOfProgressionManager() {
super(App.getAppContext());
}
FearOfProgressionManager(Context ctx) {
super(ctx);
}
public void insertQuestionnaire(FearOfProgressionQuestionnaire questionnaire) {
try {
if (questionnaire == null) {
Log.e(CLASS_NAME, "the questionnaire to be inserted equals null!");
return;
}
ContentValues contentValues = getQuestionnaireContentValues(questionnaire);
database.insertOrThrow(DBContracts.FoPTable.TABLE_NAME, null, contentValues);
Log.i(CLASS_NAME, "New questionnaire added successfully:" + questionnaire.toString());
} catch (Exception e) {
Log.e(CLASS_NAME, "Could not insert new questionnaire into db: " + questionnaire + "! " + e.getLocalizedMessage());
e.printStackTrace();
}
}
public void update(FearOfProgressionQuestionnaire questionnaire) {
String WHERE_CLAUSE = DBContracts.FoPTable.CREATION_DATE_PK + " =?";
String[] WHERE_ARGS = new String[]{EntityDbManager.dateFormat.format(questionnaire.getCreationDate_PK())};
if (questionnaire.getCreationDate_PK() == null) {
Log.e(CLASS_NAME, "Cannot update questionnaire: " + questionnaire);
return;
}
try {
ContentValues contentValues = getQuestionnaireContentValues(questionnaire);
database.update(DBContracts.FoPTable.TABLE_NAME, contentValues, WHERE_CLAUSE, WHERE_ARGS);
Log.d(CLASS_NAME, "questionnaire has been updated");
} catch (Exception e) {
Log.e(CLASS_NAME, "Exception! Could not update the questionnaire(" + questionnaire + ") " + " " + e.getLocalizedMessage());
}
}
public FearOfProgressionQuestionnaire getQuestionnaireByDate(String userName, Date data) {
List<FearOfProgressionQuestionnaire> list = getQuestionnaireListByUserName(userName);
SimpleDateFormat format = EntityDbManager.dateFormat;
for (FearOfProgressionQuestionnaire item : list) {
if (format.format(item.getCreationDate_PK()).equals(format.format(data))) {
return item;
}
}
return null;
}
@NonNull
private List<FearOfProgressionQuestionnaire> getQuestionnaireListByUserName(String userName) {
List<FearOfProgressionQuestionnaire> resultList = new ArrayList<>();
try {
Cursor cursor = database.query(DBContracts.FoPTable.TABLE_NAME,
getColumns(),
DBContracts.FoPTable.COLUMN_NAME_ID_FK + " LIKE '" + userName + "'",
null, null, null, null);
while (cursor.moveToNext()) {
FearOfProgressionQuestionnaire questionnaire = new FearOfProgressionQuestionnaire(null);
questionnaire.setCreationDate_PK(EntityDbManager.dateFormat.parse(cursor.getString(0)));
questionnaire.setUserNameId_FK(cursor.getString(1));
questionnaire.setUpdateDate(EntityDbManager.dateFormat.parse(cursor.getString(2)));
questionnaire.setLastQuestionEditedNr(cursor.getInt(3));
questionnaire.setProgressInPercent(cursor.getInt(4));
questionnaire.setSelectedAnswerIndexQ1(cursor.getInt(5));
questionnaire.setSelectedAnswerIndexQ2(cursor.getInt(6));
questionnaire.setSelectedAnswerIndexQ3(cursor.getInt(7));
questionnaire.setSelectedAnswerIndexQ4(cursor.getInt(8));
questionnaire.setSelectedAnswerIndexQ5(cursor.getInt(9));
questionnaire.setSelectedAnswerIndexQ6(cursor.getInt(10));
questionnaire.setSelectedAnswerIndexQ7(cursor.getInt(11));
questionnaire.setSelectedAnswerIndexQ8(cursor.getInt(12));
questionnaire.setSelectedAnswerIndexQ9(cursor.getInt(13));
questionnaire.setSelectedAnswerIndexQ10(cursor.getInt(14));
questionnaire.setSelectedAnswerIndexQ11(cursor.getInt(15));
questionnaire.setSelectedAnswerIndexQ12(cursor.getInt(16));
resultList.add(questionnaire);
}
if (!cursor.isClosed()) {
cursor.close();
}
} catch (Exception e) {
Log.i(CLASS_NAME, "Failed to parse date at getQuestionnaireByUserName(" + userName + ")!" + e.getLocalizedMessage());
}
return resultList;
}
/**
* Get content values by questionnaire
*
* @param questionnaire the questionnaire to get the values out
* @return the ContentValues of the questionnaire
*/
private ContentValues getQuestionnaireContentValues(FearOfProgressionQuestionnaire questionnaire) {
ContentValues values = new ContentValues();
if (questionnaire.getUserNameId_FK() != null)
values.put(DBContracts.FoPTable.COLUMN_NAME_ID_FK, questionnaire.getUserNameId_FK());
if (questionnaire.getCreationDate_PK() != null)
values.put(DBContracts.FoPTable.CREATION_DATE_PK, EntityDbManager.dateFormat.format(questionnaire.getCreationDate_PK()));
if (questionnaire.getUpdateDate() != null)
values.put(DBContracts.FoPTable.UPDATE_DATE, EntityDbManager.dateFormat.format(questionnaire.getUpdateDate()));
if (questionnaire.getLastQuestionEditedNr() >= 0)
values.put(DBContracts.FoPTable.LAST_QUESTION_EDITED_NR, questionnaire.getLastQuestionEditedNr());
if (questionnaire.getProgressInPercent() >= 0)
values.put(DBContracts.FoPTable.PROGRESS, questionnaire.getProgressInPercent());
if (questionnaire.getSelectedAnswerIndexQ1() > -1)
values.put(DBContracts.FoPTable.ANSWER_1, questionnaire.getSelectedAnswerIndexQ1());
if (questionnaire.getSelectedAnswerIndexQ2() > -1)
values.put(DBContracts.FoPTable.ANSWER_2, questionnaire.getSelectedAnswerIndexQ2());
if (questionnaire.getSelectedAnswerIndexQ3() > -1)
values.put(DBContracts.FoPTable.ANSWER_3, questionnaire.getSelectedAnswerIndexQ3());
if (questionnaire.getSelectedAnswerIndexQ4() > -1)
values.put(DBContracts.FoPTable.ANSWER_4, questionnaire.getSelectedAnswerIndexQ4());
if (questionnaire.getSelectedAnswerIndexQ5() > -1)
values.put(DBContracts.FoPTable.ANSWER_5, questionnaire.getSelectedAnswerIndexQ5());
if (questionnaire.getSelectedAnswerIndexQ6() > -1)
values.put(DBContracts.FoPTable.ANSWER_6, questionnaire.getSelectedAnswerIndexQ6());
if (questionnaire.getSelectedAnswerIndexQ7() > -1)
values.put(DBContracts.FoPTable.ANSWER_7, questionnaire.getSelectedAnswerIndexQ7());
if (questionnaire.getSelectedAnswerIndexQ8() > -1)
values.put(DBContracts.FoPTable.ANSWER_8, questionnaire.getSelectedAnswerIndexQ8());
if (questionnaire.getSelectedAnswerIndexQ9() > -1)
values.put(DBContracts.FoPTable.ANSWER_9, questionnaire.getSelectedAnswerIndexQ9());
if (questionnaire.getSelectedAnswerIndexQ10() > -1)
values.put(DBContracts.FoPTable.ANSWER_10, questionnaire.getSelectedAnswerIndexQ10());
if (questionnaire.getSelectedAnswerIndexQ11() > -1)
values.put(DBContracts.FoPTable.ANSWER_11, questionnaire.getSelectedAnswerIndexQ11());
if (questionnaire.getSelectedAnswerIndexQ12() > -1)
values.put(DBContracts.FoPTable.ANSWER_12, questionnaire.getSelectedAnswerIndexQ12());
return values;
}
@NonNull
private String[] getColumns() {
return new String[]{
DBContracts.FoPTable.CREATION_DATE_PK,
DBContracts.FoPTable.COLUMN_NAME_ID_FK,
DBContracts.FoPTable.UPDATE_DATE,
DBContracts.FoPTable.LAST_QUESTION_EDITED_NR,
DBContracts.FoPTable.PROGRESS,
DBContracts.FoPTable.ANSWER_1,
DBContracts.FoPTable.ANSWER_2,
DBContracts.FoPTable.ANSWER_3,
DBContracts.FoPTable.ANSWER_4,
DBContracts.FoPTable.ANSWER_5,
DBContracts.FoPTable.ANSWER_6,
DBContracts.FoPTable.ANSWER_7,
DBContracts.FoPTable.ANSWER_8,
DBContracts.FoPTable.ANSWER_9,
DBContracts.FoPTable.ANSWER_10,
DBContracts.FoPTable.ANSWER_11,
DBContracts.FoPTable.ANSWER_12,
};
}
}
|
package org.apache.xerces.impl.xs;
import org.apache.xerces.impl.RevalidationHandler;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.dv.DatatypeException;
import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.xs.identity.*;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.validation.ValidationManager;
import org.apache.xerces.util.XMLGrammarPoolImpl;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.xs.traversers.XSAttributeChecker;
import org.apache.xerces.impl.xs.models.CMBuilder;
import org.apache.xerces.impl.xs.models.XSCMValidator;
import org.apache.xerces.impl.xs.psvi.XSConstants;
import org.apache.xerces.impl.xs.psvi.XSObjectList;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.impl.validation.ValidationState;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.util.AugmentationsImpl;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.IntStack;
import org.apache.xerces.util.XMLResourceIdentifierImpl;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.grammars.Grammar;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.psvi.ElementPSVI;
import org.apache.xerces.xni.psvi.AttributePSVI;
import org.xml.sax.InputSource ;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
import java.io.IOException;
public class XMLSchemaValidator
implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler {
// Constants
private static final boolean DEBUG = false;
// feature identifiers
/** Feature identifier: validation. */
protected static final String VALIDATION =
Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;
/** Feature identifier: validation. */
protected static final String SCHEMA_VALIDATION =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE;
/** Feature identifier: schema full checking*/
protected static final String SCHEMA_FULL_CHECKING =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING;
/** Feature identifier: dynamic validation. */
protected static final String DYNAMIC_VALIDATION =
Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE;
/** Feature identifier: expose schema normalized value */
protected static final String NORMALIZE_DATA =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE;
/** Feature identifier: send element default value via characters() */
protected static final String SCHEMA_ELEMENT_DEFAULT =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT;
/** Feature identifier: augment PSVI */
protected static final String SCHEMA_AUGMENT_PSVI =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI;
/** Feature identifier: whether to recognize java encoding names */
protected static final String ALLOW_JAVA_ENCODINGS =
Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE;
/** Feature identifier: whether to continue parsing a schema after a fatal error is encountered */
protected static final String CONTINUE_AFTER_FATAL_ERROR =
Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE;
// property identifiers
/** Property identifier: symbol table. */
public static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
public static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: entity resolver. */
public static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
/** Property identifier: grammar pool. */
public static final String XMLGRAMMAR_POOL =
Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
protected static final String VALIDATION_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
protected static final String ENTITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
/** Property identifier: schema location. */
protected static final String SCHEMA_LOCATION =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION;
/** Property identifier: no namespace schema location. */
protected static final String SCHEMA_NONS_LOCATION =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION;
/** Property identifier: JAXP schema source. */
protected static final String JAXP_SCHEMA_SOURCE =
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE;
/** Property identifier: JAXP schema language. */
protected static final String JAXP_SCHEMA_LANGUAGE =
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE;
// recognized features and properties
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
VALIDATION,
SCHEMA_VALIDATION,
DYNAMIC_VALIDATION,
SCHEMA_FULL_CHECKING,
ALLOW_JAVA_ENCODINGS,
CONTINUE_AFTER_FATAL_ERROR,
};
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = {
null,
// NOTE: The following defaults are nulled out on purpose.
// If they are set, then when the XML Schema validator
// is constructed dynamically, these values may override
// those set by the application. This goes against the
// whole purpose of XMLComponent#getFeatureDefault but
// it can't be helped in this case. -Ac
null, //Boolean.FALSE,
null, //Boolean.FALSE,
null, //Boolean.FALSE,
null, //Boolean.FALSE,
null, //Boolean.FALSE,
};
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
ENTITY_RESOLVER,
VALIDATION_MANAGER,
SCHEMA_LOCATION,
SCHEMA_NONS_LOCATION,
JAXP_SCHEMA_SOURCE,
JAXP_SCHEMA_LANGUAGE,
};
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = {
null,
null,
null,
null,
null,
null,
null,
null,
};
// this is the number of valuestores of each kind
// we expect an element to have. It's almost
// never > 1; so leave it at that.
protected static final int ID_CONSTRAINT_NUM = 1;
// Data
/** current PSVI element info */
protected ElementPSVImpl fCurrentPSVI = new ElementPSVImpl();
// since it is the responsibility of each component to an
// Augmentations parameter if one is null, to save ourselves from
// having to create this object continually, it is created here.
// If it is not present in calls that we're passing on, we *must*
// clear this before we introduce it into the pipeline.
protected final AugmentationsImpl fAugmentations = new AugmentationsImpl();
// this is included for the convenience of handleEndElement
protected XMLString fDefaultValue;
// Validation features
protected boolean fDynamicValidation = false;
protected boolean fDoValidation = false;
protected boolean fFullChecking = false;
protected boolean fNormalizeData = true;
protected boolean fSchemaElementDefault = true;
protected boolean fAugPSVI = true;
// to indicate whether we are in the scope of entity reference or CData
protected boolean fEntityRef = false;
protected boolean fInCDATA = false;
// properties
/** Symbol table. */
protected SymbolTable fSymbolTable;
/**
* A wrapper of the standard error reporter. We'll store all schema errors
* in this wrapper object, so that we can get all errors (error codes) of
* a specific element. This is useful for PSVI.
*/
protected final class XSIErrorReporter {
// the error reporter property
XMLErrorReporter fErrorReporter;
// store error codes; starting position of the errors for each element;
// number of element (depth); and whether to record error
Vector fErrors = new Vector(INITIAL_STACK_SIZE, INC_STACK_SIZE);
int[] fContext = new int[INITIAL_STACK_SIZE];
int fContextCount;
// set the external error reporter, clear errors
public void reset(XMLErrorReporter errorReporter) {
fErrorReporter = errorReporter;
fErrors.removeAllElements();
fContextCount = 0;
}
// should be called when starting process an element or an attribute.
// store the starting position for the current context
public void pushContext() {
if (!fAugPSVI)
return;
// resize array if necessary
if (fContextCount == fContext.length) {
int newSize = fContextCount + INC_STACK_SIZE;
int[] newArray = new int[newSize];
System.arraycopy(fContext, 0, newArray, 0, fContextCount);
fContext = newArray;
}
fContext[fContextCount++] = fErrors.size();
}
// should be called on endElement: get all errors of the current element
public String[] popContext() {
if (!fAugPSVI)
return null;
// get starting position of the current element
int contextPos = fContext[--fContextCount];
// number of errors of the current element
int size = fErrors.size() - contextPos;
// if no errors, return null
if (size == 0)
return null;
// copy errors from the list to an string array
String[] errors = new String[size];
for (int i = 0; i < size; i++) {
errors[i] = (String)fErrors.elementAt(contextPos + i);
}
// remove errors of the current element
fErrors.setSize(contextPos);
return errors;
}
// should be called when an attribute is done: get all errors of
// this attribute, but leave the errors to the containing element
public String[] mergeContext() {
if (!fAugPSVI)
return null;
// get starting position of the current element
int contextPos = fContext[--fContextCount];
// number of errors of the current element
int size = fErrors.size() - contextPos;
// if no errors, return null
if (size == 0)
return null;
// copy errors from the list to an string array
String[] errors = new String[size];
for (int i = 0; i < size; i++) {
errors[i] = (String)fErrors.elementAt(contextPos + i);
}
// don't resize the vector: leave the errors for this attribute
// to the containing element
return errors;
}
public void reportError(String domain, String key, Object[] arguments,
short severity) throws XNIException {
fErrorReporter.reportError(domain, key, arguments, severity);
fErrors.addElement(key);
} // reportError(String,String,Object[],short)
public void reportError(XMLLocator location,
String domain, String key, Object[] arguments,
short severity) throws XNIException {
fErrorReporter.reportError(location, domain, key, arguments, severity);
fErrors.addElement(key);
} // reportError(XMLLocator,String,String,Object[],short)
}
/** Error reporter. */
protected final XSIErrorReporter fXSIErrorReporter = new XSIErrorReporter();
/** Entity resolver */
protected XMLEntityResolver fEntityResolver;
// updated during reset
protected ValidationManager fValidationManager = null;
protected ValidationState fValidationState = new ValidationState();
protected XMLGrammarPool fGrammarPool;
// schema location property values
protected String fExternalSchemas = null;
protected String fExternalNoNamespaceSchema = null;
//JAXP Schema Source property
protected Object fJaxpSchemaSource = null ;
//ResourceIdentifier for use in calling EntityResolver
final XMLResourceIdentifierImpl fResourceIdentifier = new XMLResourceIdentifierImpl();
/** Schema Grammar Description passed, to give a chance to application to supply the Grammar */
protected final XSDDescription fXSDDescription = new XSDDescription() ;
protected final Hashtable fLocationPairs = new Hashtable() ;
protected final XMLSchemaLoader.LocationArray fNoNamespaceLocationArray = new XMLSchemaLoader.LocationArray();
/** Base URI for the DOM revalidation*/
protected String fBaseURI = null;
// handlers
/** Document handler. */
protected XMLDocumentHandler fDocumentHandler;
protected XMLDocumentSource fDocumentSource;
// XMLComponent methods
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return (String[])(RECOGNIZED_FEATURES.clone());
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return (String[])(RECOGNIZED_PROPERTIES.clone());
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
} // setProperty(String,Object)
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*
* @param featureId The feature identifier.
*
* @since Xerces 2.2.0
*/
public Boolean getFeatureDefault(String featureId) {
for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return FEATURE_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*
* @param propertyId The property identifier.
*
* @since Xerces 2.2.0
*/
public Object getPropertyDefault(String propertyId) {
for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return PROPERTY_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
// XMLDocumentSource methods
/** Sets the document handler to receive information about the document. */
public void setDocumentHandler(XMLDocumentHandler documentHandler) {
fDocumentHandler = documentHandler;
} // setDocumentHandler(XMLDocumentHandler)
/** Returns the document handler */
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
} // setDocumentHandler(XMLDocumentHandler)
// XMLDocumentHandler methods
/** Sets the document source */
public void setDocumentSource(XMLDocumentSource source){
fDocumentSource = source;
} // setDocumentSource
/** Returns the document source */
public XMLDocumentSource getDocumentSource (){
return fDocumentSource;
} // getDocumentSource
/**
* The start of the document.
*
* @param locator The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param namespaceContext
* The namespace context in effect at the
* start of this document.
* This object represents the current context.
* Implementors of this class are responsible
* for copying the namespace bindings from the
* the current context (and its parent contexts)
* if that information is important.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext namespaceContext, Augmentations augs)
throws XNIException {
fValidationState.setNamespaceSupport(namespaceContext);
fState4XsiType.setNamespaceSupport(namespaceContext);
fState4ApplyDefault.setNamespaceSupport(namespaceContext);
handleStartDocument(locator, encoding);
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startDocument(locator, encoding, namespaceContext, augs);
}
} // startDocument(XMLLocator,String)
/**
* Notifies of the presence of an XMLDecl line in the document. If
* present, this method will be called immediately following the
* startDocument call.
*
* @param version The XML version.
* @param encoding The IANA encoding name of the document, or null if
* not specified.
* @param standalone The standalone value, or null if not specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void xmlDecl(String version, String encoding, String standalone, Augmentations augs)
throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
}
} // xmlDecl(String,String,String)
/**
* Notifies of the presence of the DOCTYPE line in the document.
*
* @param rootElement The name of the root element.
* @param publicId The public identifier if an external DTD or null
* if the external DTD is specified using SYSTEM.
* @param systemId The system identifier if an external DTD, null
* otherwise.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void doctypeDecl(String rootElement, String publicId, String systemId,
Augmentations augs)
throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs);
}
} // doctypeDecl(String,String,String)
/**
* The start of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param uri The URI bound to the prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
if (DEBUG) {
System.out.println("startPrefixMapping("+prefix+","+uri+")");
}
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startPrefixMapping(prefix, uri, augs);
}
} // startPrefixMapping(String,String)
/**
* The start of an element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
Augmentations modifiedAugs = handleStartElement(element, attributes, augs);
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startElement(element, attributes, modifiedAugs );
}
} // startElement(QName,XMLAttributes, Augmentations)
/**
* An empty element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
Augmentations modifiedAugs = handleStartElement(element, attributes, augs);
// in the case where there is a {value constraint}, and the element
// doesn't have any text content, change emptyElement call to
// start + characters + end
fDefaultValue = null;
// fElementDepth == -2 indicates that the schema validator was removed
// from the pipeline. then we don't need to call handleEndElement.
if (fElementDepth != -2)
modifiedAugs = handleEndElement(element, modifiedAugs);
// call handlers
if (fDocumentHandler != null) {
if (!fSchemaElementDefault || fDefaultValue == null) {
fDocumentHandler.emptyElement(element, attributes, modifiedAugs);
} else {
fDocumentHandler.startElement(element, attributes, modifiedAugs);
fDocumentHandler.characters(fDefaultValue, null);
fDocumentHandler.endElement(element, modifiedAugs);
}
}
} // emptyElement(QName,XMLAttributes, Augmentations)
/**
* Character content.
*
* @param text The content.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void characters(XMLString text, Augmentations augs) throws XNIException {
text = handleCharacters(text);
// call handlers
if (fDocumentHandler != null) {
if (fNormalizeData && fUnionType) {
// for union types we can't normalize data
// thus we only need to send augs information if any;
// the normalized data for union will be send
// after normalization is performed (at the endElement())
if (augs != null)
fDocumentHandler.characters(fEmptyXMLStr, augs);
}
else {
fDocumentHandler.characters(text, augs);
}
}
} // characters(XMLString)
/**
* Ignorable whitespace. For this method to be called, the document
* source must have some way of determining that the text containing
* only whitespace characters should be considered ignorable. For
* example, the validator can determine if a length of whitespace
* characters in the document are ignorable based on the element
* content model.
*
* @param text The ignorable whitespace.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
handleIgnorableWhitespace(text);
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.ignorableWhitespace(text, augs);
}
} // ignorableWhitespace(XMLString)
/**
* The end of an element.
*
* @param element The name of the element.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endElement(QName element, Augmentations augs) throws XNIException {
// in the case where there is a {value constraint}, and the element
// doesn't have any text content, add a characters call.
fDefaultValue = null;
Augmentations modifiedAugs = handleEndElement(element, augs);
// call handlers
if (fDocumentHandler != null) {
if (!fSchemaElementDefault || fDefaultValue == null) {
fDocumentHandler.endElement(element, modifiedAugs);
} else {
fDocumentHandler.characters(fDefaultValue, null);
fDocumentHandler.endElement(element, modifiedAugs);
}
}
} // endElement(QName, Augmentations)
/**
* The end of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException {
if (DEBUG) {
System.out.println("endPrefixMapping("+prefix+")");
}
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.endPrefixMapping(prefix, augs);
}
} // endPrefixMapping(String)
/**
* The start of a CDATA section.
*
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startCDATA(Augmentations augs) throws XNIException {
// REVISIT: what should we do here if schema normalization is on??
fInCDATA = true;
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startCDATA(augs);
}
} // startCDATA()
/**
* The end of a CDATA section.
*
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endCDATA(Augmentations augs) throws XNIException {
// call handlers
fInCDATA = false;
if (fDocumentHandler != null) {
fDocumentHandler.endCDATA(augs);
}
} // endCDATA()
/**
* The end of the document.
*
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDocument(Augmentations augs) throws XNIException {
handleEndDocument();
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.endDocument(augs);
}
} // endDocument(Augmentations)
// DOMRevalidationHandler methods
public void setBaseURI (String base){
fBaseURI = base;
}
public boolean characterData(String data, Augmentations augs){
// REVISIT: this methods basically duplicates implementation of
// handleCharacters(). We should be able to reuse some code
// if whitespace == -1 skip normalization, because it is a complexType
// or a union type.
if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) {
// normalize data
normalizeWhitespace(data, fWhiteSpace == XSSimpleType.WS_COLLAPSE);
fBuffer.append(fNormalizedStr.ch, fNormalizedStr.offset, fNormalizedStr.length);
}
else {
fBuffer.append(data);
}
// When it's a complex type with element-only content, we need to
// find out whether the content contains any non-whitespace character.
boolean allWhiteSpace = true;
if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) {
// data outside of element content
for (int i=0; i< data.length(); i++) {
if (!XMLChar.isSpace(data.charAt(i))) {
allWhiteSpace = false;
fSawCharacters = true;
break;
}
}
}
}
// we saw first chunk of characters
fFirstChunk = false;
return allWhiteSpace;
}
public void elementDefault(String data){
// no-op
}
// XMLDocumentHandler and XMLDTDHandler methods
/**
* This method notifies the start of a general entity.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the general entity.
* @param identifier The resource identifier.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException Thrown by handler to signal an error.
*/
public void startGeneralEntity(String name,
XMLResourceIdentifier identifier,
String encoding,
Augmentations augs) throws XNIException {
// REVISIT: what should happen if normalize_data_ is on??
fEntityRef = true;
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs);
}
} // startEntity(String,String,String,String,String)
/**
* Notifies of the presence of a TextDecl line in an entity. If present,
* this method will be called immediately following the startEntity call.
* <p>
* <strong>Note:</strong> This method will never be called for the
* document entity; it is only called for external general entities
* referenced in document content.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param version The XML version, or null if not specified.
* @param encoding The IANA encoding name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void textDecl(String version, String encoding, Augmentations augs) throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.textDecl(version, encoding, augs);
}
} // textDecl(String,String)
/**
* A comment.
*
* @param text The text in the comment.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text, Augmentations augs) throws XNIException {
// record the fact that there is a comment child.
fSawChildren = true;
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.comment(text, augs);
}
} // comment(XMLString)
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
// record the fact that there is a PI child.
fSawChildren = true;
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.processingInstruction(target, data, augs);
}
} // processingInstruction(String,XMLString)
/**
* This method notifies the end of a general entity.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException
* Thrown by handler to signal an error.
*/
public void endGeneralEntity(String name, Augmentations augs) throws XNIException {
// call handlers
fEntityRef = false;
if (fDocumentHandler != null) {
fDocumentHandler.endGeneralEntity(name, augs);
}
} // endEntity(String)
// constants
static final int INITIAL_STACK_SIZE = 8;
static final int INC_STACK_SIZE = 8;
// Data
// Schema Normalization
private static final boolean DEBUG_NORMALIZATION = false;
// temporary empty string buffer.
private final XMLString fEmptyXMLStr = new XMLString(null, 0, -1);
// temporary character buffer, and empty string buffer.
private static final int BUFFER_SIZE = 20;
private final XMLString fNormalizedStr = new XMLString();
private boolean fFirstChunk = true; // got first chunk in characters() (SAX)
private boolean fTrailing = false; // Previous chunk had a trailing space
private short fWhiteSpace = -1; //whiteSpace: preserve/replace/collapse
private boolean fUnionType = false;
/** Schema grammar resolver. */
final XSGrammarBucket fGrammarBucket;
final SubstitutionGroupHandler fSubGroupHandler;
// Schema grammar loader
final XMLSchemaLoader fSchemaLoader;
/** the DV usd to convert xsi:type to a QName */
// REVISIT: in new simple type design, make things in DVs static,
// so that we can QNameDV.getCompiledForm()
final XSSimpleType fQNameDV = (XSSimpleType)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME);
/** used to build content models */
// REVISIT: create decl pool, and pass it to each traversers
final CMBuilder fCMBuilder = new CMBuilder();
// state
/** String representation of the validation root. */
// REVISIT: what do we store here? QName, XPATH, some ID? use rawname now.
String fValidationRoot;
/** Skip validation. */
int fSkipValidationDepth;
/** Partial validation depth */
int fPartialValidationDepth;
/** Element depth: -2: validator not in pipeline; >= -1 current depth. */
int fElementDepth;
/** Child count. */
int fChildCount;
/** Element decl stack. */
int[] fChildCountStack = new int[INITIAL_STACK_SIZE];
/** Current element declaration. */
XSElementDecl fCurrentElemDecl;
/** Element decl stack. */
XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE];
/** nil value of the current element */
boolean fNil;
/** nil value stack */
boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE];
/** notation value of the current element */
XSNotationDecl fNotation;
/** notation stack */
XSNotationDecl[] fNotationStack = new XSNotationDecl[INITIAL_STACK_SIZE];
/** Current type. */
XSTypeDecl fCurrentType;
/** type stack. */
XSTypeDecl[] fTypeStack = new XSTypeDecl[INITIAL_STACK_SIZE];
/** Current content model. */
XSCMValidator fCurrentCM;
/** Content model stack. */
XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE];
/** the current state of the current content model */
int[] fCurrCMState;
/** stack to hold content model states */
int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][];
/** Temporary string buffers. */
final StringBuffer fBuffer = new StringBuffer();
/** Did we see non-whitespace character data? */
boolean fSawCharacters = false;
/** Stack to record if we saw character data outside of element content*/
boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE];
/** Did we see children that are neither characters nor elements? */
boolean fSawChildren = false;
/** Stack to record if we other children that character or elements */
boolean[] fSawChildrenStack = new boolean[INITIAL_STACK_SIZE];
/** temprory qname */
final QName fTempQName = new QName();
/** temprory validated info */
ValidatedInfo fValidatedInfo = new ValidatedInfo();
// used to validate default/fixed values against xsi:type
// only need to check facets, so we set extraChecking to false (in reset)
private ValidationState fState4XsiType = new ValidationState();
// used to apply default/fixed values
// only need to check id/idref/entity, so we set checkFacets to false
private ValidationState fState4ApplyDefault = new ValidationState();
// identity constraint information
/**
* Stack of active XPath matchers for identity constraints. All
* active XPath matchers are notified of startElement
* and endElement callbacks in order to perform their matches.
* <p>
* For each element with identity constraints, the selector of
* each identity constraint is activated. When the selector matches
* its XPath, then all the fields of the identity constraint are
* activated.
* <p>
* <strong>Note:</strong> Once the activation scope is left, the
* XPath matchers are automatically removed from the stack of
* active matchers and no longer receive callbacks.
*/
protected XPathMatcherStack fMatcherStack = new XPathMatcherStack();
/** Cache of value stores for identity constraint fields. */
protected ValueStoreCache fValueStoreCache = new ValueStoreCache();
// Constructors
/** Default constructor. */
public XMLSchemaValidator() {
fGrammarBucket = new XSGrammarBucket();
fSubGroupHandler = new SubstitutionGroupHandler(fGrammarBucket);
// initialize the schema loader
fSchemaLoader = new XMLSchemaLoader(fXSIErrorReporter.fErrorReporter, fGrammarBucket, fSubGroupHandler, fCMBuilder);
fState4XsiType.setExtraChecking(false);
fState4ApplyDefault.setFacetChecking(false);
} // <init>()
/*
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on finitialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager) throws XMLConfigurationException {
// get error reporter
fXSIErrorReporter.reset((XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER));
fSchemaLoader.setProperty(ERROR_REPORTER, fXSIErrorReporter.fErrorReporter);
// get symbol table. if it's a new one, add symbols to it.
SymbolTable symbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
if (symbolTable != fSymbolTable) {
fSchemaLoader.setProperty(SYMBOL_TABLE, symbolTable);
fSymbolTable = symbolTable;
}
try {
fDynamicValidation = componentManager.getFeature(DYNAMIC_VALIDATION);
}
catch (XMLConfigurationException e) {
fDynamicValidation = false;
}
if (fDynamicValidation) {
fDoValidation = true;
}
else {
try {
fDoValidation = componentManager.getFeature(VALIDATION);
}
catch (XMLConfigurationException e) {
fDoValidation = false;
}
}
if (fDoValidation) {
try {
fDoValidation = componentManager.getFeature(this.SCHEMA_VALIDATION);
}
catch (XMLConfigurationException e) {
}
}
try {
fFullChecking = componentManager.getFeature(SCHEMA_FULL_CHECKING);
}
catch (XMLConfigurationException e) {
fFullChecking = false;
}
// the validator will do full checking anyway; the loader should
// not (and in fact cannot) concern itself with this.
fSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, false);
try {
fNormalizeData = componentManager.getFeature(NORMALIZE_DATA);
}
catch (XMLConfigurationException e) {
fNormalizeData = false;
}
try {
fSchemaElementDefault = componentManager.getFeature(SCHEMA_ELEMENT_DEFAULT);
}
catch (XMLConfigurationException e) {
fSchemaElementDefault = false;
}
try {
fAugPSVI = componentManager.getFeature(SCHEMA_AUGMENT_PSVI);
}
catch (XMLConfigurationException e) {
fAugPSVI = true;
}
fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_MANAGER);
fSchemaLoader.setEntityResolver(fEntityResolver);
fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER);
fValidationManager.addValidationState(fValidationState);
fValidationState.setSymbolTable(fSymbolTable);
//reset XSDDescription
fLocationPairs.clear();
fNoNamespaceLocationArray.resize(0 , 2) ;
// get schema location properties
try {
fExternalSchemas = (String)componentManager.getProperty(SCHEMA_LOCATION);
fExternalNoNamespaceSchema = (String)componentManager.getProperty(SCHEMA_NONS_LOCATION);
}
catch (XMLConfigurationException e) {
fExternalSchemas = null;
fExternalNoNamespaceSchema = null;
}
fSchemaLoader.setProperty(SCHEMA_LOCATION, fExternalSchemas);
fSchemaLoader.setProperty(SCHEMA_NONS_LOCATION, fExternalNoNamespaceSchema);
// store the external schema locations. they are set when reset is called,
// so any other schemaLocation declaration for the same namespace will be
// effectively ignored. becuase we choose to take first location hint
// available for a particular namespace.
storeLocations(fExternalSchemas, fExternalNoNamespaceSchema) ;
try {
fJaxpSchemaSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE);
}
catch (XMLConfigurationException e){
fJaxpSchemaSource = null;
}
fSchemaLoader.setProperty(JAXP_SCHEMA_SOURCE, fJaxpSchemaSource);
fResourceIdentifier.clear();
// clear grammars, and put the one for schema namespace there
try {
fGrammarPool = (XMLGrammarPool)componentManager.getProperty(XMLGRAMMAR_POOL);
}
catch (XMLConfigurationException e){
fGrammarPool = null;
}
fSchemaLoader.setProperty(XMLGRAMMAR_POOL, fGrammarPool);
// Copy the allow-java-encoding feature to the grammar loader.
// REVISIT: what other fetures/properties do we want to copy?
try {
boolean allowJavaEncodings = componentManager.getFeature(ALLOW_JAVA_ENCODINGS);
fSchemaLoader.setFeature(ALLOW_JAVA_ENCODINGS, allowJavaEncodings);
}
catch (XMLConfigurationException e){
}
// get continue-after-fatal-error feature
try {
boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR);
fSchemaLoader.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError);
}
catch (XMLConfigurationException e){
}
// clear grammars, and put the one for schema namespace there
// logic for resetting grammar-related components moved
// to schema loader
fSchemaLoader.reset();
// initialize state
fCurrentElemDecl = null;
fCurrentCM = null;
fCurrCMState = null;
fSkipValidationDepth = -1;
fPartialValidationDepth = -1;
fElementDepth = -1;
fChildCount = 0;
// datatype normalization
fEntityRef = false;
fInCDATA = false;
fMatcherStack.clear();
fBaseURI = null;
fState4XsiType.setSymbolTable(symbolTable);
fState4ApplyDefault.setSymbolTable(symbolTable);
} // reset(XMLComponentManager)
// FieldActivator methods
/**
* Start the value scope for the specified identity constraint. This
* method is called when the selector matches in order to initialize
* the value store.
*
* @param identityConstraint The identity constraint.
*/
public void startValueScopeFor(IdentityConstraint identityConstraint,
int initialDepth)
throws XNIException {
ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth);
valueStore.startValueScope();
} // startValueScopeFor(IdentityConstraint identityConstraint)
/**
* Request to activate the specified field. This method returns the
* matcher for the field.
*
* @param field The field to activate.
*/
public XPathMatcher activateField(Field field, int initialDepth) {
ValueStore valueStore = fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth);
field.setMayMatch(true);
XPathMatcher matcher = field.createMatcher(valueStore);
fMatcherStack.addMatcher(matcher);
matcher.startDocumentFragment(fSymbolTable);
return matcher;
} // activateField(Field):XPathMatcher
/**
* Ends the value scope for the specified identity constraint.
*
* @param identityConstraint The identity constraint.
*/
public void endValueScopeFor(IdentityConstraint identityConstraint, int initialDepth)
throws XNIException {
ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth);
valueStore.endValueScope();
} // endValueScopeFor(IdentityConstraint)
// a utility method for Idnetity constraints
private void activateSelectorFor(IdentityConstraint ic) throws XNIException {
Selector selector = ic.getSelector();
FieldActivator activator = this;
if (selector == null)
return;
XPathMatcher matcher = selector.createMatcher(activator, fElementDepth);
fMatcherStack.addMatcher(matcher);
matcher.startDocumentFragment(fSymbolTable);
}
// Protected methods
/** ensure element stack capacity */
void ensureStackCapacity() {
if (fElementDepth == fElemDeclStack.length) {
int newSize = fElementDepth + INC_STACK_SIZE;
int[] newArrayI = new int[newSize];
System.arraycopy(fChildCountStack, 0, newArrayI, 0, fElementDepth);
fChildCountStack = newArrayI;
XSElementDecl[] newArrayE = new XSElementDecl[newSize];
System.arraycopy(fElemDeclStack, 0, newArrayE, 0, fElementDepth);
fElemDeclStack = newArrayE;
boolean[] newArrayB = new boolean[newSize];
System.arraycopy(fNilStack, 0, newArrayB, 0, fElementDepth);
fNilStack = newArrayB;
XSNotationDecl[] newArrayN = new XSNotationDecl[newSize];
System.arraycopy(fNotationStack, 0, newArrayN, 0, fElementDepth);
fNotationStack = newArrayN;
XSTypeDecl[] newArrayT = new XSTypeDecl[newSize];
System.arraycopy(fTypeStack, 0, newArrayT, 0, fElementDepth);
fTypeStack = newArrayT;
XSCMValidator[] newArrayC = new XSCMValidator[newSize];
System.arraycopy(fCMStack, 0, newArrayC, 0, fElementDepth);
fCMStack = newArrayC;
boolean[] newArrayD = new boolean[newSize];
System.arraycopy(fStringContent, 0, newArrayD, 0, fElementDepth);
fStringContent = newArrayD;
newArrayD = new boolean[newSize];
System.arraycopy(fSawChildrenStack, 0, newArrayD, 0, fElementDepth);
fSawChildrenStack = newArrayD;
int[][] newArrayIA = new int[newSize][];
System.arraycopy(fCMStateStack, 0, newArrayIA, 0, fElementDepth);
fCMStateStack = newArrayIA;
}
} // ensureStackCapacity
// handle start document
void handleStartDocument(XMLLocator locator, String encoding) {
fValueStoreCache.startDocument();
} // handleStartDocument(XMLLocator,String)
void handleEndDocument() {
fValueStoreCache.endDocument();
} // handleEndDocument()
// handle character contents
// returns the normalized string if possible, otherwise the original string
XMLString handleCharacters(XMLString text) {
if (fSkipValidationDepth >= 0)
return text;
// Note: data in EntityRef and CDATA is normalized as well
// if whitespace == -1 skip normalization, because it is a complexType
// or a union type.
if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) {
// normalize data
normalizeWhitespace(text, fWhiteSpace == XSSimpleType.WS_COLLAPSE);
text = fNormalizedStr;
}
fBuffer.append(text.ch, text.offset, text.length);
// When it's a complex type with element-only content, we need to
// find out whether the content contains any non-whitespace character.
if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) {
// data outside of element content
for (int i=text.offset; i< text.offset+text.length; i++) {
if (!XMLChar.isSpace(text.ch[i])) {
fSawCharacters = true;
break;
}
}
}
}
// we saw first chunk of characters
fFirstChunk = false;
return text;
} // handleCharacters(XMLString)
/**
* Normalize whitespace in an XMLString according to the rules defined
* in XML Schema specifications.
* @param value The string to normalize.
* @param collapse replace or collapse
*/
private void normalizeWhitespace( XMLString value, boolean collapse) {
boolean skipSpace = collapse;
boolean sawNonWS = false;
int leading = 0;
int trailing = 0;
char c;
int size = value.offset+value.length;
// ensure the ch array is big enough
if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < value.length+1) {
fNormalizedStr.ch = new char[value.length+1];
}
// don't include the leading ' ' for now. might include it later.
fNormalizedStr.offset = 1;
fNormalizedStr.length = 1;
for (int i = value.offset; i < size; i++) {
c = value.ch[i];
if (XMLChar.isSpace(c)) {
if (!skipSpace) {
// take the first whitespace as a space and skip the others
fNormalizedStr.ch[fNormalizedStr.length++] = ' ';
skipSpace = collapse;
}
if (!sawNonWS) {
// this is a leading whitespace, record it
leading = 1;
}
}
else {
fNormalizedStr.ch[fNormalizedStr.length++] = c;
skipSpace = false;
sawNonWS = true;
}
}
if (skipSpace) {
if ( fNormalizedStr.length > 1) {
// if we finished on a space trim it but also record it
fNormalizedStr.length
trailing = 2;
}
else if (leading != 0 && !sawNonWS) {
// if all we had was whitespace we skipped record it as
// trailing whitespace as well
trailing = 2;
}
}
// 0 if no triming is done or if there is neither leading nor
// trailing whitespace,
// 1 if there is only leading whitespace,
// 2 if there is only trailing whitespace,
// 3 if there is both leading and trailing whitespace.
int spaces = collapse ? leading + trailing : 0;
if (fNormalizedStr.length > 1) {
if (!fFirstChunk && (fWhiteSpace==XSSimpleType.WS_COLLAPSE) ) {
if (fTrailing) {
// previous chunk ended on whitespace
// insert whitespace
fNormalizedStr.offset = 0;
fNormalizedStr.ch[0] = ' ';
} else if (spaces == 1 || spaces == 3) {
// previous chunk ended on character,
// this chunk starts with whitespace
fNormalizedStr.offset = 0;
fNormalizedStr.ch[0] = ' ';
}
}
}
// The length includes the leading ' '. Now removing it.
fNormalizedStr.length -= fNormalizedStr.offset;
fTrailing = (spaces > 1)?true:false;
}
private void normalizeWhitespace( String value, boolean collapse) {
boolean skipSpace = collapse;
char c;
int size = value.length();
// ensure the ch array is big enough
if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < size) {
fNormalizedStr.ch = new char[size];
}
fNormalizedStr.offset = 0;
fNormalizedStr.length = 0;
for (int i = 0; i < size; i++) {
c = value.charAt(i);
if (XMLChar.isSpace(c)) {
if (!skipSpace) {
// take the first whitespace as a space and skip the others
fNormalizedStr.ch[fNormalizedStr.length++] = ' ';
skipSpace = collapse;
}
}
else {
fNormalizedStr.ch[fNormalizedStr.length++] = c;
skipSpace = false;
}
}
if (skipSpace) {
if (fNormalizedStr.length != 0)
// if we finished on a space trim it but also record it
fNormalizedStr.length
}
}
// handle ignorable whitespace
void handleIgnorableWhitespace(XMLString text) {
if (fSkipValidationDepth >= 0)
return;
// REVISIT: the same process needs to be performed as handleCharacters.
// only it's simpler here: we know all characters are whitespaces.
} // handleIgnorableWhitespace(XMLString)
/** Handle element. */
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) {
if (DEBUG) {
System.out.println("==>handleStartElement: " +element);
}
// root element
if (fElementDepth == -1 && fValidationManager.isGrammarFound()) {
// if a DTD grammar is found, we do the same thing as Dynamic:
// if a schema grammar is found, validation is performed;
// otherwise, skip the whole document.
fDynamicValidation = true;
}
// get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes,
// parse them to get the grammars
String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION);
String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
//store the location hints.. we need to do it so that we can defer the loading of grammar until
//there is a reference to a component from that namespace. To provide location hints to the
//application for a namespace
storeLocations(sLocation, nsLocation) ;
// if we are in the content of "skip", then just skip this element
// REVISIT: is this the correct behaviour for ID constraints? -NG
if (fSkipValidationDepth >= 0) {
fElementDepth++;
if (fAugPSVI)
augs = getEmptyAugs(augs);
return augs;
}
//try to find schema grammar by different means..
SchemaGrammar sGrammar = findSchemaGrammar(XSDDescription.CONTEXT_ELEMENT,
element.uri, null,
element, attributes);
// if we are not skipping this element, and there is a content model,
// we try to find the corresponding decl object for this element.
// the reason we move this part of code here is to make sure the
// error reported here (if any) is stored within the parent element's
// context, instead of that of the current element.
Object decl = null;
if (fCurrentCM != null) {
decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler);
// it could be an element decl or a wildcard decl
if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
//REVISIT: is it the only case we will have particle = null?
if (ctype.fParticle != null) {
reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, ctype.fParticle.toString()});
}
else {
reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, "mixed with no element content"});
}
}
}
// push error reporter context: record the current position
fXSIErrorReporter.pushContext();
// if it's not the root element, we push the current states in the stacks
if (fElementDepth != -1) {
ensureStackCapacity();
fChildCountStack[fElementDepth] = fChildCount+1;
fChildCount = 0;
fElemDeclStack[fElementDepth] = fCurrentElemDecl;
fNilStack[fElementDepth] = fNil;
fNotationStack[fElementDepth] = fNotation;
fTypeStack[fElementDepth] = fCurrentType;
fCMStack[fElementDepth] = fCurrentCM;
fCMStateStack[fElementDepth] = fCurrCMState;
fStringContent[fElementDepth] = fSawCharacters;
fSawChildrenStack[fElementDepth] = fSawChildren;
}
// increase the element depth after we've saved
// all states for the parent element
fElementDepth++;
fCurrentElemDecl = null;
XSWildcardDecl wildcard = null;
fCurrentType = null;
fNil = false;
fNotation = null;
// and the buffer to hold the value of the element
fBuffer.setLength(0);
fSawCharacters = false;
fSawChildren = false;
// check what kind of declaration the "decl" from
// oneTransition() maps to
if (decl != null) {
if (decl instanceof XSElementDecl) {
fCurrentElemDecl = (XSElementDecl)decl;
}
else {
wildcard = (XSWildcardDecl)decl;
}
}
// if the wildcard is skip, then return
if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) {
fSkipValidationDepth = fElementDepth;
if (fAugPSVI)
augs = getEmptyAugs(augs);
return augs;
}
// try again to get the element decl:
// case 1: find declaration for root element
// case 2: find declaration for element from another namespace
if (fCurrentElemDecl == null) {
if (sGrammar != null){
fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart);
}
}
// Element Locally Valid (Element)
// 2 Its {abstract} must be false.
if (fCurrentElemDecl != null && fCurrentElemDecl.getIsAbstract())
reportSchemaError("cvc-elt.2", new Object[]{element.rawname});
if (fCurrentElemDecl != null) {
// then get the type
fCurrentType = fCurrentElemDecl.fType;
}
// get type from xsi:type
String xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE);
if (xsiType != null)
fCurrentType = getAndCheckXsiType(element, xsiType, attributes);
// if the element decl is not found
if (fCurrentType == null) {
// if this is the validation root, report an error, because
// we can't find eith decl or type for this element
// REVISIT: should we report error, or warning?
if (fElementDepth == 0) {
// for dynamic validation, skip the whole content,
// because no grammar was found.
if (fDynamicValidation) {
// no schema grammar was found, but it's either dynamic
// validation, or another kind of grammar was found (DTD,
// for example). The intended behavior here is to skip
// the whole document. To improve performance, we try to
// remove the validator from the pipeline, since it's not
// supposed to do anything.
if (fDocumentSource != null) {
fDocumentSource.setDocumentHandler(fDocumentHandler);
if (fDocumentHandler != null)
fDocumentHandler.setDocumentSource(fDocumentSource);
// indicate that the validator was removed.
fElementDepth = -2;
return augs;
}
fSkipValidationDepth = fElementDepth;
if (fAugPSVI)
augs = getEmptyAugs(augs);
return augs;
}
// report error, because it's root element
reportSchemaError("cvc-elt.1", new Object[]{element.rawname});
}
// if wildcard = strict, report error
else if (wildcard != null &&
wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) {
// report error, because wilcard = strict
reportSchemaError("cvc-complex-type.2.4.c", new Object[]{element.rawname});
}
// no element decl or type found for this element.
// Allowed by the spec, we can choose to either laxly assess this
// element, or to skip it. Now we choose lax assessment.
fCurrentType = SchemaGrammar.fAnyType;
}
// make the current element validation root
if (fElementDepth == 0) {
fValidationRoot = element.rawname;
}
// update normalization flags
if (fNormalizeData) {
// reset values
fFirstChunk = true;
fTrailing = false;
fUnionType = false;
fWhiteSpace = -1;
}
// Element Locally Valid (Type)
// 2 Its {abstract} must be false.
if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
if (ctype.getIsAbstract()) {
reportSchemaError("cvc-type.2", new Object[]{"Element " + element.rawname + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"});
}
if (fNormalizeData) {
// find out if the content type is simple and if variety is union
// to be able to do character normalization
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) {
if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) {
fUnionType = true;
} else {
try {
fWhiteSpace = ctype.fXSSimpleType.getWhitespace();
} catch (DatatypeException e){
// do nothing
}
}
}
}
}
// normalization: simple type
else if (fNormalizeData) {
// if !union type
XSSimpleType dv = (XSSimpleType)fCurrentType;
if (dv.getVariety() == XSSimpleType.VARIETY_UNION) {
fUnionType = true;
} else {
try {
fWhiteSpace = dv.getWhitespace();
} catch (DatatypeException e){
// do nothing
}
}
}
// then try to get the content model
fCurrentCM = null;
if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) {
fCurrentCM = ((XSComplexTypeDecl)fCurrentType).getContentModel(fCMBuilder);
}
// and get the initial content model state
fCurrCMState = null;
if (fCurrentCM != null)
fCurrCMState = fCurrentCM.startContentModel();
// get information about xsi:nil
String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL);
// only deal with xsi:nil when there is an element declaration
if (xsiNil != null && fCurrentElemDecl != null)
fNil = getXsiNil(element, xsiNil);
// now validate everything related with the attributes
// first, get the attribute group
XSAttributeGroupDecl attrGrp = null;
if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
attrGrp = ctype.getAttrGrp();
}
processAttributes(element, attributes, attrGrp);
// add default attributes
if (attrGrp != null) {
addDefaultAttributes(element, attributes, attrGrp);
}
// activate identity constraints
fValueStoreCache.startElement();
fMatcherStack.pushContext();
if (fCurrentElemDecl != null) {
fValueStoreCache.initValueStoresFor(fCurrentElemDecl);
int icCount = fCurrentElemDecl.fIDCPos;
int uniqueOrKey = 0;
for (;uniqueOrKey < icCount; uniqueOrKey++) {
if (fCurrentElemDecl.fIDConstraints[uniqueOrKey].getCategory() != IdentityConstraint.IC_KEYREF) {
activateSelectorFor(fCurrentElemDecl.fIDConstraints[uniqueOrKey]);
}
else
break;
}
for (int keyref = uniqueOrKey; keyref < icCount; keyref++) {
activateSelectorFor((IdentityConstraint)fCurrentElemDecl.fIDConstraints[keyref]);
}
}
// call all active identity constraints
int count = fMatcherStack.getMatcherCount();
for (int i = 0; i < count; i++) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.startElement(element, attributes, fCurrentElemDecl);
}
if (fAugPSVI) {
augs = getEmptyAugs(augs);
// PSVI: add validation context
fCurrentPSVI.fValidationContext = fValidationRoot;
// PSVI: add element declaration
fCurrentPSVI.fDeclaration = fCurrentElemDecl;
// PSVI: add element type
fCurrentPSVI.fTypeDecl = fCurrentType;
// PSVI: add notation attribute
fCurrentPSVI.fNotation = fNotation;
}
return augs;
} // handleStartElement(QName,XMLAttributes,boolean)
/**
* Handle end element. If there is not text content, and there is a
* {value constraint} on the corresponding element decl, then
* set the fDefaultValue XMLString representing the default value.
*/
Augmentations handleEndElement(QName element, Augmentations augs) {
if (DEBUG) {
System.out.println("==>handleEndElement:" +element);
}
// if we are skipping, return
if (fSkipValidationDepth >= 0) {
// but if this is the top element that we are skipping,
// restore the states.
if (fSkipValidationDepth == fElementDepth &&
fSkipValidationDepth > 0) {
// set the partial validation depth to the depth of parent
fPartialValidationDepth = fSkipValidationDepth-1;
fSkipValidationDepth = -1;
fElementDepth
fChildCount = fChildCountStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fNotation = fNotationStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
fSawChildren = fSawChildrenStack[fElementDepth];
}
else {
fElementDepth
}
// PSVI: validation attempted:
// use default values in psvi item for
// validation attempted, validity, and error codes
// check extra schema constraints on root element
if (fElementDepth == -1 && fFullChecking) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter);
}
if (fAugPSVI)
augs = getEmptyAugs(augs);
return augs;
}
// now validate the content of the element
processElementContent(element);
// Element Locally Valid (Element)
// 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4).
// call matchers and de-activate context
int oldCount = fMatcherStack.getMatcherCount();
for (int i = oldCount - 1; i >= 0; i
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.endElement(element, fCurrentElemDecl,
fDefaultValue == null ?
fValidatedInfo.normalizedValue :
fCurrentElemDecl.fDefault.normalizedValue);
}
if (fMatcherStack.size() > 0) {
fMatcherStack.popContext();
}
int newCount = fMatcherStack.getMatcherCount();
// handle everything *but* keyref's.
for (int i = oldCount - 1; i >= newCount; i
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
if(matcher instanceof Selector.Matcher) {
Selector.Matcher selMatcher = (Selector.Matcher)matcher;
IdentityConstraint id;
if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) {
fValueStoreCache.transplant(id, selMatcher.getInitialDepth());
}
}
}
// now handle keyref's/...
for (int i = oldCount - 1; i >= newCount; i
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
if(matcher instanceof Selector.Matcher) {
Selector.Matcher selMatcher = (Selector.Matcher)matcher;
IdentityConstraint id;
if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) {
ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth());
if (values != null) // nothing to do if nothing matched!
values.endDocumentFragment();
}
}
}
fValueStoreCache.endElement();
// decrease element depth and restore states
fElementDepth
SchemaGrammar[] grammars = null;
// have we reached the end tag of the validation root?
if (fElementDepth == -1) {
// 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4).
String invIdRef = fValidationState.checkIDRefID();
if (invIdRef != null) {
reportSchemaError("cvc-id.1", new Object[]{invIdRef});
}
// check extra schema constraints
if (fFullChecking) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter);
}
fValidationState.resetIDTables();
grammars = fGrammarBucket.getGrammars();
// return the final set of grammars validator ended up with
if (fGrammarPool != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars);
}
}
else {
// get the states for the parent element.
fChildCount = fChildCountStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fNotation = fNotationStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
fSawChildren = fSawChildrenStack[fElementDepth];
}
if (fAugPSVI) {
augs = getEmptyAugs(augs);
// the 4 properties sent on startElement calls
fCurrentPSVI.fDeclaration = this.fCurrentElemDecl;
fCurrentPSVI.fTypeDecl = this.fCurrentType;
fCurrentPSVI.fNotation = this.fNotation;
fCurrentPSVI.fValidationContext = this.fValidationRoot;
// PSVI: validation attempted
if (fElementDepth <= fPartialValidationDepth) {
// the element had child with a content skip.
fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_PARTIAL;
if (fElementDepth == fPartialValidationDepth) {
// set depth to the depth of the parent
fPartialValidationDepth
}
}
else {
fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_FULL;
}
if (fDefaultValue != null)
fCurrentPSVI.fSpecified = true;
fCurrentPSVI.fNil = fNil;
fCurrentPSVI.fMemberType = fValidatedInfo.memberType;
fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue;
// pop error reporter context: get all errors for the current
// element, and remove them from the error list
String[] errors = fXSIErrorReporter.popContext();
// PSVI: error codes
fCurrentPSVI.fErrorCodes = errors;
// PSVI: validity
fCurrentPSVI.fValidity = (errors == null) ?
ElementPSVI.VALIDITY_VALID :
ElementPSVI.VALIDITY_INVALID;
if (fElementDepth == -1) {
// store [schema information] in the PSVI
fCurrentPSVI.fSchemaInformation = new XSModelImpl(grammars);
}
}
return augs;
} // handleEndElement(QName,boolean)*/
Augmentations getEmptyAugs(Augmentations augs) {
if (augs == null) {
augs = fAugmentations;
augs.clear();
}
augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI);
fCurrentPSVI.reset();
return augs;
}
void storeLocations(String sLocation, String nsLocation){
if (sLocation != null) {
if(!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs)) { // error!
fXSIErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"SchemaLocation",
new Object[]{sLocation},
XMLErrorReporter.SEVERITY_WARNING);
}
}
if (nsLocation != null) {
fNoNamespaceLocationArray.addLocation(nsLocation);
fLocationPairs.put(XMLSymbols.EMPTY_STRING, fNoNamespaceLocationArray);
}
}//storeLocations
//this is the function where logic of retrieving grammar is written , parser first tries to get the grammar from
//the local pool, if not in local pool, it gives chance to application to be able to retrieve the grammar, then it
//tries to parse the grammar using location hints from the give namespace.
SchemaGrammar findSchemaGrammar(short contextType , String namespace , QName enclosingElement, QName triggeringComponet, XMLAttributes attributes ){
SchemaGrammar grammar = null ;
//get the grammar from local pool...
grammar = fGrammarBucket.getGrammar(namespace);
if (grammar == null){
fXSDDescription.reset();
fXSDDescription.fContextType = contextType ;
fXSDDescription.fTargetNamespace = namespace ;
fXSDDescription.fEnclosedElementName = enclosingElement ;
fXSDDescription.fTriggeringComponent = triggeringComponet ;
fXSDDescription.fAttributes = attributes ;
if (fBaseURI != null) {
fXSDDescription.setBaseSystemId(fBaseURI);
}
String[] temp = null ;
if( namespace != null){
Object locationArray = fLocationPairs.get(namespace) ;
if(locationArray != null)
temp = ((XMLSchemaLoader.LocationArray)locationArray).getLocationArray() ;
}else{
temp = fNoNamespaceLocationArray.getLocationArray() ;
}
if (temp != null && temp.length != 0) {
fXSDDescription.fLocationHints = new String [temp.length] ;
System.arraycopy(temp, 0 , fXSDDescription.fLocationHints, 0, temp.length );
}
// give a chance to application to be able to retreive the grammar.
if (fGrammarPool != null){
grammar = (SchemaGrammar)fGrammarPool.retrieveGrammar(fXSDDescription);
if (grammar != null) {
// put this grammar into the bucket, along with grammars
// imported by it (directly or indirectly)
if (!fGrammarBucket.putGrammar(grammar, true)) {
// REVISIT: a conflict between new grammar(s) and grammars
// in the bucket. What to do? A warning? An exception?
fXSIErrorReporter.fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"GrammarConflict", null,
XMLErrorReporter.SEVERITY_WARNING);
grammar = null;
}
}
}
if (grammar == null) {
// try to parse the grammar using location hints from that namespace..
try {
XMLInputSource xis = XMLSchemaLoader.resolveDocument(fXSDDescription, fLocationPairs, fEntityResolver);
grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs);
} catch (IOException ex) {
fXSIErrorReporter.fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"schema_reference.4",
new Object[]{fXSDDescription.getLocationHints()[0]},
XMLErrorReporter.SEVERITY_WARNING);
}
}
}
return grammar ;
}//findSchemaGrammar
XSTypeDecl getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) {
// This method also deals with clause 1.2.1.2 of the constraint
// Validation Rule: Schema-Validity Assessment (Element)
// Element Locally Valid (Element)
// 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4);
QName typeName = null;
try {
typeName = (QName)fQNameDV.validate(xsiType, fValidationState, null);
}
catch (InvalidDatatypeValueException e) {
reportSchemaError(e.getKey(), e.getArgs());
reportSchemaError("cvc-elt.4.1", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_TYPE, xsiType});
return null;
}
// 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4)
XSTypeDecl type = null;
// if the namespace is schema namespace, first try built-in types
if (typeName.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
type = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(typeName.localpart);
}
// if it's not schema built-in types, then try to get a grammar
if (type == null) {
//try to find schema grammar by different means....
SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_XSITYPE , typeName.uri , element , typeName , attributes);
if (grammar != null)
type = grammar.getGlobalTypeDecl(typeName.localpart);
}
// still couldn't find the type, report an error
if (type == null) {
reportSchemaError("cvc-elt.4.2", new Object[]{element.rawname, xsiType});
return null;
}
// if there is no current type, set this one as current.
// and we don't need to do extra checking
if (fCurrentType != null) {
// 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition).
short block = fCurrentElemDecl.fBlock;
if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE)
block |= ((XSComplexTypeDecl)fCurrentType).fBlock;
if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block))
reportSchemaError("cvc-elt.4.3", new Object[]{element.rawname, xsiType});
}
return type;
}//getAndCheckXsiType
boolean getXsiNil(QName element, String xsiNil) {
// Element Locally Valid (Element)
// 3 The appropriate case among the following must be true:
if (fCurrentElemDecl != null && !fCurrentElemDecl.getIsNillable()) {
reportSchemaError("cvc-elt.3.1", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_NIL});
}
// 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true:
// 3.2.2 There must be no fixed {value constraint}.
else {
String value = xsiNil.trim();
if (value.equals(SchemaSymbols.ATTVAL_TRUE) ||
value.equals(SchemaSymbols.ATTVAL_TRUE_1)) {
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) {
reportSchemaError("cvc-elt.3.2.2", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_NIL});
}
return true;
}
}
return false;
}
void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) {
if (DEBUG) {
System.out.println("==>processAttributes: " +attributes.getLength());
}
// whether we have seen a Wildcard ID.
String wildcardIDName = null;
// for each present attribute
int attCount = attributes.getLength();
Augmentations augs = null;
AttributePSVImpl attrPSVI = null;
boolean isSimple = fCurrentType == null ||
fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE;
XSObjectList attrUses = null;
int useCount = 0;
XSWildcardDecl attrWildcard = null;
if (!isSimple) {
attrUses = attrGrp.getAttributeUses();
useCount = attrUses.getLength();
attrWildcard = attrGrp.fAttributeWC;
}
// Element Locally Valid (Complex Type)
// get the corresponding attribute decl
for (int index = 0; index < attCount; index++) {
attributes.getName(index, fTempQName);
if (DEBUG) {
System.out.println("==>process attribute: "+fTempQName);
}
if (fAugPSVI) {
augs = attributes.getAugmentations(index);
attrPSVI = (AttributePSVImpl) augs.getItem(Constants.ATTRIBUTE_PSVI);
if (attrPSVI != null) {
attrPSVI.reset();
} else {
attrPSVI= new AttributePSVImpl();
augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI);
}
// PSVI attribute: validation context
attrPSVI.fValidationContext = fValidationRoot;
}
// Element Locally Valid (Type)
// 3.1.1 The element information item's [attributes] must be empty, excepting those
// whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation.
// for the 4 xsi attributes, get appropriate decl, and validate
if (fTempQName.uri == SchemaSymbols.URI_XSI) {
XSAttributeDecl attrDecl = null;
if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION)
attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);
else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION)
attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
else if (fTempQName.localpart == SchemaSymbols.XSI_NIL)
attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL);
else if (fTempQName.localpart == SchemaSymbols.XSI_TYPE)
attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE);
if (attrDecl != null) {
processOneAttribute(element, attributes, index,
attrDecl, null, attrPSVI);
continue;
}
}
// for namespace attributes, no_validation/unknow_validity
if (fTempQName.rawname == XMLSymbols.PREFIX_XMLNS || fTempQName.rawname.startsWith("xmlns:")) {
continue;
}
// simple type doesn't allow any other attributes
if (isSimple) {
reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname});
continue;
}
// it's not xmlns, and not xsi, then we need to find a decl for it
XSAttributeUseImpl currUse = null, oneUse;
for (int i = 0; i < useCount; i++) {
oneUse = (XSAttributeUseImpl)attrUses.getItem(i);
if (oneUse.fAttrDecl.fName == fTempQName.localpart &&
oneUse.fAttrDecl.fTargetNamespace == fTempQName.uri) {
currUse = oneUse;
break;
}
}
// 3.2 otherwise all of the following must be true:
// 3.2.1 There must be an {attribute wildcard}.
// 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4).
// if failed, get it from wildcard
if (currUse == null) {
//if (attrWildcard == null)
// reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname});
if (attrWildcard == null ||
!attrWildcard.allowNamespace(fTempQName.uri)) {
// so this attribute is not allowed
reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname});
continue;
}
}
XSAttributeDecl currDecl = null;
if (currUse != null) {
currDecl = currUse.fAttrDecl;
}
else {
// which means it matches a wildcard
// skip it if processContents is skip
if (attrWildcard.fProcessContents == XSWildcardDecl.PC_SKIP)
continue;
//try to find grammar by different means...
SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE , fTempQName.uri , element , fTempQName , attributes);
if (grammar != null){
currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart);
}
// if can't find
if (currDecl == null) {
// if strict, report error
if (attrWildcard.fProcessContents == XSWildcardDecl.PC_STRICT){
reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname});
}
// then continue to the next attribute
continue;
}
else {
// 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true:
// 5.1 There must be no more than one item in wild IDs.
if (currDecl.fType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE &&
((XSSimpleType)currDecl.fType).isIDType()) {
if (wildcardIDName != null){
reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName});
}
else
wildcardIDName = currDecl.fName;
}
}
}
processOneAttribute(element, attributes, index,
currDecl, currUse, attrPSVI);
} // end of for (all attributes)
// 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID.
if (!isSimple && attrGrp.fIDAttrName != null && wildcardIDName != null){
reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName});
}
} //processAttributes
void processOneAttribute(QName element, XMLAttributes attributes, int index,
XSAttributeDecl currDecl, XSAttributeUseImpl currUse,
AttributePSVImpl attrPSVI) {
String attrValue = attributes.getValue(index);
fXSIErrorReporter.pushContext();
// Attribute Locally Valid
// For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true:
// 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case).
// 2 Its {type definition} must not be absent.
// 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4).
// get simple type
XSSimpleType attDV = currDecl.fType;
Object actualValue = null;
try {
actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo);
// store the normalized value
if (fNormalizeData)
attributes.setValue(index, fValidatedInfo.normalizedValue);
if (attributes instanceof XMLAttributesImpl) {
XMLAttributesImpl attrs = (XMLAttributesImpl)attributes;
boolean schemaId = fValidatedInfo.memberType != null ?
fValidatedInfo.memberType.isIDType() :
attDV.isIDType();
attrs.setSchemaId(index, schemaId);
}
// PSVI: element notation
if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC &&
attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION){
QName qName = (QName)actualValue;
SchemaGrammar grammar = fGrammarBucket.getGrammar(qName.uri);
//REVISIT: is it possible for the notation to be in different namespace than the attribute
//with which it is associated, CHECK !! <fof n1:att1 = "n2:notation1" ..>
// should we give chance to the application to be able to retrieve a grammar - nb
//REVISIT: what would be the triggering component here.. if it is attribute value that
// triggered the loading of grammar ?? -nb
if (grammar != null) {
fNotation = grammar.getGlobalNotationDecl(qName.localpart);
}
}
}
catch (InvalidDatatypeValueException idve) {
reportSchemaError(idve.getKey(), idve.getArgs());
reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue});
}
// get the value constraint from use or decl
// 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType
if (actualValue != null &&
currDecl.getConstraintType() == XSConstants.VC_FIXED) {
if (!attDV.isEqual(actualValue, currDecl.fDefault.actualValue)){
reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue});
}
}
// 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5).
if (actualValue != null &&
currUse != null && currUse.fConstraintType == XSConstants.VC_FIXED) {
if (!attDV.isEqual(actualValue, currUse.fDefault.actualValue)){
reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue});
}
}
if (fAugPSVI) {
// PSVI: attribute declaration
attrPSVI.fDeclaration = currDecl;
if (currDecl != null && currDecl.fDefault != null)
attrPSVI.fSchemaDefault = currDecl.fDefault.normalizedValue;
// PSVI: attribute type
attrPSVI.fTypeDecl = attDV;
// PSVI: attribute memberType
attrPSVI.fMemberType = fValidatedInfo.memberType;
// PSVI: attribute normalized value
// NOTE: we always store the normalized value, even if it's invlid,
// because it might still be useful to the user. But when the it's
// not valid, the normalized value is not trustable.
attrPSVI.fNormalizedValue = fValidatedInfo.normalizedValue;
// PSVI: validation attempted:
attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL;
String[] errors = fXSIErrorReporter.mergeContext();
// PSVI: error codes
attrPSVI.fErrorCodes = errors;
// PSVI: validity
attrPSVI.fValidity = (errors == null) ?
AttributePSVI.VALIDITY_VALID :
AttributePSVI.VALIDITY_INVALID;
}
}
void addDefaultAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) {
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// REVISIT: should we check prohibited attributes?
// (2) report error for PROHIBITED attrs that are present (V_TAGc)
// (3) add default attrs (FIXED and NOT_FIXED)
if (DEBUG) {
System.out.println("==>addDefaultAttributes: " + element);
}
XSObjectList attrUses = attrGrp.getAttributeUses();
int useCount = attrUses.getLength();
XSAttributeUseImpl currUse;
XSAttributeDecl currDecl;
short constType;
ValidatedInfo defaultValue;
boolean isSpecified;
QName attName;
// for each attribute use
for (int i = 0; i < useCount; i++) {
currUse = (XSAttributeUseImpl)attrUses.getItem(i);
currDecl = currUse.fAttrDecl;
// get value constraint
constType = currUse.fConstraintType;
defaultValue = currUse.fDefault;
if (constType == XSConstants.VC_NONE) {
constType = currDecl.getConstraintType();
defaultValue = currDecl.fDefault;
}
// whether this attribute is specified
isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null;
// Element Locally Valid (Complex Type)
// 4 The {attribute declaration} of each attribute use in the {attribute uses} whose
// {required} is true matches one of the attribute information items in the element
// information item's [attributes] as per clause 3.1 above.
if (currUse.fUse == SchemaSymbols.USE_REQUIRED) {
if (!isSpecified)
reportSchemaError("cvc-complex-type.4", new Object[]{element.rawname, currDecl.fName});
}
// if the attribute is not specified, then apply the value constraint
if (!isSpecified && constType != XSConstants.VC_NONE) {
attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace);
String normalized = (defaultValue!=null)?defaultValue.normalizedValue:"";
int attrIndex = attributes.addAttribute(attName, "CDATA", normalized);
if (attributes instanceof XMLAttributesImpl) {
XMLAttributesImpl attrs = (XMLAttributesImpl)attributes;
boolean schemaId = defaultValue != null &&
defaultValue.memberType != null ?
defaultValue.memberType.isIDType() :
currDecl.fType.isIDType();
attrs.setSchemaId(attrIndex, schemaId);
}
if (fAugPSVI) {
// PSVI: attribute is "schema" specified
Augmentations augs = attributes.getAugmentations(attrIndex);
AttributePSVImpl attrPSVI = new AttributePSVImpl();
augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI);
attrPSVI.fNormalizedValue = normalized;
attrPSVI.fSchemaDefault = normalized;
attrPSVI.fValidationContext = fValidationRoot;
attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID;
attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL;
attrPSVI.fSpecified = true;
}
}
} // for
} // addDefaultAttributes
/**
* If there is not text content, and there is a
* {value constraint} on the corresponding element decl, then return
* an XMLString representing the default value.
*/
void processElementContent(QName element) {
// 1 If the item is ?valid? with respect to an element declaration as per Element Locally Valid (Element) (?3.3.4) and the {value constraint} is present, but clause 3.2 of Element Locally Valid (Element) (?3.3.4) above is not satisfied and the item has no element or character information item [children], then schema. Furthermore, the post-schema-validation infoset has the canonical lexical representation of the {value constraint} value as the item's [schema normalized value] property.
if (fCurrentElemDecl != null && fCurrentElemDecl.fDefault != null &&
fBuffer.length() == 0 && fChildCount == 0 && !fNil) {
int bufLen = fCurrentElemDecl.fDefault.normalizedValue.length();
if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) {
fNormalizedStr.ch = new char[bufLen];
}
fCurrentElemDecl.fDefault.normalizedValue.getChars(0, bufLen, fNormalizedStr.ch, 0);
fNormalizedStr.offset = 0;
fNormalizedStr.length = bufLen;
fDefaultValue = fNormalizedStr;
}
// fixed values are handled later, after xsi:type determined.
String content = fBuffer.toString();
fValidatedInfo.normalizedValue = null;
// Element Locally Valid (Element)
// 3.2.1 The element information item must have no character or element information item [children].
if (fNil) {
if (fChildCount != 0 || content.length() != 0){
reportSchemaError("cvc-elt.3.2.1", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_NIL});
}
}
this.fValidatedInfo.reset();
// 5 The appropriate case among the following must be true:
// 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true:
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() != XSConstants.VC_NONE &&
fChildCount == 0 && content.length() == 0 && !fNil) {
// 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6).
if (fCurrentType != fCurrentElemDecl.fType) {
//REVISIT:we should pass ValidatedInfo here.
if (XSConstraints.ElementDefaultValidImmediate(fCurrentType, fCurrentElemDecl.fDefault.normalizedValue, fState4XsiType, null) == null)
reportSchemaError("cvc-elt.5.1.1", new Object[]{element.rawname, fCurrentType.getName(), fCurrentElemDecl.fDefault.normalizedValue});
}
// 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4).
// REVISIT: don't use toString, but validateActualValue instead
// use the fState4ApplyDefault
elementLocallyValidType(element, fCurrentElemDecl.fDefault.normalizedValue);
}
else {
// The following method call also deal with clause 1.2.2 of the constraint
// Validation Rule: Schema-Validity Assessment (Element)
// 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true:
// 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4).
Object actualValue = elementLocallyValidType(element, content);
// 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true:
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED &&
!fNil) {
// 5.2.2.1 The element information item must have no element information item [children].
if (fChildCount != 0)
reportSchemaError("cvc-elt.5.2.2.1", new Object[]{element.rawname});
// 5.2.2.2 The appropriate case among the following must be true:
if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
// 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value.
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) {
// REVISIT: how to get the initial value, does whiteSpace count?
if (!fCurrentElemDecl.fDefault.normalizedValue.equals(content))
reportSchemaError("cvc-elt.5.2.2.2.1", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue});
}
// 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value.
else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) {
if (actualValue != null &&
!ctype.fXSSimpleType.isEqual(actualValue, fCurrentElemDecl.fDefault.actualValue))
reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue});
}
}
else if (fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) {
XSSimpleType sType = (XSSimpleType)fCurrentType;
if (actualValue != null &&
!sType.isEqual(actualValue, fCurrentElemDecl.fDefault.actualValue))
// REVISIT: the spec didn't mention this case: fixed
// value with simple type
reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue});
}
}
}
if (fDefaultValue == null && fNormalizeData &&
fDocumentHandler != null && fUnionType) {
// for union types we need to send data because we delayed sending
// this data when we received it in the characters() call.
if (fValidatedInfo.normalizedValue != null)
content = fValidatedInfo.normalizedValue;
int bufLen = content.length();
if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) {
fNormalizedStr.ch = new char[bufLen];
}
content.getChars(0, bufLen, fNormalizedStr.ch, 0);
fNormalizedStr.offset = 0;
fNormalizedStr.length = bufLen;
fDocumentHandler.characters(fNormalizedStr, null);
}
} // processElementContent
Object elementLocallyValidType(QName element, String textContent) {
if (fCurrentType == null)
return null;
Object retValue = null;
// Element Locally Valid (Type)
// 3 The appropriate case among the following must be true:
// 3.1 If the type definition is a simple type definition, then all of the following must be true:
if (fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) {
// 3.1.2 The element information item must have no element information item [children].
if (fChildCount != 0)
reportSchemaError("cvc-type.3.1.2", new Object[]{element.rawname});
// 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4).
if (!fNil) {
XSSimpleType dv = (XSSimpleType)fCurrentType;
try {
if (!fNormalizeData || fUnionType) {
fValidationState.setNormalizationRequired(true);
}
retValue = dv.validate(textContent, fValidationState, fValidatedInfo);
}
catch (InvalidDatatypeValueException e) {
reportSchemaError(e.getKey(), e.getArgs());
reportSchemaError("cvc-type.3.1.3", new Object[]{element.rawname, textContent});
}
}
}
else {
// 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4);
retValue = elementLocallyValidComplexType(element, textContent);
}
return retValue;
} // elementLocallyValidType
Object elementLocallyValidComplexType(QName element, String textContent) {
Object actualValue = null;
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
// Element Locally Valid (Complex Type)
// For an element information item to be locally valid with respect to a complex type definition all of the following must be true:
// 1 {abstract} is false.
// 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true:
if (!fNil) {
// 2.1 If the {content type} is empty, then the element information item has no character or element information item [children].
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY &&
(fChildCount != 0 || textContent.length() != 0 || fSawChildren)) {
reportSchemaError("cvc-complex-type.2.1", new Object[]{element.rawname});
}
// 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4).
else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) {
if (fChildCount != 0)
reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname});
XSSimpleType dv = ctype.fXSSimpleType;
try {
if (!fNormalizeData || fUnionType) {
fValidationState.setNormalizationRequired(true);
}
actualValue = dv.validate(textContent, fValidationState, fValidatedInfo);
}
catch (InvalidDatatypeValueException e) {
reportSchemaError(e.getKey(), e.getArgs());
reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname});
}
// REVISIT: eventually, this method should return the same actualValue as elementLocallyValidType...
// obviously it'll return null when the content is complex.
}
// 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)].
else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) {
if (fSawCharacters) {
reportSchemaError("cvc-complex-type.2.3", new Object[]{element.rawname});
}
}
// 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4).
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT ||
ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) {
// if the current state is a valid state, check whether
// it's one of the final states.
if (DEBUG) {
System.out.println(fCurrCMState);
}
if (fCurrCMState[0] >= 0 &&
!fCurrentCM.endContentModel(fCurrCMState)) {
reportSchemaError("cvc-complex-type.2.4.b", new Object[]{element.rawname, ((XSParticleDecl)ctype.getParticle()).toString()});
}
}
}
return actualValue;
} // elementLocallyValidComplexType
void reportSchemaError(String key, Object[] arguments) {
if (fDoValidation)
fXSIErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
key, arguments,
XMLErrorReporter.SEVERITY_ERROR);
}
// xpath matcher information
/**
* Stack of XPath matchers for identity constraints.
*
* @author Andy Clark, IBM
*/
protected static class XPathMatcherStack {
// Data
/** Active matchers. */
protected XPathMatcher[] fMatchers = new XPathMatcher[4];
/** Count of active matchers. */
protected int fMatchersCount;
/** Offset stack for contexts. */
protected IntStack fContextStack = new IntStack();
// Constructors
public XPathMatcherStack() {
} // <init>()
// Public methods
/** Resets the XPath matcher stack. */
public void clear() {
for (int i = 0; i < fMatchersCount; i++) {
fMatchers[i] = null;
}
fMatchersCount = 0;
fContextStack.clear();
} // clear()
/** Returns the size of the stack. */
public int size() {
return fContextStack.size();
} // size():int
/** Returns the count of XPath matchers. */
public int getMatcherCount() {
return fMatchersCount;
} // getMatcherCount():int
/** Adds a matcher. */
public void addMatcher(XPathMatcher matcher) {
ensureMatcherCapacity();
fMatchers[fMatchersCount++] = matcher;
} // addMatcher(XPathMatcher)
/** Returns the XPath matcher at the specified index. */
public XPathMatcher getMatcherAt(int index) {
return fMatchers[index];
} // getMatcherAt(index):XPathMatcher
/** Pushes a new context onto the stack. */
public void pushContext() {
fContextStack.push(fMatchersCount);
} // pushContext()
/** Pops a context off of the stack. */
public void popContext() {
fMatchersCount = fContextStack.pop();
} // popContext()
// Private methods
/** Ensures the size of the matchers array. */
private void ensureMatcherCapacity() {
if (fMatchersCount == fMatchers.length) {
XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2];
System.arraycopy(fMatchers, 0, array, 0, fMatchers.length);
fMatchers = array;
}
} // ensureMatcherCapacity()
} // class XPathMatcherStack
// value store implementations
/**
* Value store implementation base class. There are specific subclasses
* for handling unique, key, and keyref.
*
* @author Andy Clark, IBM
*/
protected abstract class ValueStoreBase
implements ValueStore {
// Constants
/** Not a value (Unicode: #FFFF). */
protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null);
// Data
/** Identity constraint. */
protected IdentityConstraint fIdentityConstraint;
/** Current data values. */
protected final OrderedHashtable fValues = new OrderedHashtable();
/** Current data value count. */
protected int fValuesCount;
/** Data value tuples. */
protected final Vector fValueTuples = new Vector();
// Constructors
/** Constructs a value store for the specified identity constraint. */
protected ValueStoreBase(IdentityConstraint identityConstraint) {
fIdentityConstraint = identityConstraint;
} // <init>(IdentityConstraint)
// Public methods
// destroys this ValueStore; useful when, for instance, a
// locally-scoped ID constraint is involved.
public void clear() {
fValuesCount = 0;
fValues.clear();
fValueTuples.removeAllElements();
} // end clear():void
// appends the contents of one ValueStore to those of us.
public void append(ValueStoreBase newVal) {
for (int i = 0; i < newVal.fValueTuples.size(); i++) {
OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i);
if (!contains(o))
fValueTuples.addElement(o);
}
} // append(ValueStoreBase)
/** Start scope for value store. */
public void startValueScope() throws XNIException {
fValuesCount = 0;
int count = fIdentityConstraint.getFieldCount();
for (int i = 0; i < count; i++) {
fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE);
}
} // startValueScope()
/** Ends scope for value store. */
public void endValueScope() throws XNIException {
// is there anything to do?
// REVISIT: This check solves the problem with field matchers
// that get activated because they are at the same
// level as the declaring element (e.g. selector xpath
// is ".") but never match.
// However, this doesn't help us catch the problem
// when we expect a field value but never see it. A
// better solution has to be found. -Ac
// REVISIT: Is this a problem? -Ac
// Yes - NG
if (fValuesCount == 0) {
if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) {
String code = "AbsentKeyValue";
String eName = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{eName});
}
return;
}
// do we have enough values?
if (fValuesCount != fIdentityConstraint.getFieldCount()) {
switch (fIdentityConstraint.getCategory()) {
case IdentityConstraint.IC_UNIQUE: {
String code = "UniqueNotEnoughValues";
String ename = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{ename});
break;
}
case IdentityConstraint.IC_KEY: {
String code = "KeyNotEnoughValues";
UniqueOrKey key = (UniqueOrKey)fIdentityConstraint;
String ename = fIdentityConstraint.getElementName();
String kname = key.getIdentityConstraintName();
reportSchemaError(code, new Object[]{ename,kname});
break;
}
case IdentityConstraint.IC_KEYREF: {
String code = "KeyRefNotEnoughValues";
KeyRef keyref = (KeyRef)fIdentityConstraint;
String ename = fIdentityConstraint.getElementName();
String kname = (keyref.getKey()).getIdentityConstraintName();
reportSchemaError(code, new Object[]{ename,kname});
break;
}
}
return;
}
} // endValueScope()
// This is needed to allow keyref's to look for matched keys
// in the correct scope. Unique and Key may also need to
// override this method for purposes of their own.
// This method is called whenever the DocumentFragment
// of an ID Constraint goes out of scope.
public void endDocumentFragment() throws XNIException {
} // endDocumentFragment():void
/**
* Signals the end of the document. This is where the specific
* instances of value stores can verify the integrity of the
* identity constraints.
*/
public void endDocument() throws XNIException {
} // endDocument()
// ValueStore methods
/* reports an error if an element is matched
* has nillable true and is matched by a key.
*/
public void reportError(String key, Object[] args) {
reportSchemaError(key, args);
} // reportError(String,Object[])
/**
* Adds the specified value to the value store.
*
* @param value The value to add.
* @param field The field associated to the value. This reference
* is used to ensure that each field only adds a value
* once within a selection scope.
*/
public void addValue(Field field, IDValue value) {
if (!field.mayMatch()) {
String code = "FieldMultipleMatch";
reportSchemaError(code, new Object[]{field.toString()});
}
// do we even know this field?
int index = fValues.indexOf(field);
if (index == -1) {
String code = "UnknownField";
reportSchemaError(code, new Object[]{field.toString()});
return;
}
// store value
IDValue storedValue = fValues.valueAt(index);
if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) {
fValuesCount++;
}
fValues.put(field, value);
if (fValuesCount == fValues.size()) {
// is this value as a group duplicated?
if (contains(fValues)) {
duplicateValue(fValues);
}
// store values
OrderedHashtable values = (OrderedHashtable)fValues.clone();
fValueTuples.addElement(values);
}
} // addValue(String,Field)
/**
* Returns true if this value store contains the specified
* values tuple.
*/
public boolean contains(OrderedHashtable tuple) {
// do sizes match?
int tcount = tuple.size();
// iterate over tuples to find it
int count = fValueTuples.size();
LOOP: for (int i = 0; i < count; i++) {
OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i);
// compare values
for (int j = 0; j < tcount; j++) {
IDValue value1 = vtuple.valueAt(j);
IDValue value2 = tuple.valueAt(j);
if (!(value1.isDuplicateOf(value2))) {
continue LOOP;
}
}
// found it
return true;
}
// didn't find it
return false;
} // contains(Hashtable):boolean
// Protected methods
/**
* Called when a duplicate value is added. Subclasses should override
* this method to perform error checking.
*
* @param tuple The duplicate value tuple.
*/
protected void duplicateValue(OrderedHashtable tuple)
throws XNIException {
// no-op
} // duplicateValue(Hashtable)
/** Returns a string of the specified values. */
protected String toString(OrderedHashtable tuple) {
// no values
int size = tuple.size();
if (size == 0) {
return "";
}
// construct value string
StringBuffer str = new StringBuffer();
for (int i = 0; i < size; i++) {
if (i > 0) {
str.append(',');
}
str.append(tuple.valueAt(i));
}
return str.toString();
} // toString(OrderedHashtable):String
// Object methods
/** Returns a string representation of this object. */
public String toString() {
String s = super.toString();
int index1 = s.lastIndexOf('$');
if (index1 != -1) {
s = s.substring(index1 + 1);
}
int index2 = s.lastIndexOf('.');
if (index2 != -1) {
s = s.substring(index2 + 1);
}
return s + '[' + fIdentityConstraint + ']';
} // toString():String
} // class ValueStoreBase
/**
* Unique value store.
*
* @author Andy Clark, IBM
*/
protected class UniqueValueStore
extends ValueStoreBase {
// Constructors
/** Constructs a unique value store. */
public UniqueValueStore(UniqueOrKey unique) {
super(unique);
} // <init>(Unique)
// ValueStoreBase protected methods
/**
* Called when a duplicate value is added.
*
* @param tuple The duplicate value tuple.
*/
protected void duplicateValue(OrderedHashtable tuple)
throws XNIException {
String code = "DuplicateUnique";
String value = toString(tuple);
String ename = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{value,ename});
} // duplicateValue(Hashtable)
} // class UniqueValueStore
/**
* Key value store.
*
* @author Andy Clark, IBM
*/
protected class KeyValueStore
extends ValueStoreBase {
// REVISIT: Implement a more efficient storage mechanism. -Ac
// Constructors
/** Constructs a key value store. */
public KeyValueStore(UniqueOrKey key) {
super(key);
} // <init>(Key)
// ValueStoreBase protected methods
/**
* Called when a duplicate value is added.
*
* @param tuple The duplicate value tuple.
*/
protected void duplicateValue(OrderedHashtable tuple)
throws XNIException {
String code = "DuplicateKey";
String value = toString(tuple);
String ename = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{value,ename});
} // duplicateValue(Hashtable)
} // class KeyValueStore
/**
* Key reference value store.
*
* @author Andy Clark, IBM
*/
protected class KeyRefValueStore
extends ValueStoreBase {
// Data
/** Key value store. */
protected ValueStoreBase fKeyValueStore;
// Constructors
/** Constructs a key value store. */
public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) {
super(keyRef);
fKeyValueStore = keyValueStore;
} // <init>(KeyRef)
// ValueStoreBase methods
// end the value Scope; here's where we have to tie
// up keyRef loose ends.
public void endDocumentFragment () throws XNIException {
// do all the necessary management...
super.endDocumentFragment ();
// verify references
// get the key store corresponding (if it exists):
fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey());
if (fKeyValueStore == null) {
// report error
String code = "KeyRefOutOfScope";
String value = fIdentityConstraint.toString();
reportSchemaError(code, new Object[]{value});
return;
}
int count = fValueTuples.size();
for (int i = 0; i < count; i++) {
OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i);
if (!fKeyValueStore.contains(values)) {
String code = "KeyNotFound";
String value = toString(values);
String element = fIdentityConstraint.getElementName();
String name = fIdentityConstraint.getName();
reportSchemaError(code, new Object[]{name, value,element});
}
}
} // endDocumentFragment()
/** End document. */
public void endDocument() throws XNIException {
super.endDocument();
} // endDocument()
} // class KeyRefValueStore
// value store management
/**
* Value store cache. This class is used to store the values for
* identity constraints.
*
* @author Andy Clark, IBM
*/
protected class ValueStoreCache {
// Data
// values stores
/** stores all global Values stores. */
protected final Vector fValueStores = new Vector();
/**
* Values stores associated to specific identity constraints.
* This hashtable maps IdentityConstraints and
* the 0-based element on which their selectors first matched to
* a corresponding ValueStore. This should take care
* of all cases, including where ID constraints with
* descendant-or-self axes occur on recursively-defined
* elements.
*/
protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable();
// sketch of algorithm:
// - when a constraint is first encountered, its
// values are stored in the (local) fIdentityConstraint2ValueStoreMap;
// - Once it is validated (i.e., wen it goes out of scope),
// its values are merged into the fGlobalIDConstraintMap;
// - as we encounter keyref's, we look at the global table to
// validate them.
// the fGlobalIDMapStack has the following structure:
// - validation always occurs against the fGlobalIDConstraintMap
// (which comprises all the "eligible" id constraints);
// When an endelement is found, this Hashtable is merged with the one
// below in the stack.
// When a start tag is encountered, we create a new
// fGlobalIDConstraintMap.
// i.e., the top of the fGlobalIDMapStack always contains
// the preceding siblings' eligible id constraints;
// the fGlobalIDConstraintMap contains descendants+self.
// keyrefs can only match descendants+self.
protected final Stack fGlobalMapStack = new Stack();
protected final Hashtable fGlobalIDConstraintMap = new Hashtable();
// Constructors
/** Default constructor. */
public ValueStoreCache() {
} // <init>()
// Public methods
/** Resets the identity constraint cache. */
public void startDocument() throws XNIException {
fValueStores.removeAllElements();
fIdentityConstraint2ValueStoreMap.clear();
fGlobalIDConstraintMap.clear();
fGlobalMapStack.removeAllElements();
} // startDocument()
// startElement: pushes the current fGlobalIDConstraintMap
// onto fGlobalMapStack and clears fGlobalIDConstraint map.
public void startElement() {
// only clone the hashtable when there are elements
if (fGlobalIDConstraintMap.size() > 0)
fGlobalMapStack.push(fGlobalIDConstraintMap.clone());
else
fGlobalMapStack.push(null);
fGlobalIDConstraintMap.clear();
} // startElement(void)
// endElement(): merges contents of fGlobalIDConstraintMap with the
// top of fGlobalMapStack into fGlobalIDConstraintMap.
public void endElement() {
if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc!
Hashtable oldMap = (Hashtable)fGlobalMapStack.pop();
// return if there is no element
if (oldMap == null) return;
Enumeration keys = oldMap.keys();
while (keys.hasMoreElements()) {
IdentityConstraint id = (IdentityConstraint)keys.nextElement();
ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id);
if (oldVal != null) {
ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id);
if (currVal == null)
fGlobalIDConstraintMap.put(id, oldVal);
else {
currVal.append(oldVal);
}
}
}
} // endElement()
/**
* Initializes the value stores for the specified element
* declaration.
*/
public void initValueStoresFor(XSElementDecl eDecl) {
// initialize value stores for unique fields
IdentityConstraint [] icArray = eDecl.fIDConstraints;
int icCount = eDecl.fIDCPos;
for (int i = 0; i < icCount; i++) {
switch (icArray[i].getCategory()) {
case (IdentityConstraint.IC_UNIQUE):
// initialize value stores for unique fields
UniqueOrKey unique = (UniqueOrKey)icArray[i];
LocalIDKey toHash = new LocalIDKey (unique, fElementDepth);
UniqueValueStore uniqueValueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(toHash);
if (uniqueValueStore == null) {
uniqueValueStore = new UniqueValueStore(unique);
fIdentityConstraint2ValueStoreMap.put(toHash, uniqueValueStore);
} else {
uniqueValueStore.clear();
}
fValueStores.addElement(uniqueValueStore);
break;
case (IdentityConstraint.IC_KEY):
// initialize value stores for key fields
UniqueOrKey key = (UniqueOrKey)icArray[i];
toHash = new LocalIDKey(key, fElementDepth);
KeyValueStore keyValueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(toHash);
if (keyValueStore == null) {
keyValueStore = new KeyValueStore(key);
fIdentityConstraint2ValueStoreMap.put(toHash, keyValueStore);
} else {
keyValueStore.clear();
}
fValueStores.addElement(keyValueStore);
break;
case (IdentityConstraint.IC_KEYREF):
// initialize value stores for keyRef fields
KeyRef keyRef = (KeyRef)icArray[i];
toHash = new LocalIDKey(keyRef, fElementDepth);
KeyRefValueStore keyRefValueStore = (KeyRefValueStore)fIdentityConstraint2ValueStoreMap.get(toHash);
if (keyRefValueStore == null) {
keyRefValueStore = new KeyRefValueStore(keyRef, null);
fIdentityConstraint2ValueStoreMap.put(toHash, keyRefValueStore);
} else {
keyRefValueStore.clear();
}
fValueStores.addElement(keyRefValueStore);
break;
}
}
} // initValueStoresFor(XSElementDecl)
/** Returns the value store associated to the specified IdentityConstraint. */
public ValueStoreBase getValueStoreFor(IdentityConstraint id, int initialDepth) {
ValueStoreBase vb = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(new LocalIDKey(id, initialDepth));
// vb should *never* be null!
return vb;
} // getValueStoreFor(IdentityConstraint, int):ValueStoreBase
/** Returns the global value store associated to the specified IdentityConstraint. */
public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) {
return(ValueStoreBase)fGlobalIDConstraintMap.get(id);
} // getValueStoreFor(IdentityConstraint):ValueStoreBase
// This method takes the contents of the (local) ValueStore
// associated with id and moves them into the global
// hashtable, if id is a <unique> or a <key>.
// If it's a <keyRef>, then we leave it for later.
public void transplant(IdentityConstraint id, int initialDepth) {
ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(new LocalIDKey(id, initialDepth));
if (id.getCategory() == IdentityConstraint.IC_KEYREF) return;
ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id);
if (currVals != null) {
currVals.append(newVals);
fGlobalIDConstraintMap.put(id, currVals);
}
else
fGlobalIDConstraintMap.put(id, newVals);
} // transplant(id)
/** Check identity constraints. */
public void endDocument() {
int count = fValueStores.size();
for (int i = 0; i < count; i++) {
ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i);
valueStore.endDocument();
}
} // endDocument()
// Object methods
/** Returns a string representation of this object. */
public String toString() {
String s = super.toString();
int index1 = s.lastIndexOf('$');
if (index1 != -1) {
return s.substring(index1 + 1);
}
int index2 = s.lastIndexOf('.');
if (index2 != -1) {
return s.substring(index2 + 1);
}
return s;
} // toString():String
} // class ValueStoreCache
// utility classes
/**
* Ordered hashtable. This class acts as a hashtable with
* <code>put()</code> and <code>get()</code> operations but also
* allows values to be queried via the order that they were
* added to the hashtable.
* <p>
* <strong>Note:</strong> This class does not perform any error
* checking.
* <p>
* <strong>Note:</strong> This class is <em>not</em> efficient but
* is assumed to be used for a very small set of values.
*
* @author Andy Clark, IBM
*/
static final class OrderedHashtable
implements Cloneable {
// Data
/** Size. */
private int fSize;
/** Hashtable entries. */
private Entry[] fEntries = null;
// Public methods
/** Returns the number of entries in the hashtable. */
public int size() {
return fSize;
} // size():int
/** Puts an entry into the hashtable. */
public void put(Field key, IDValue value) {
int index = indexOf(key);
if (index == -1) {
ensureCapacity(fSize);
index = fSize++;
fEntries[index].key = key;
}
fEntries[index].value = value;
} // put(Field,String)
/** Returns the value associated to the specified key. */
public IDValue get(Field key) {
return fEntries[indexOf(key)].value;
} // get(Field):String
/** Returns the index of the entry with the specified key. */
public int indexOf(Field key) {
for (int i = 0; i < fSize; i++) {
// NOTE: Only way to be sure that the keys are the
// same is by using a reference comparison. In
// order to rely on the equals method, each
// field would have to take into account its
// position in the identity constraint, the
// identity constraint, the declaring element,
// and the grammar that it is defined in.
// Otherwise, you have the possibility that
// the equals method would return true for two
// fields that look *very* similar.
// The reference compare isn't bad, actually,
// because the field objects are cacheable. -Ac
if (fEntries[i].key == key) {
return i;
}
}
return -1;
} // indexOf(Field):int
/** Returns the key at the specified index. */
public Field keyAt(int index) {
return fEntries[index].key;
} // keyAt(int):Field
/** Returns the value at the specified index. */
public IDValue valueAt(int index) {
return fEntries[index].value;
} // valueAt(int):String
/** Removes all of the entries from the hashtable. */
public void clear() {
fSize = 0;
} // clear()
// Private methods
/** Ensures the capacity of the entries array. */
private void ensureCapacity(int size) {
// sizes
int osize = -1;
int nsize = -1;
// create array
if (fEntries == null) {
osize = 0;
nsize = 2;
fEntries = new Entry[nsize];
}
// resize array
else if (fEntries.length <= size) {
osize = fEntries.length;
nsize = 2 * osize;
Entry[] array = new Entry[nsize];
System.arraycopy(fEntries, 0, array, 0, osize);
fEntries = array;
}
// create new entries
for (int i = osize; i < nsize; i++) {
fEntries[i] = new Entry();
}
} // ensureCapacity(int)
// Cloneable methods
/** Clones this object. */
public Object clone() {
OrderedHashtable hashtable = new OrderedHashtable();
for (int i = 0; i < fSize; i++) {
hashtable.put(fEntries[i].key, fEntries[i].value);
}
return hashtable;
} // clone():Object
// Object methods
/** Returns a string representation of this object. */
public String toString() {
if (fSize == 0) {
return "[]";
}
StringBuffer str = new StringBuffer();
str.append('[');
for (int i = 0; i < fSize; i++) {
if (i > 0) {
str.append(',');
}
str.append('{');
str.append(fEntries[i].key);
str.append(',');
str.append(fEntries[i].value);
str.append('}');
}
str.append(']');
return str.toString();
} // toString():String
// Classes
/**
* Hashtable entry.
*/
public static final class Entry {
// Data
/** Key. */
public Field key;
/** Value. */
public IDValue value;
} // class Entry
} // class OrderedHashtable
// the purpose of this class is to enable IdentityConstraint,int
// pairs to be used easily as keys in Hashtables.
protected class LocalIDKey {
private IdentityConstraint fId;
private int fDepth;
public LocalIDKey (IdentityConstraint id, int depth) {
fId = id;
fDepth = depth;
} // init(IdentityConstraint, int)
// object method
public int hashCode() {
return fId.hashCode()+fDepth;
}
public boolean equals(Object localIDKey) {
if(localIDKey instanceof LocalIDKey) {
LocalIDKey lIDKey = (LocalIDKey)localIDKey;
return (lIDKey.fId == fId && lIDKey.fDepth == fDepth);
}
return false;
}
} // class LocalIDKey
} // class SchemaValidator
|
package com.opencms.workplace;
import com.opencms.boot.*;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
public class CmsAdminDatabase extends CmsWorkplaceDefault implements I_CmsConstants {
private static String C_DATABASE_THREAD = "databse_im_export_thread";
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName()
+ "getting content of element "
+ ((elementName == null) ? "<root>" : elementName));
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName()
+ "template file is: " + templateFile);
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName()
+ "selected template section is: "
+ ((templateSelector == null) ? "<default>" : templateSelector));
}
//CmsXmlTemplateFile xmlTemplateDocument = getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector);
CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms, templateFile);
I_CmsSession session = cms.getRequestContext().getSession(true);
// get the parameters
// String folder = (String)parameters.get("selectallfolders");
String fileName = (String)parameters.get("filename");
String existingFile = (String)parameters.get("existingfile");
String action = (String)parameters.get("action");
String allResources = (String)parameters.get("ALLRES");
if(action == null) {
// This is an initial request of the database administration page
// Generate datablocks for checkboxes in the HTML form
if(!cms.getRequestContext().currentProject().equals(cms.onlineProject())) {
xmlTemplateDocument.setData("nounchanged",
xmlTemplateDocument.getProcessedDataValue("nounchangedbox", this, parameters));
}
if(cms.isAdmin()) {
xmlTemplateDocument.setData("userdata",
xmlTemplateDocument.getProcessedDataValue("userdatabox", this, parameters));
}
}
// first we look if the thread is allready running
if((action != null) && ("working".equals(action))) {
// still working?
Thread doTheWork = (Thread)session.getValue(C_DATABASE_THREAD);
if(doTheWork.isAlive()) {
String time = (String)parameters.get("time");
int wert = Integer.parseInt(time);
wert += 20;
xmlTemplateDocument.setData("time", "" + wert);
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, "wait");
}
else {
// thread has come to an end, was there an error?
String errordetails = (String)session.getValue(C_SESSION_THREAD_ERROR);
if(errordetails == null) {
// im/export ready
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, "done");
}
else {
// get errorpage:
xmlTemplateDocument.setData("details", errordetails);
session.removeValue(C_SESSION_THREAD_ERROR);
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, "error");
}
}
}
try {
if("export".equals(action)) {
// export the database
Vector resourceNames = parseResources(allResources);
String[] exportPaths = new String[resourceNames.size()];
CmsXmlLanguageFile lang = xmlTemplateDocument.getLanguageFile();
for(int i = 0;i < resourceNames.size();i++) {
// modify the foldername if nescessary (the root folder is always given
// as a nice name)
if(lang.getLanguageValue("title.rootfolder").equals(resourceNames.elementAt(i))) {
resourceNames.setElementAt("/", i);
}
exportPaths[i] = (String)resourceNames.elementAt(i);
}
boolean excludeSystem = false;
if(parameters.get("nosystem") != null) {
excludeSystem = true;
}
boolean excludeUnchanged = false;
if(parameters.get("nounchanged") != null) {
excludeUnchanged = true;
}
boolean exportUserdata = false;
if(parameters.get("userdata") != null) {
exportUserdata = true;
}
// start the thread for: export
// first clear the session entry if necessary
if(session.getValue(C_SESSION_THREAD_ERROR) != null) {
session.removeValue(C_SESSION_THREAD_ERROR);
}
Thread doExport = new CmsAdminDatabaseExportThread(cms, CmsBase.getAbsolutePath(cms.readExportPath()) + File.separator
+ fileName, exportPaths, excludeSystem, excludeUnchanged, exportUserdata);
doExport.start();
session.putValue(C_DATABASE_THREAD, doExport);
xmlTemplateDocument.setData("time", "10");
templateSelector = "wait";
}
else {
if("import".equals(action)) {
// start the thread for: import
// first clear the session entry if necessary
if(session.getValue(C_SESSION_THREAD_ERROR) != null) {
session.removeValue(C_SESSION_THREAD_ERROR);
}
Thread doImport = new CmsAdminDatabaseImportThread(cms, CmsBase.getAbsolutePath(cms.readExportPath()) + File.separator
+ existingFile);
doImport.start();
session.putValue(C_DATABASE_THREAD, doImport);
xmlTemplateDocument.setData("time", "10");
templateSelector = "wait";
}
}
}
catch(CmsException exc) {
xmlTemplateDocument.setData("details", Utils.getStackTrace(exc));
templateSelector = "error";
}
// Now load the template file and start the processing
return startProcessing(cms, xmlTemplateDocument, elementName, parameters,
templateSelector);
}
/**
* Gets all export-files from the export-path.
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
* <P>
* <code>names</code> will contain language specific view descriptions
* and <code>values</code> will contain the correspondig URL for each
* of these views after returning from this method.
* <P>
*
* @param cms CmsObject Object for accessing system resources.
* @param lang reference to the currently valid language file
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the user's current filter view in the vectors.
* @exception CmsException
*/
public Integer getExportFiles(CmsObject cms, CmsXmlLanguageFile lang, Vector values,
Vector names, Hashtable parameters) throws CmsException {
// get the systems-exportpath
String exportpath = cms.readExportPath();
exportpath = CmsBase.getAbsolutePath(exportpath);
File folder = new File(exportpath);
if (!folder.exists()){
folder.mkdirs();
}
// get a list of all files
String[] list = folder.list(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return(fileName.endsWith(".zip"));
}});
for(int i = 0;i < list.length;i++) {
File diskFile = new File(exportpath, list[i]);
// check if it is a file
if(diskFile.isFile()) {
values.addElement(list[i]);
names.addElement(list[i]);
}
}
return new Integer(0);
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
/** Parse the string which holds all resources
*
* @param resources containts the full pathnames of all the resources, separated by semicolons
* @return A vector with the same resources
*/
private Vector parseResources(String resources) {
Vector ret = new Vector();
if(resources != null) {
StringTokenizer resTokenizer = new StringTokenizer(resources, ";");
while(resTokenizer.hasMoreElements()) {
String path = (String)resTokenizer.nextElement();
ret.addElement(path);
}
}
return ret;
}
}
|
package com.navigation.reactnative;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Pair;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.SharedElementCallback;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.widget.ViewPager2;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class NavigationStackView extends ViewGroup implements LifecycleEventListener {
protected ArrayList<String> sceneKeys = new ArrayList<>();
protected HashMap<String, SceneView> scenes = new HashMap<>();
Fragment fragment = null;
protected ReadableArray keys;
private int oldCrumb = -1;
private String oldKey;
private SparseIntArray defaultAnimation;
private Activity mainActivity;
protected String enterAnim;
protected String exitAnim;
protected ReadableArray sharedElementNames;
protected ReadableArray oldSharedElementNames;
protected Boolean startNavigation = null;
protected boolean finish = false;
SceneNavigator navigator;
public NavigationStackView(Context context) {
super(context);
defaultAnimation = new SparseIntArray();
TypedArray activityStyle = context.getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowAnimationStyle});
int windowAnimationStyleResId = activityStyle.getResourceId(0, 0);
activityStyle.recycle();
activityStyle = context.getTheme().obtainStyledAttributes(windowAnimationStyleResId, new int[] {
android.R.attr.activityOpenEnterAnimation, android.R.attr.activityOpenExitAnimation,
android.R.attr.activityCloseEnterAnimation, android.R.attr.activityCloseExitAnimation
});
defaultAnimation.put(android.R.attr.activityOpenEnterAnimation, activityStyle.getResourceId(0, 0));
defaultAnimation.put(android.R.attr.activityOpenExitAnimation, activityStyle.getResourceId(1, 0));
defaultAnimation.put(android.R.attr.activityCloseEnterAnimation, activityStyle.getResourceId(2, 0));
defaultAnimation.put(android.R.attr.activityCloseExitAnimation, activityStyle.getResourceId(3, 0));
activityStyle.recycle();
}
protected void onAfterUpdateTransaction() {
Activity currentActivity = ((ThemedReactContext) getContext()).getCurrentActivity();
if (currentActivity == null)
return;
if (mainActivity == null) {
mainActivity = currentActivity;
Uri uri = mainActivity.getIntent().getData();
if (uri != null) {
mainActivity.getIntent().setData(null);
DeviceEventManagerModule deviceEventManagerModule = ((ThemedReactContext) getContext()).getNativeModule(DeviceEventManagerModule.class);
deviceEventManagerModule.emitNewIntentReceived(uri);
}
}
if (finish) {
currentActivity.finishAffinity();
return;
}
if (fragment == null) {
fragment = new StackFragment(this);
FragmentManager fragmentManager = ((FragmentActivity) currentActivity).getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(fragment, "Stack" + getId());
transaction.commitNowAllowingStateLoss();
}
startNavigation = startNavigation == null && keys.size() != 0;
if (scenes.size() == 0 || fragment.getChildFragmentManager().isStateSaved())
return;
int crumb = keys.size() - 1;
int currentCrumb = oldCrumb;
if (crumb < currentCrumb) {
FragmentManager fragmentManager = fragment.getChildFragmentManager();
SceneFragment fragment = (SceneFragment) fragmentManager.findFragmentByTag(oldKey);
Pair[] sharedElements = fragment != null ? getOldSharedElements(currentCrumb, crumb, fragment, currentActivity) : null;
SceneFragment prevFragment = (SceneFragment) fragmentManager.findFragmentByTag(keys.getString(crumb));
if (sharedElements != null && prevFragment != null && prevFragment.getScene() != null)
prevFragment.getScene().transitioner = new SharedElementTransitioner(prevFragment, getSharedElementSet(oldSharedElementNames));
fragmentManager.popBackStack(String.valueOf(crumb), 0);
}
if (crumb > currentCrumb) {
final FragmentManager fragmentManager = fragment.getChildFragmentManager();
int enter = getAnimationResourceId(currentActivity, enterAnim, android.R.attr.activityOpenEnterAnimation);
int exit = getAnimationResourceId(currentActivity, exitAnim, android.R.attr.activityOpenExitAnimation);
if (exit == 0 && exitAnim != null)
exit = getAnimationResourceId(currentActivity, null, android.R.attr.activityOpenExitAnimation);
for(int i = 0; i < crumb - currentCrumb; i++) {
int nextCrumb = currentCrumb + i + 1;
String key = keys.getString(nextCrumb);
SceneView scene = scenes.get(key);
int popEnter = getAnimationResourceId(currentActivity, scene.enterAnim, android.R.attr.activityCloseEnterAnimation);
int popExit = getAnimationResourceId(currentActivity, scene.exitAnim, android.R.attr.activityCloseExitAnimation);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setReorderingAllowed(true);
Pair[] sharedElements = null;
if (nextCrumb > 0) {
String prevKey = keys.getString(nextCrumb - 1);
SceneFragment prevFramgent = (SceneFragment) fragmentManager.findFragmentByTag(prevKey);
if (prevFramgent != null)
sharedElements = getSharedElements(currentCrumb, crumb, prevFramgent);
}
if (sharedElements != null) {
for(Pair sharedElement : sharedElements) {
fragmentTransaction.addSharedElement((View) sharedElement.first, (String) sharedElement.second);
}
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
} else {
fragmentTransaction.setCustomAnimations(oldCrumb != -1 ? enter : 0, exit, popEnter, popExit);
}
SceneFragment fragment = new SceneFragment(scene, getSharedElementSet(sharedElementNames));
fragmentTransaction.replace(getId(), fragment, key);
fragmentTransaction.addToBackStack(String.valueOf(nextCrumb));
fragmentTransaction.commit();
}
}
if (crumb == currentCrumb && !oldKey.equals(keys.getString(crumb))) {
int enter = getAnimationResourceId(currentActivity, enterAnim, android.R.attr.activityOpenEnterAnimation);
int exit = getAnimationResourceId(currentActivity, exitAnim, android.R.attr.activityOpenExitAnimation);
String key = keys.getString(crumb);
SceneView scene = scenes.get(key);
int popEnter = getAnimationResourceId(currentActivity, scene.enterAnim, android.R.attr.activityCloseEnterAnimation);
int popExit = getAnimationResourceId(currentActivity, scene.exitAnim, android.R.attr.activityCloseExitAnimation);
FragmentManager fragmentManager = fragment.getChildFragmentManager();
fragmentManager.popBackStack();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(enter, exit, popEnter, popExit);
fragmentTransaction.add(getId(), new SceneFragment(scene, null), key);
fragmentTransaction.addToBackStack(String.valueOf(crumb));
fragmentTransaction.commit();
}
oldCrumb = keys.size() - 1;
oldKey = keys.getString(oldCrumb);
}
int getAnimationResourceId(Context context, String animationName, int defaultId) {
if (animationName == null)
return defaultAnimation.get(defaultId);
if (animationName.equals(""))
return 0;
String packageName = context.getPackageName();
return context.getResources().getIdentifier(animationName, "anim", packageName);
}
HashSet<String> getSharedElementSet(ReadableArray sharedElementNames) {
if (sharedElementNames == null)
return null;
HashSet<String> sharedElementSet = new HashSet<>();
for(int i = 0; i < sharedElementNames.size(); i++) {
sharedElementSet.add(sharedElementNames.getString(i));
}
return sharedElementSet;
}
HashMap<String, View> getSharedElementMap(SceneView scene) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
return null;
HashMap<String, View> sharedElementMap = new HashMap<>();
for(View sharedElement : scene.sharedElements) {
sharedElementMap.put(sharedElement.getTransitionName(), sharedElement);
}
return sharedElementMap;
}
Pair[] getSharedElements(HashMap<String, View> sharedElementMap, ReadableArray sharedElementNames) {
if (sharedElementMap == null || sharedElementNames == null)
return null;
ArrayList<Pair> sharedElementPairs = new ArrayList<>();
for(int i = 0; i < sharedElementNames.size(); i++) {
String name = sharedElementNames.getString(i);
if (sharedElementMap.containsKey(name))
sharedElementPairs.add(Pair.create(sharedElementMap.get(name), name));
}
return sharedElementPairs.toArray(new Pair[0]);
}
private Pair[] getOldSharedElements(int currentCrumb, int crumb, SharedElementContainer sharedElementContainer, final Activity activity) {
final HashMap<String, View> oldSharedElementsMap = getSharedElementMap(sharedElementContainer.getScene());
final Pair[] oldSharedElements = currentCrumb - crumb == 1 ? getSharedElements(oldSharedElementsMap, oldSharedElementNames) : null;
if (oldSharedElements != null && oldSharedElements.length != 0) {
final SharedElementTransitioner transitioner = new SharedElementTransitioner(sharedElementContainer, getSharedElementSet(oldSharedElementNames));
for(int i = 0; i < oldSharedElementNames.size(); i++) {
String name = oldSharedElementNames.getString(i);
if (oldSharedElementsMap.containsKey(name)) {
View oldSharedElement = oldSharedElementsMap.get(name);
SharedElementView oldSharedElementView = (SharedElementView) oldSharedElement.getParent();
transitioner.load(name, oldSharedElementView.exitTransition, activity);
}
}
sharedElementContainer.setEnterCallback(new SharedElementCallback() {
@Override
public void onMapSharedElements(List<String> names, Map<String, View> elements) {
for(int i = 0; i < oldSharedElementNames.size(); i++) {
String name = oldSharedElementNames.getString(i);
if (oldSharedElementsMap.containsKey(name)) {
View oldSharedElement = oldSharedElementsMap.get(name);
elements.put(names.get(i), oldSharedElement);
}
}
}
});
return oldSharedElements;
}
return null;
}
private Pair[] getSharedElements(int currentCrumb, int crumb, SharedElementContainer sharedElementContainer) {
final HashMap<String, View> sharedElementsMap = getSharedElementMap(sharedElementContainer.getScene());
final Pair[] sharedElements = crumb - currentCrumb == 1 ? getSharedElements(sharedElementsMap, sharedElementNames) : null;
if (sharedElements != null && sharedElements.length != 0) {
sharedElementContainer.setExitCallback(new SharedElementCallback() {
@Override
public void onMapSharedElements(List<String> names, Map<String, View> elements) {
for(int i = 0; i < names.size(); i++) {
String mappedName = names.get(i);
if (oldSharedElementNames != null && oldSharedElementNames.size() > i)
mappedName = oldSharedElementNames.getString(i);
if (sharedElementsMap.containsKey(mappedName))
elements.put(names.get(i), sharedElementsMap.get(mappedName));
}
}
});
return sharedElements;
}
return null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
onAfterUpdateTransaction();
((ThemedReactContext) getContext()).addLifecycleEventListener(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
((ThemedReactContext) getContext()).removeLifecycleEventListener(this);
}
void scrollToTop() {
if (keys.size() > 1) {
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "onNavigateToTop", null);
}
if (keys.size() == 1) {
SceneView scene = scenes.get(keys.getString(0));
for (int i = 0; i < scene.getChildCount(); i++) {
if (scene.getChildAt(i) instanceof CoordinatorLayoutView)
((CoordinatorLayoutView) scene.getChildAt(i)).scrollToTop();
if (scene.getChildAt(i) instanceof NavigationBarView)
((NavigationBarView) scene.getChildAt(i)).setExpanded(true);
if (scene.getChildAt(i) instanceof ScrollView)
((ScrollView) scene.getChildAt(i)).smoothScrollTo(0, 0);
if (scene.getChildAt(i) instanceof TabBarPagerView)
((TabBarPagerView) scene.getChildAt(i)).scrollToTop();
if (scene.getChildAt(i) instanceof ViewPager2)
TabBarPagerRTLManager.getAdapter((ViewPager2) scene.getChildAt(i)).scrollToTop();
}
}
}
void removeFragment() {
if (mainActivity != null && fragment != null) {
FragmentManager fragmentManager = ((FragmentActivity) mainActivity).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commitAllowingStateLoss();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
@Override
public void onHostResume() {
onAfterUpdateTransaction();
}
@Override
public void onHostPause() {
}
@Override
public void onHostDestroy() {
}
public static class StackFragment extends Fragment {
private NavigationStackView stack;
public StackFragment() {
super();
}
StackFragment(NavigationStackView stack) {
super();
this.stack = stack;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return stack != null ? stack : new View(getContext());
}
}
}
|
package org.apache.xerces.readers;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.utils.CharDataChunk;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringHasher;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.ImplementationMessages;
import org.xml.sax.SAXParseException;
import java.util.Vector;
/**
* An abstract class for readers that process input data as characters.
* <p>
* This is the base class of the CharReader and UTF8CharReader classes.
* The CharReader classes fills in the "chunks" of data to process from
* a character stream (java.io.Reader). The UTF8CharReader performs
* its own UTF-8 transcoding to fill in the data from an InputStream.
*
* @version $Id$
*/
abstract class AbstractCharReader extends XMLEntityReader {
/**
* Subclass constructor
*
* @param entityHandler The entity handler.
* @param errorReporter The error reporter.
* @param sendCharDataAsCharArray true if char data should be reported using
* char arrays instead of string handles.
* @param stringPool The string pool.
*/
protected AbstractCharReader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, StringPool stringPool) {
super(entityHandler, errorReporter, sendCharDataAsCharArray);
fStringPool = stringPool;
fCurrentChunk = CharDataChunk.createChunk(fStringPool, null);
}
// These instance variables are referenced and updated directly
// by our subclass from the fillCurrentChunk() method.
protected CharDataChunk fCurrentChunk = null;
protected int fCurrentIndex = 0;
protected char[] fMostRecentData = null;
protected int fMostRecentChar = 0;
protected int fLength = 0;
/**
* Fill the current chunk the next buffer worth of data.
*
* This method should replace any 0xD,0xA sequence with a single
* 0xA character, and replace single 0xD characters with a 0xA
* character. This is described in the spec under section 2.11,
* "End-of-Line Handling".
*
* @return The value of the first character available for processing.
* @exception java.lang.Exception
*/
protected abstract int fillCurrentChunk() throws Exception;
/**
* Delay reporting an error message.
*
* If there is an error detected in the underlying input stream during
* the fillCurrentChunk method, the error is described here and will be
* reported when we reach that offset during normal processing. The
* subclass should place a character with a value of zero at that offset,
* which will be detected here as an invalid character. When the invalid
* character is scanned, we will generate the deferred exception.
*
* @param errorCode the errorCode to report
* @param args an array of arguments needed to generate a good error message
* @param offset the position in the reader where the error occured
*/
protected void deferException(int errorCode, Object[] args, int offset) {
if (fDeferredErrors == null)
fDeferredErrors = new Vector();
DeferredError de = new DeferredError(errorCode, args, offset);
fDeferredErrors.addElement(de);
}
/**
* Change readers at end of input.
*
* We override our superclass method to release the final chunk
* of the input data before handing off to the next reader.
*
* @return The next reader used to continue processing the document.
*/
protected XMLEntityHandler.EntityReader changeReaders() throws Exception {
XMLEntityHandler.EntityReader nextReader = super.changeReaders();
fCurrentChunk.releaseChunk();
fCurrentChunk = null;
return nextReader;
}
// XMLEntityHandler.EntityReader implementation
// The first five methods of the interface are implemented
// in the XMLEntityHandler base class for us, namely
// public int currentOffset();
// public int getLineNumber();
// public int getColumnNumber();
// public void setInCDSect(boolean inCDSect);
// public boolean getInCDSect();
/**
* Append the characters processed by this reader associated with <code>offset</code> and
* <code>length</code> to the <code>CharBuffer</code>.
*
* @param charBuffer The <code>CharBuffer</code> to append the characters to.
* @param offset The offset within this reader where the copy should start.
* @param length The length within this reader where the copy should stop.
*/
public void append(XMLEntityHandler.CharBuffer charBuffer, int offset, int length) {
fCurrentChunk.append(charBuffer, offset, length);
}
/**
* Add a string to the <code>StringPool</code> from the characters scanned using this
* reader as described by <code>offset</code> and <code>length</code>.
*
* @param offset The offset within this reader where the characters start.
* @param length The length within this reader where the characters end.
* @return The <code>StringPool</code> handle for the string.
*/
public int addString(int offset, int length) {
if (length == 0)
return 0;
return fCurrentChunk.addString(offset, length);
}
/**
* Add a symbol to the <code>StringPool</code> from the characters scanned using this
* reader as described by <code>offset</code> and <code>length</code>.
*
* @param offset The offset within this reader where the characters start.
* @param length The length within this reader where the characters end.
* @return The <code>StringPool</code> handle for the symbol.
*/
public int addSymbol(int offset, int length) {
if (length == 0)
return 0;
return fCurrentChunk.addSymbol(offset, length, 0);
}
public boolean lookingAtChar(char chr, boolean skipPastChar) throws Exception {
int ch = fMostRecentChar;
if (ch != chr) {
if (ch == 0) {
if (atEOF(fCurrentOffset + 1)) {
return changeReaders().lookingAtChar(chr, skipPastChar);
}
}
return false;
}
if (skipPastChar) {
fCharacterCounter++;
fCurrentOffset++;
if (++fCurrentIndex == CharDataChunk.CHUNK_SIZE)
slowLoadNextChar();
else
fMostRecentChar = fMostRecentData[fCurrentIndex] & 0xFFFF;
}
return true;
}
public boolean lookingAtValidChar(boolean skipPastChar) throws Exception {
int ch = fMostRecentChar;
if (ch < 0xD800) {
if (ch >= 0x20 || ch == 0x09) {
if (skipPastChar) {
fCharacterCounter++;
loadNextChar();
}
return true;
}
if (ch == 0x0A) {
if (skipPastChar) {
fLinefeedCounter++;
fCharacterCounter = 1;
loadNextChar();
}
return true;
}
if (ch == 0) {
if (atEOF(fCurrentOffset + 1)) {
return changeReaders().lookingAtValidChar(skipPastChar);
}
}
return false;
}
if (ch > 0xFFFD) {
return false;
}
if (ch < 0xDC00) {
CharDataChunk savedChunk = fCurrentChunk;
int savedIndex = fCurrentIndex;
int savedOffset = fCurrentOffset;
ch = loadNextChar();
boolean valid = (ch >= 0xDC00 && ch < 0xE000);
if (!valid || !skipPastChar) {
fCurrentChunk = savedChunk;
fCurrentIndex = savedIndex;
fCurrentOffset = savedOffset;
fMostRecentData = savedChunk.toCharArray();
fMostRecentChar = fMostRecentData[savedIndex] & 0xFFFF;
return valid;
}
} else if (ch < 0xE000) {
return false;
}
if (skipPastChar) {
fCharacterCounter++;
loadNextChar();
}
return true;
}
public boolean lookingAtSpace(boolean skipPastChar) throws Exception {
int ch = fMostRecentChar;
if (ch > 0x20)
return false;
if (ch == 0x20 || ch == 0x09) {
if (!skipPastChar)
return true;
fCharacterCounter++;
} else if (ch == 0x0A) {
if (!skipPastChar)
return true;
fLinefeedCounter++;
fCharacterCounter = 1;
} else {
if (ch == 0) { // REVISIT - should we be checking this here ?
if (atEOF(fCurrentOffset + 1)) {
return changeReaders().lookingAtSpace(skipPastChar);
}
}
return false;
}
fCurrentOffset++;
if (++fCurrentIndex == CharDataChunk.CHUNK_SIZE)
slowLoadNextChar();
else
fMostRecentChar = fMostRecentData[fCurrentIndex] & 0xFFFF;
return true;
}
public void skipToChar(char chr) throws Exception {
// REVISIT - this will skip invalid characters without reporting them.
int ch = fMostRecentChar;
while (true) {
if (ch == chr)
return;
if (ch == 0) {
if (atEOF(fCurrentOffset + 1)) {
changeReaders().skipToChar(chr);
return;
}
fCharacterCounter++;
} else if (ch == 0x0A) {
fLinefeedCounter++;
fCharacterCounter = 1;
} else if (ch >= 0xD800 && ch < 0xDC00) {
fCharacterCounter++;
ch = loadNextChar();
if (ch < 0xDC00 || ch >= 0xE000)
continue;
} else
fCharacterCounter++;
ch = loadNextChar();
}
}
public void skipPastSpaces() throws Exception {
int ch = fMostRecentChar;
while (true) {
if (ch == 0x20 || ch == 0x09) {
fCharacterCounter++;
} else if (ch == 0x0A) {
fLinefeedCounter++;
fCharacterCounter = 1;
} else {
if (ch == 0 && atEOF(fCurrentOffset + 1))
changeReaders().skipPastSpaces();
return;
}
ch = loadNextChar();
}
}
public void skipPastName(char fastcheck) throws Exception {
int ch = fMostRecentChar;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0)
return;
} else {
if ( ! fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0)
return;
}
while (true) {
fCharacterCounter++;
ch = loadNextChar();
if (fastcheck == ch)
return;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0)
return;
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0)
return;
}
}
}
public void skipPastNmtoken(char fastcheck) throws Exception {
int ch = fMostRecentChar;
while (true) {
if (fastcheck == ch)
return;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0)
return;
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0)
return;
}
fCharacterCounter++;
ch = loadNextChar();
}
}
public boolean skippedString(char[] s) throws Exception {
int length = s.length;
char[] data = fMostRecentData;
int index = fCurrentIndex;
if (index + length <= CharDataChunk.CHUNK_SIZE) {
for (int i = 0; i < length; i++) {
if (data[index++] != s[i])
return false;
}
fCharacterCounter += length;
fCurrentOffset += length;
fCurrentIndex = index;
if (index == CharDataChunk.CHUNK_SIZE)
slowLoadNextChar();
else
fMostRecentChar = data[index] & 0xFFFF;
return true;
}
CharDataChunk dataChunk = fCurrentChunk;
int offset = fCurrentOffset;
int savedIndex = index;
int i = 0;
while (index < CharDataChunk.CHUNK_SIZE) {
if (data[index++] != s[i++])
return false;
}
slowLoadNextChar();
data = fMostRecentData;
index = 0;
while (i < length) {
if (data[index++] != s[i++]) {
fCurrentChunk = dataChunk;
fCurrentIndex = savedIndex;
fCurrentOffset = offset;
fMostRecentData = dataChunk.toCharArray();
fMostRecentChar = fMostRecentData[savedIndex] & 0xFFFF;
return false;
}
}
fCharacterCounter += length;
fCurrentOffset += length;
fCurrentIndex = index;
if (index == CharDataChunk.CHUNK_SIZE)
slowLoadNextChar();
else
fMostRecentChar = data[index] & 0xFFFF;
return true;
}
public int scanInvalidChar() throws Exception {
int ch = fMostRecentChar;
if (ch == 0x0A) {
fLinefeedCounter++;
fCharacterCounter = 1;
loadNextChar();
} else if (ch == 0) {
if (atEOF(fCurrentOffset + 1)) {
return changeReaders().scanInvalidChar();
}
if (fDeferredErrors != null) {
for (int i = 0; i < fDeferredErrors.size(); i++) {
DeferredError de = (DeferredError)fDeferredErrors.elementAt(i);
if (de.offset == fCurrentIndex) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
de.errorCode,
0,
de.args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
fDeferredErrors.removeElementAt(i);
fCharacterCounter++;
loadNextChar();
return -1;
}
}
}
fCharacterCounter++;
loadNextChar();
} else {
fCharacterCounter++;
if (ch >= 0xD800 && ch < 0xDC00) {
int ch2 = loadNextChar();
if (ch2 >= 0xDC00 && ch2 < 0xE000) {
ch = ((ch-0xD800)<<10)+(ch2-0xDC00)+0x10000;
loadNextChar();
}
} else
loadNextChar();
}
return ch;
}
public int scanCharRef(boolean hex) throws Exception {
int ch = fMostRecentChar;
if (ch == 0) {
if (atEOF(fCurrentOffset + 1)) {
return changeReaders().scanCharRef(hex);
}
return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR;
}
int num = 0;
if (hex) {
if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0)
return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR;
num = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10);
} else {
if (ch < '0' || ch > '9')
return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR;
num = ch - '0';
}
fCharacterCounter++;
loadNextChar();
boolean toobig = false;
while (true) {
ch = fMostRecentChar;
if (ch == 0)
break;
if (hex) {
if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0)
break;
} else {
if (ch < '0' || ch > '9')
break;
}
fCharacterCounter++;
loadNextChar();
if (hex) {
int dig = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10);
num = (num << 4) + dig;
} else {
int dig = ch - '0';
num = (num * 10) + dig;
}
if (num > 0x10FFFF) {
toobig = true;
num = 0;
}
}
if (ch != ';')
return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED;
fCharacterCounter++;
loadNextChar();
if (toobig)
return XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE;
return num;
}
public int scanStringLiteral() throws Exception {
boolean single;
if (!(single = lookingAtChar('\'', true)) && !lookingAtChar('\"', true)) {
return XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED;
}
int offset = fCurrentOffset;
char qchar = single ? '\'' : '\"';
while (!lookingAtChar(qchar, false)) {
if (!lookingAtValidChar(true)) {
return XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR;
}
}
int stringIndex = addString(offset, fCurrentOffset - offset);
lookingAtChar(qchar, true); // move past qchar
return stringIndex;
}
// [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
// | "'" ([^<&'] | Reference)* "'"
public int scanAttValue(char qchar, boolean asSymbol) throws Exception
{
int offset = fCurrentOffset;
while (true) {
if (lookingAtChar(qchar, false)) {
break;
}
if (lookingAtChar(' ', true)) {
continue;
}
if (lookingAtSpace(false)) {
return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX;
}
if (lookingAtChar('&', false)) {
return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX;
}
if (lookingAtChar('<', false)) {
return XMLEntityHandler.ATTVALUE_RESULT_LESSTHAN;
}
if (!lookingAtValidChar(true)) {
return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR;
}
}
int result = asSymbol ? addSymbol(offset, fCurrentOffset - offset) : addString(offset, fCurrentOffset - offset);
lookingAtChar(qchar, true);
return result;
}
// [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
// | "'" ([^%&'] | PEReference | Reference)* "'"
public int scanEntityValue(int qchar, boolean createString) throws Exception
{
int offset = fCurrentOffset;
while (true) {
if (atEOF(fCurrentOffset + 1)) {
changeReaders();
return XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT;
}
if (qchar != -1 && lookingAtChar((char)qchar, false)) {
if (!createString)
return XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED;
break;
}
if (lookingAtChar('&', false)) {
return XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE;
}
if (lookingAtChar('%', false)) {
return XMLEntityHandler.ENTITYVALUE_RESULT_PEREF;
}
if (!lookingAtValidChar(true)) {
return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR;
}
}
int result = addString(offset, fCurrentOffset - offset);
lookingAtChar((char)qchar, true);
return result;
}
public int scanName(char fastcheck) throws Exception {
int ch = fMostRecentChar;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0)
return -1;
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0)
return -1;
}
int offset = fCurrentOffset;
int index = fCurrentIndex;
char[] data = fMostRecentData;
if (++index == CharDataChunk.CHUNK_SIZE) {
slowLoadNextChar();
index = 0;
data = fMostRecentData;
}
fCharacterCounter++;
fCurrentOffset++;
int hashcode = 0;
while (true) {
hashcode = StringHasher.hashChar(hashcode, ch);
ch = data[index] & 0xFFFF;
if (fastcheck == ch)
break;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0)
break;
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0)
break;
}
if (++index == CharDataChunk.CHUNK_SIZE) {
slowLoadNextChar();
index = 0;
data = fMostRecentData;
}
fCharacterCounter++;
fCurrentOffset++;
}
fCurrentIndex = index;
fMostRecentChar = ch;
hashcode = StringHasher.finishHash(hashcode);
int length = fCurrentOffset - offset;
int nameIndex = fCurrentChunk.addSymbol(offset, length, hashcode);
return nameIndex;
}
public boolean scanExpectedName(char fastcheck, StringPool.CharArrayRange expectedName) throws Exception {
char[] expected = expectedName.chars;
int offset = expectedName.offset;
int len = expectedName.length;
int ch = fMostRecentChar;
for (int i = 0; i < len; i++) {
if (ch != expected[offset++]) {
skipPastNmtoken(fastcheck);
return false;
}
fCharacterCounter++;
fCurrentOffset++;
if (++fCurrentIndex == CharDataChunk.CHUNK_SIZE)
ch = slowLoadNextChar();
else
ch = (fMostRecentChar = fMostRecentData[fCurrentIndex] & 0xFFFF);
}
if (ch == fastcheck)
return true;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0)
return true;
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0)
return true;
}
skipPastNmtoken(fastcheck);
return false;
}
public void scanQName(char fastcheck, QName qname) throws Exception {
int ch = fMostRecentChar;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0) {
qname.clear();
return;
}
if (ch == ':') {
qname.clear();
return;
}
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) {
qname.clear();
return;
}
}
int offset = fCurrentOffset;
int index = fCurrentIndex;
char[] data = fMostRecentData;
if (++index == CharDataChunk.CHUNK_SIZE) {
slowLoadNextChar();
index = 0;
data = fMostRecentData;
}
fCharacterCounter++;
fCurrentOffset++;
int hashcode = 0;
int prefixend = -1;
while (true) {
hashcode = StringHasher.hashChar(hashcode, ch);
ch = data[index] & 0xFFFF;
if (fastcheck == ch)
break;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0)
break;
if (ch == ':') {
if (prefixend != -1)
break;
prefixend = fCurrentOffset;
// We need to peek ahead one character. If the next character is not a
// valid initial name character, or is another colon, then we cannot meet
// both the Prefix and LocalPart productions for the QName production,
// which means that there is no Prefix and we need to terminate the QName
// at the first colon.
if (index + 1 == CharDataChunk.CHUNK_SIZE) {
CharDataChunk savedChunk = fCurrentChunk;
int savedOffset = fCurrentOffset;
ch = slowLoadNextChar();
fCurrentChunk = savedChunk;
fCurrentOffset = savedOffset;
fMostRecentData = savedChunk.toCharArray();
} else
ch = data[index + 1] & 0xFFFF;
boolean lpok = true;
if (ch < 0x80) {
if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0 || ch == ':')
lpok = false;
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0)
lpok = false;
}
ch = ':';
if (!lpok) {
prefixend = -1;
break;
}
}
} else {
if (!fCalledCharPropInit) {
XMLCharacterProperties.initCharFlags();
fCalledCharPropInit = true;
}
if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0)
break;
}
if (++index == CharDataChunk.CHUNK_SIZE) {
slowLoadNextChar();
index = 0;
data = fMostRecentData;
}
fCharacterCounter++;
fCurrentOffset++;
}
fCurrentIndex = index;
fMostRecentChar = ch;
hashcode = StringHasher.finishHash(hashcode);
int length = fCurrentOffset - offset;
qname.rawname = fCurrentChunk.addSymbol(offset, length, hashcode);
qname.prefix = prefixend == -1 ? -1 : addSymbol(offset, prefixend - offset);
qname.localpart = prefixend == -1 ? qname.rawname : addSymbol(prefixend + 1, fCurrentOffset - (prefixend + 1));
qname.uri = -1;
} // scanQName(char,QName)
// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
public int scanContent(QName element) throws Exception {
if (fCallClearPreviousChunk && fCurrentChunk.clearPreviousChunk())
fCallClearPreviousChunk = false;
int charDataOffset = fCurrentOffset;
int ch = fMostRecentChar;
if (ch < 0x80) {
switch (XMLCharacterProperties.fgAsciiWSCharData[ch]) {
case 0:
fCharacterCounter++;
ch = loadNextChar();
break;
case 1:
fCharacterCounter++;
ch = loadNextChar();
if (!fInCDSect) {
return recognizeMarkup(ch);
}
break;
case 2:
fCharacterCounter++;
ch = loadNextChar();
if (!fInCDSect) {
return recognizeReference(ch);
}
break;
case 3:
fCharacterCounter++;
ch = loadNextChar();
if (ch != ']')
break;
if (fCurrentIndex + 1 == CharDataChunk.CHUNK_SIZE) {
CharDataChunk dataChunk = fCurrentChunk;
int index = fCurrentIndex;
int offset = fCurrentOffset;
if (loadNextChar() != '>') {
fCurrentChunk = dataChunk;
fCurrentIndex = index;
fCurrentOffset = offset;
fMostRecentData = dataChunk.toCharArray();
fMostRecentChar = ']';
break;
}
} else {
if (fMostRecentData[fCurrentIndex + 1] != '>')
break;
fCurrentIndex++;
fCurrentOffset++;
}
loadNextChar();
fCharacterCounter += 2;
return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT;
case 4: // invalid char
if (ch == 0 && atEOF(fCurrentOffset + 1)) {
changeReaders();
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite...
}
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR;
case 5:
do {
if (ch == 0x0A) {
fLinefeedCounter++;
fCharacterCounter = 1;
} else
fCharacterCounter++;
ch = loadNextChar();
} while (ch == 0x20 || ch == 0x09 || ch == 0x0A);
if (ch < 0x80) {
switch (XMLCharacterProperties.fgAsciiCharData[ch]) {
case 0:
fCharacterCounter++;
ch = loadNextChar();
break;
case 1:
if (!fInCDSect) {
callCharDataHandler(charDataOffset, fCurrentOffset, true);
fCharacterCounter++;
ch = loadNextChar();
return recognizeMarkup(ch);
}
fCharacterCounter++;
ch = loadNextChar();
break;
case 2:
if (!fInCDSect) {
callCharDataHandler(charDataOffset, fCurrentOffset, true);
fCharacterCounter++;
ch = loadNextChar();
return recognizeReference(ch);
}
fCharacterCounter++;
ch = loadNextChar();
break;
case 3:
int endOffset = fCurrentOffset;
ch = loadNextChar();
if (ch != ']') {
fCharacterCounter++;
break;
}
if (fCurrentIndex + 1 == CharDataChunk.CHUNK_SIZE) {
CharDataChunk dataChunk = fCurrentChunk;
int index = fCurrentIndex;
int offset = fCurrentOffset;
if (loadNextChar() != '>') {
fCurrentChunk = dataChunk;
fCurrentIndex = index;
fCurrentOffset = offset;
fMostRecentData = dataChunk.toCharArray();
fMostRecentChar = ']';
fCharacterCounter++;
break;
}
} else {
if (fMostRecentData[fCurrentIndex + 1] != '>') {
fCharacterCounter++;
break;
}
fCurrentIndex++;
fCurrentOffset++;
}
loadNextChar();
callCharDataHandler(charDataOffset, endOffset, true);
fCharacterCounter += 3;
return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT;
case 4: // invalid char
callCharDataHandler(charDataOffset, fCurrentOffset, true);
if (ch == 0 && atEOF(fCurrentOffset + 1)) {
changeReaders();
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite...
}
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR;
}
} else if (!skipMultiByteCharData(ch)) {
callCharDataHandler(charDataOffset, fCurrentOffset, true);
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR;
}
break;
}
} else if (!skipMultiByteCharData(ch)) {
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR;
}
ch = skipAsciiCharData();
while (true) {
if (ch < 0x80) {
switch (XMLCharacterProperties.fgAsciiCharData[ch]) {
case 0:
fCharacterCounter++;
ch = loadNextChar();
break;
case 1:
if (!fInCDSect) {
callCharDataHandler(charDataOffset, fCurrentOffset, false);
fCharacterCounter++;
ch = loadNextChar();
return recognizeMarkup(ch);
}
fCharacterCounter++;
ch = loadNextChar();
break;
case 2:
if (!fInCDSect) {
callCharDataHandler(charDataOffset, fCurrentOffset, false);
fCharacterCounter++;
ch = loadNextChar();
return recognizeReference(ch);
}
fCharacterCounter++;
ch = loadNextChar();
break;
case 3:
int endOffset = fCurrentOffset;
ch = loadNextChar();
if (ch != ']') {
fCharacterCounter++;
break;
}
if (fCurrentIndex + 1 == CharDataChunk.CHUNK_SIZE) {
CharDataChunk dataChunk = fCurrentChunk;
int index = fCurrentIndex;
int offset = fCurrentOffset;
if (loadNextChar() != '>') {
fCurrentChunk = dataChunk;
fCurrentIndex = index;
fCurrentOffset = offset;
fMostRecentData = dataChunk.toCharArray();
fMostRecentChar = ']';
fCharacterCounter++;
break;
}
} else {
if (fMostRecentData[fCurrentIndex + 1] != '>') {
fCharacterCounter++;
break;
}
fCurrentIndex++;
fCurrentOffset++;
}
loadNextChar();
callCharDataHandler(charDataOffset, endOffset, false);
fCharacterCounter += 3;
return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT;
case 4: // invalid char
if (ch == 0x0A) {
fLinefeedCounter++;
fCharacterCounter = 1;
ch = loadNextChar();
break;
}
callCharDataHandler(charDataOffset, fCurrentOffset, false);
if (ch == 0 && atEOF(fCurrentOffset + 1)) {
changeReaders();
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite...
}
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR;
}
} else {
if (!skipMultiByteCharData(ch)) {
callCharDataHandler(charDataOffset, fCurrentOffset, false);
return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR;
}
ch = fMostRecentChar;
}
}
}
// Private data members
private static final char[] cdata_string = { 'C','D','A','T','A','[' };
private StringPool fStringPool = null;
private boolean fCalledCharPropInit = false;
private boolean fCallClearPreviousChunk = true;
private Vector fDeferredErrors = null;
// Private classes
private class DeferredError {
int errorCode;
Object[] args;
int offset;
DeferredError(int ec, Object[] a, int o) {
errorCode = ec;
args = a;
offset = o;
}
}
// Private methods
/*
* Return a result code for scanContent when the character data
* ends with a less-than character.
*/
private int recognizeMarkup(int ch) throws Exception {
switch (ch) {
case 0:
return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT;
case '?':
fCharacterCounter++;
loadNextChar();
return XMLEntityHandler.CONTENT_RESULT_START_OF_PI;
case '!':
fCharacterCounter++;
ch = loadNextChar();
if (ch == 0) {
fCharacterCounter
fCurrentOffset
return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT;
}
if (ch == '-') {
fCharacterCounter++;
ch = loadNextChar();
if (ch == 0) {
fCharacterCounter -= 2;
fCurrentOffset -= 2;
return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT;
}
if (ch == '-') {
fCharacterCounter++;
loadNextChar();
return XMLEntityHandler.CONTENT_RESULT_START_OF_COMMENT;
}
break;
}
if (ch == '[') {
for (int i = 0; i < 6; i++) {
fCharacterCounter++;
ch = loadNextChar();
if (ch == 0) {
fCharacterCounter -= (2 + i);
fCurrentOffset -= (2 + i);
return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT;
}
if (ch != cdata_string[i]) {
return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED;
}
}
fCharacterCounter++;
loadNextChar();
return XMLEntityHandler.CONTENT_RESULT_START_OF_CDSECT;
}
break;
case '/':
fCharacterCounter++;
loadNextChar();
return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG;
default:
return XMLEntityHandler.CONTENT_RESULT_START_OF_ELEMENT;
}
return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED;
}
/*
* Return a result code for scanContent when the character data
* ends with an ampersand character.
*/
private int recognizeReference(int ch) throws Exception {
if (ch == 0) {
return XMLEntityHandler.CONTENT_RESULT_REFERENCE_END_OF_INPUT;
}
// [67] Reference ::= EntityRef | CharRef
// [68] EntityRef ::= '&' Name ';'
// [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
if (ch == '
fCharacterCounter++;
loadNextChar();
return XMLEntityHandler.CONTENT_RESULT_START_OF_CHARREF;
} else {
return XMLEntityHandler.CONTENT_RESULT_START_OF_ENTITYREF;
}
}
/*
* Skip over a multi-byte character.
*/
private boolean skipMultiByteCharData(int ch) throws Exception {
if (ch < 0xD800) {
loadNextChar();
return true;
}
if (ch > 0xFFFD)
return false;
if (ch >= 0xDC00 && ch < 0xE000)
return false;
if (ch >= 0xD800 && ch < 0xDC00) {
CharDataChunk savedChunk = fCurrentChunk;
int savedIndex = fCurrentIndex;
int savedOffset = fCurrentOffset;
ch = loadNextChar();
if (ch < 0xDC00 || ch >= 0xE000) {
fCurrentChunk = savedChunk;
fCurrentIndex = savedIndex;
fCurrentOffset = savedOffset;
fMostRecentData = savedChunk.toCharArray();
fMostRecentChar = fMostRecentData[savedIndex] & 0xFFFF;
return false;
}
}
loadNextChar();
return true;
}
/*
* Skip over contiguous ascii character data.
*
* @return the character skipped
* @exception java.lang.Exception
*/
private int fskipAsciiCharData() throws Exception {
int index = fCurrentIndex;
int offset = fCurrentOffset - index;
while (true) {
char[] data = fMostRecentData;
while (index < CharDataChunk.CHUNK_SIZE) {
int ch = data[index] & 0xFFFF;
if (ch >= 0x80) {
fCurrentOffset = offset + index;
fCurrentIndex = index;
fMostRecentChar = ch;
return ch;
}
if (XMLCharacterProperties.fgAsciiCharData[ch] == 0) {
fCharacterCounter++;
} else if (ch == 0x0A) {
fLinefeedCounter++;
fCharacterCounter = 1;
} else {
fCurrentOffset = offset + index;
fCurrentIndex = index;
fMostRecentChar = ch;
return ch;
}
index++;
}
offset += index;
slowLoadNextChar();
index = 0;
}
}
/*
* Report character data to the parser through the entity handler interface.
*
* @param offset the offset of the start of the character data
* @param endOffset the offset of the end of the character data
* @param isWhitespace true if the character data is whitespace
* @exception java.lang.Exception
*/
private void callCharDataHandler(int offset, int endOffset, boolean isWhitespace) throws Exception {
int length = endOffset - offset;
if (!fSendCharDataAsCharArray) {
int stringIndex = addString(offset, length);
if (isWhitespace)
fCharDataHandler.processWhitespace(stringIndex);
else
fCharDataHandler.processCharacters(stringIndex);
return;
}
CharDataChunk dataChunk = fCurrentChunk.chunkFor(offset);
int index = offset & CharDataChunk.CHUNK_MASK;
if (index + length <= CharDataChunk.CHUNK_SIZE) {
// All the chars are in the same chunk
if (length != 0) {
if (isWhitespace)
fCharDataHandler.processWhitespace(dataChunk.toCharArray(), index, length);
else
fCharDataHandler.processCharacters(dataChunk.toCharArray(), index, length);
}
return;
}
// The data is spread across chunks.
int count = length;
int nbytes = CharDataChunk.CHUNK_SIZE - index;
if (isWhitespace)
fCharDataHandler.processWhitespace(dataChunk.toCharArray(), index, nbytes);
else
fCharDataHandler.processCharacters(dataChunk.toCharArray(), index, nbytes);
count -= nbytes;
// Use each Chunk in turn until we are done.
do {
dataChunk = dataChunk.nextChunk();
if (dataChunk == null) {
throw new RuntimeException(new ImplementationMessages().createMessage(null, ImplementationMessages.INT_DCN, 0, null));
}
nbytes = count <= CharDataChunk.CHUNK_SIZE ? count : CharDataChunk.CHUNK_SIZE;
if (isWhitespace)
fCharDataHandler.processWhitespace(dataChunk.toCharArray(), 0, nbytes);
else
fCharDataHandler.processCharacters(dataChunk.toCharArray(), 0, nbytes);
count -= nbytes;
} while (count > 0);
}
/*
* Advance the reader's notion of where it is, moving on to the next chunk.
*
* @return The next character that will be processed.
* @exception java.lang.Exception
*/
private int slowLoadNextChar() throws Exception {
fCallClearPreviousChunk = true;
if (fCurrentChunk.nextChunk() != null) {
fCurrentChunk = fCurrentChunk.nextChunk();
fCurrentIndex = 0;
fMostRecentData = fCurrentChunk.toCharArray();
return (fMostRecentChar = fMostRecentData[fCurrentIndex] & 0xFFFF);
} else {
fCurrentChunk = CharDataChunk.createChunk(fStringPool, fCurrentChunk);
return fillCurrentChunk();
}
}
/*
* Advance the reader's notion of where it is
*
* @return The next character that will be processed.
* @exception java.lang.Exception
*/
private int loadNextChar() throws Exception {
fCurrentOffset++;
if (++fCurrentIndex == CharDataChunk.CHUNK_SIZE)
return slowLoadNextChar();
return (fMostRecentChar = fMostRecentData[fCurrentIndex] & 0xFFFF);
}
/*
* Would the reader be at end of file at a given offset?
*
* @param offset the offset to test for being at EOF
* @return true if being at offset would mean being at or beyond EOF
*/
private boolean atEOF(int offset) {
return (offset > fLength);
}
}
|
package com.Webtrekk.SDKTest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
import android.test.InstrumentationTestRunner;
import com.Webtrekk.SDKTest.SimpleHTTPServer.HttpServer;
import com.webtrekk.webtrekksdk.Utils.HelperFunctions;
import com.webtrekk.webtrekksdk.Utils.WebtrekkLogging;
import com.webtrekk.webtrekksdk.Webtrekk;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ScheduledExecutorService;
public class ActivityInstrumentationTestCase2BaseMain<T extends Activity> extends ActivityInstrumentationTestCase2<T> {
protected Application mApplication;
private Thread.UncaughtExceptionHandler mOldHandler;
protected boolean mIsErrorHandlerTest;
protected boolean mIsExternalCall;
static private String IS_EXTERNAL = "external";
protected boolean mIsCDBTestRequest;
public ActivityInstrumentationTestCase2BaseMain(Class<T> activityClass) {
super(activityClass);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void setUp() throws Exception {
super.setUp();
//refresh webtrekk instance
refreshWTInstance();
mOldHandler = Thread.getDefaultUncaughtExceptionHandler();
mApplication = (Application)getInstrumentation().getTargetContext().getApplicationContext();
if (!mIsErrorHandlerTest)
deleteErrorHandlerFile(mApplication);
if (!mIsCDBTestRequest)
deleteCDBRepeatRequestInfo();
Bundle arguments = ((InstrumentationTestRunner)getInstrumentation()).getArguments();
if (arguments.size() > 0)
WebtrekkLogging.log("Receive arguments for test:"+arguments);
mIsExternalCall = arguments.getString(IS_EXTERNAL) != null;
}
@Override
public void tearDown() throws Exception {
Webtrekk webtrekk = Webtrekk.getInstance();
if (webtrekk.isInitialized())
webtrekk.stopTracking();
Thread.setDefaultUncaughtExceptionHandler(mOldHandler);
unregisterCallback();
getInstrumentation().waitForIdleSync();
stopSendThread();
super.tearDown();
}
protected void deleteErrorHandlerFile(Context context)
{
File loadFile = new File(context.getFilesDir().getPath() + File.separator+"exception.txt");
loadFile.delete();
}
protected void refreshWTInstance() {
Class<Webtrekk> wtClass = Webtrekk.class;
try {
for (Class<?> classObj : wtClass.getDeclaredClasses()) {
if (classObj.getName().contains("SingletonHolder")) {
Field field = null;
field = classObj.getDeclaredField("webtrekk");
field.setAccessible(true);
Constructor<Webtrekk> wtConstr = wtClass.getDeclaredConstructor();
wtConstr.setAccessible(true);
field.set(null, wtConstr.newInstance());
}
}
} catch (NoSuchFieldException e) {
WebtrekkLogging.log("Can't refresh Webtrekk instance");
} catch (NoSuchMethodException e) {
WebtrekkLogging.log("Can't refresh Webtrekk instance");
} catch (InstantiationException e) {
WebtrekkLogging.log("Can't refresh Webtrekk instance");
} catch (IllegalAccessException e) {
WebtrekkLogging.log("Can't refresh Webtrekk instance");
} catch (InvocationTargetException e) {
WebtrekkLogging.log("Can't refresh Webtrekk instance");
}
}
protected void unregisterCallback()
{
if (mApplication == null)
{
WebtrekkLogging.log("Error unregister callback. Application reference is null");
return;
}
if (!Webtrekk.getInstance().isInitialized())
{
WebtrekkLogging.log("Error unregister callback. Webtrekk isn't initialized");
return;
}
Webtrekk webtrekk = Webtrekk.getInstance();
try {
Field callbackField = Webtrekk.class.getDeclaredField("mCallbacks");
callbackField.setAccessible(true);
Application.ActivityLifecycleCallbacks callback = (Application.ActivityLifecycleCallbacks) callbackField.get(webtrekk);
mApplication.unregisterActivityLifecycleCallbacks(callback);
} catch (NoSuchFieldException e) {
WebtrekkLogging.log("Can't remove activity callback");
} catch (IllegalAccessException e) {
WebtrekkLogging.log("Can't remove activity callback");
}
}
protected void finishActivitySync(Activity activity)
{
finishActivitySync(activity, getInstrumentation(), true);
}
protected void finishActivitySync(Activity activity, boolean killApplication)
{
ActivityInstrumentationTestCase2BaseMain.finishActivitySync(activity, getInstrumentation(), killApplication);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
static public void finishActivitySync(Activity activity, Instrumentation instrumentation, boolean killApplication)
{ activity.finish();
//give activity one minute to finish
long currentTime = System.currentTimeMillis();
boolean finishTimeout = false;
int activityHash = activity.hashCode();
while (!activity.isDestroyed() && !finishTimeout) {
instrumentation.waitForIdleSync();
finishTimeout = (System.currentTimeMillis() - currentTime) > 140000;
}
if (finishTimeout) {
WebtrekkLogging.log("finishActivitySync: finished by timeout. Hash:" + activityHash);
}
}
private void deleteCDBRepeatRequestInfo()
{
SharedPreferences preferences = HelperFunctions.getWebTrekkSharedPreference(getInstrumentation().getTargetContext());
if (preferences.contains("LAST_CBD_REQUEST_DATE"))
preferences.edit().remove("LAST_CBD_REQUEST_DATE").apply();
}
private void stopSendThread()
{
if (mApplication == null)
{
WebtrekkLogging.log("Error unregister callback. Application reference is null");
return;
}
if (!Webtrekk.getInstance().isInitialized())
{
WebtrekkLogging.log("Error unregister callback. Webtrekk isn't initialized");
return;
}
Webtrekk webtrekk = Webtrekk.getInstance();
try {
Field callbackField = Webtrekk.class.getDeclaredField("mTimerService");
callbackField.setAccessible(true);
ScheduledExecutorService threadService = (ScheduledExecutorService) callbackField.get(webtrekk);
threadService.shutdownNow();
} catch (NoSuchFieldException e) {
WebtrekkLogging.log("Can't remove activity callback");
} catch (IllegalAccessException e) {
WebtrekkLogging.log("Can't remove activity callback");
}
}
}
|
package com.topologi.diffx.xml;
import java.io.IOException;
import java.io.StringWriter;
/**
* An XML which writes on to a string.
*
* <p>This XML writer is backed by a {@link StringWriter} and will defer the XML writer's method to
* either a {@link XMLWriterImpl} or {@link XMLWriterNSImpl} depending on whether namespace support is
* required.
*
* <p>The write methods do not throw any {@link IOException}.
*
* <p>If the write is not set to support namespaces, the method which require a namespace URI will
* throw an {@link UnsupportedOperationException}.
*
* @author Christophe Lauret
* @version 7 March 2012
*/
public final class XMLStringWriter implements XMLWriter {
/**
* Wraps an XML Writer
*/
private final StringWriter writer;
/**
* Wraps an XML Writer
*/
private final XMLWriter xml;
/**
* <p>Creates a new XML string writer.
*
* @param namespaces Whether this XML writer should use namespaces.
*/
public XMLStringWriter(boolean namespaces) {
this(namespaces, false);
}
/**
* <p>Create a new XML string writer.
*
* @param namespaces Whether this XML writer should use namespaces.
* @param indent Set the indentation flag.
*/
public XMLStringWriter(boolean namespaces, boolean indent) {
this.writer = new StringWriter();
this.xml = namespaces? new XMLWriterNSImpl(this.writer, indent) : new XMLWriterImpl(this.writer, indent);
}
// XML Writer methods
@Override
public void xmlDecl() {
try {
this.xml.xmlDecl();
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void setIndentChars(String spaces) {
this.xml.setIndentChars(spaces);
}
@Override
public void writeText(char c) {
try {
this.xml.writeText(c);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writeText(String text) {
try {
this.xml.writeText(text);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writeText(char[] text, int off, int len) {
try {
this.xml.writeText(text, off, len);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writeCDATA(String cdata) {
try {
this.xml.writeCDATA(cdata);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writeXML(String text) {
try {
this.xml.writeXML(text);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writeXML(char[] text, int off, int len) {
try {
this.xml.writeXML(text, off, len);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writeComment(String comment) {
try {
this.xml.writeComment(comment);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void writePI(String target, String data) {
try {
this.xml.writePI(target, data);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void openElement(String name) {
try {
this.xml.openElement(name);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void openElement(String name, boolean hasChildren) {
try {
this.xml.openElement(name, hasChildren);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void openElement(String uri, String name, boolean hasChildren) {
try {
this.xml.openElement(uri, name, hasChildren);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void closeElement() {
try {
this.xml.closeElement();
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void element(String name, String text) {
try {
this.xml.element(name, text);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void emptyElement(String element) {
try {
this.xml.emptyElement(element);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void emptyElement(String uri, String element) {
try {
this.xml.emptyElement(element);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void attribute(String name, String value) {
try {
this.xml.attribute(name, value);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void attribute(String name, int value) {
try {
this.xml.attribute(name, value);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void attribute(String uri, String name, String value) {
try {
this.xml.attribute(uri, name, value);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void attribute(String uri, String name, int value) {
try {
this.xml.attribute(uri, name, value);
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void setPrefixMapping(String uri, String prefix) {
this.xml.setPrefixMapping(uri, prefix);
}
@Override
public void flush() {
try {
this.xml.flush();
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
@Override
public void close() throws UnclosedElementException {
try {
this.xml.close();
} catch (IOException ex) {
// Will not occur
doNothing();
}
}
/**
* Returns the XML content as a {@link String}.
*
* @return the XML content as a {@link String}.
*/
@Override
public String toString() {
return this.writer.toString();
}
/**
* Do nothing
*/
private static void doNothing(){
}
}
|
package com.jme3.input;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.input.controls.*;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import java.io.IOException;
/**
* A camera that follows a spatial and can turn around it by dragging the mouse
* @author nehon
*/
public class ChaseCamera implements ActionListener, AnalogListener, Control {
protected Spatial target = null;
protected float minVerticalRotation = 0.00f;
protected float maxVerticalRotation = FastMath.PI / 2;
protected float minDistance = 1.0f;
protected float maxDistance = 40.0f;
protected float distance = 20;
protected float rotationSpeed = 1.0f;
protected float rotation = 0;
protected float trailingRotationInertia = 0.05f;
protected float zoomSensitivity = 2f;
protected float rotationSensitivity = 5f;
protected float chasingSensitivity = 5f;
protected float trailingSensitivity = 0.5f;
protected float vRotation = FastMath.PI / 6;
protected boolean smoothMotion = false;
protected boolean trailingEnabled = true;
protected float rotationLerpFactor = 0;
protected float trailingLerpFactor = 0;
protected boolean rotating = false;
protected boolean vRotating = false;
protected float targetRotation = rotation;
protected InputManager inputManager;
protected Vector3f initialUpVec;
protected float targetVRotation = vRotation;
protected float vRotationLerpFactor = 0;
protected float targetDistance = distance;
protected float distanceLerpFactor = 0;
protected boolean zooming = false;
protected boolean trailing = false;
protected boolean chasing = false;
protected boolean veryCloseRotation = true;
protected boolean canRotate;
protected float offsetDistance = 0.002f;
protected Vector3f prevPos;
protected boolean targetMoves = false;
protected boolean enabled = true;
protected Camera cam = null;
protected final Vector3f targetDir = new Vector3f();
protected float previousTargetRotation;
protected final Vector3f pos = new Vector3f();
protected Vector3f targetLocation = new Vector3f(0, 0, 0);
protected boolean dragToRotate = true;
protected Vector3f lookAtOffset = new Vector3f(0, 0, 0);
protected boolean leftClickRotate = true;
protected boolean rightClickRotate = true;
protected Vector3f temp = new Vector3f(0, 0, 0);
protected boolean invertYaxis = false;
protected boolean invertXaxis = false;
protected final static String ChaseCamDown = "ChaseCamDown";
protected final static String ChaseCamUp = "ChaseCamUp";
protected final static String ChaseCamZoomIn = "ChaseCamZoomIn";
protected final static String ChaseCamZoomOut = "ChaseCamZoomOut";
protected final static String ChaseCamMoveLeft = "ChaseCamMoveLeft";
protected final static String ChaseCamMoveRight = "ChaseCamMoveRight";
protected final static String ChaseCamToggleRotate = "ChaseCamToggleRotate";
protected boolean zoomin;
protected boolean hideCursorOnRotate = true;
/**
* Constructs the chase camera
* @param cam the application camera
* @param target the spatial to follow
*/
public ChaseCamera(Camera cam, final Spatial target) {
this(cam);
target.addControl(this);
}
/**
* Constructs the chase camera
* if you use this constructor you have to attach the cam later to a spatial
* doing spatial.addControl(chaseCamera);
* @param cam the application camera
*/
public ChaseCamera(Camera cam) {
this.cam = cam;
initialUpVec = cam.getUp().clone();
}
/**
* Constructs the chase camera, and registers inputs
* if you use this constructor you have to attach the cam later to a spatial
* doing spatial.addControl(chaseCamera);
* @param cam the application camera
* @param inputManager the inputManager of the application to register inputs
*/
public ChaseCamera(Camera cam, InputManager inputManager) {
this(cam);
registerWithInput(inputManager);
}
/**
* Constructs the chase camera, and registers inputs
* @param cam the application camera
* @param target the spatial to follow
* @param inputManager the inputManager of the application to register inputs
*/
public ChaseCamera(Camera cam, final Spatial target, InputManager inputManager) {
this(cam, target);
registerWithInput(inputManager);
}
public void onAction(String name, boolean keyPressed, float tpf) {
if (dragToRotate) {
if (name.equals(ChaseCamToggleRotate) && enabled) {
if (keyPressed) {
canRotate = true;
if (hideCursorOnRotate) {
inputManager.setCursorVisible(false);
}
} else {
canRotate = false;
if (hideCursorOnRotate) {
inputManager.setCursorVisible(true);
}
}
}
}
}
public void onAnalog(String name, float value, float tpf) {
if (name.equals(ChaseCamMoveLeft)) {
rotateCamera(-value);
} else if (name.equals(ChaseCamMoveRight)) {
rotateCamera(value);
} else if (name.equals(ChaseCamUp)) {
vRotateCamera(value);
} else if (name.equals(ChaseCamDown)) {
vRotateCamera(-value);
} else if (name.equals(ChaseCamZoomIn)) {
zoomCamera(-value);
if (zoomin == false) {
distanceLerpFactor = 0;
}
zoomin = true;
} else if (name.equals(ChaseCamZoomOut)) {
zoomCamera(+value);
if (zoomin == true) {
distanceLerpFactor = 0;
}
zoomin = false;
}
}
/**
* Registers inputs with the input manager
* @param inputManager
*/
public final void registerWithInput(InputManager inputManager) {
String[] inputs = {ChaseCamToggleRotate,
ChaseCamDown,
ChaseCamUp,
ChaseCamMoveLeft,
ChaseCamMoveRight,
ChaseCamZoomIn,
ChaseCamZoomOut};
this.inputManager = inputManager;
if (!invertYaxis) {
inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
} else {
inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
}
inputManager.addMapping(ChaseCamZoomIn, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false));
inputManager.addMapping(ChaseCamZoomOut, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true));
if (!invertXaxis) {
inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, false));
} else {
inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, true));
}
inputManager.addMapping(ChaseCamToggleRotate, new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
inputManager.addMapping(ChaseCamToggleRotate, new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(this, inputs);
}
/**
* Sets custom triggers for toggleing the rotation of the cam
* deafult are
* new MouseButtonTrigger(MouseInput.BUTTON_LEFT) left mouse button
* new MouseButtonTrigger(MouseInput.BUTTON_RIGHT) right mouse button
* @param triggers
*/
public void setToggleRotationTrigger(Trigger... triggers) {
inputManager.deleteMapping(ChaseCamToggleRotate);
inputManager.addMapping(ChaseCamToggleRotate, triggers);
inputManager.addListener(this, ChaseCamToggleRotate);
}
/**
* Sets custom triggers for zomming in the cam
* default is
* new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true) mouse wheel up
* @param triggers
*/
public void setZoomInTrigger(Trigger... triggers) {
inputManager.deleteMapping(ChaseCamZoomIn);
inputManager.addMapping(ChaseCamZoomIn, triggers);
inputManager.addListener(this, ChaseCamZoomIn);
}
/**
* Sets custom triggers for zomming out the cam
* default is
* new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false) mouse wheel down
* @param triggers
*/
public void setZoomOutTrigger(Trigger... triggers) {
inputManager.deleteMapping(ChaseCamZoomOut);
inputManager.addMapping(ChaseCamZoomOut, triggers);
inputManager.addListener(this, ChaseCamZoomOut);
}
protected void computePosition() {
float hDistance = (distance) * FastMath.sin((FastMath.PI / 2) - vRotation);
pos.set(hDistance * FastMath.cos(rotation), (distance) * FastMath.sin(vRotation), hDistance * FastMath.sin(rotation));
pos.addLocal(target.getWorldTranslation());
}
//rotate the camera around the target on the horizontal plane
protected void rotateCamera(float value) {
if (!canRotate || !enabled) {
return;
}
rotating = true;
targetRotation += value * rotationSpeed;
}
//move the camera toward or away the target
protected void zoomCamera(float value) {
if (!enabled) {
return;
}
zooming = true;
targetDistance += value * zoomSensitivity;
if (targetDistance > maxDistance) {
targetDistance = maxDistance;
}
if (targetDistance < minDistance) {
targetDistance = minDistance;
}
if (veryCloseRotation) {
if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) {
targetVRotation = minVerticalRotation;
}
}
}
//rotate the camera around the target on the vertical plane
protected void vRotateCamera(float value) {
if (!canRotate || !enabled) {
return;
}
vRotating = true;
float lastGoodRot = targetVRotation;
targetVRotation += value * rotationSpeed;
if (targetVRotation > maxVerticalRotation) {
targetVRotation = lastGoodRot;
}
if (veryCloseRotation) {
if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) {
targetVRotation = minVerticalRotation;
} else if (targetVRotation < -FastMath.DEG_TO_RAD * 90) {
targetVRotation = lastGoodRot;
}
} else {
if ((targetVRotation < minVerticalRotation)) {
targetVRotation = lastGoodRot;
}
}
}
/**
* Updates the camera, should only be called internally
*/
protected void updateCamera(float tpf) {
if (enabled) {
targetLocation.set(target.getWorldTranslation()).addLocal(lookAtOffset);
if (smoothMotion) {
//computation of target direction
targetDir.set(targetLocation).subtractLocal(prevPos);
float dist = targetDir.length();
//Low pass filtering on the target postition to avoid shaking when physics are enabled.
if (offsetDistance < dist) {
//target moves, start chasing.
chasing = true;
//target moves, start trailing if it has to.
if (trailingEnabled) {
trailing = true;
}
//target moves...
targetMoves = true;
} else {
//if target was moving, we compute a slight offset in rotation to avoid a rought stop of the cam
//We do not if the player is rotationg the cam
if (targetMoves && !canRotate) {
if (targetRotation - rotation > trailingRotationInertia) {
targetRotation = rotation + trailingRotationInertia;
} else if (targetRotation - rotation < -trailingRotationInertia) {
targetRotation = rotation - trailingRotationInertia;
}
}
//Target stops
targetMoves = false;
}
//the user is rotating the cam by dragging the mouse
if (canRotate) {
//reseting the trailing lerp factor
trailingLerpFactor = 0;
//stop trailing user has the control
trailing = false;
}
if (trailingEnabled && trailing) {
if (targetMoves) {
//computation if the inverted direction of the target
Vector3f a = targetDir.negate().normalizeLocal();
//the x unit vector
Vector3f b = Vector3f.UNIT_X;
//2d is good enough
a.y = 0;
//computation of the rotation angle between the x axis and the trail
if (targetDir.z > 0) {
targetRotation = FastMath.TWO_PI - FastMath.acos(a.dot(b));
} else {
targetRotation = FastMath.acos(a.dot(b));
}
if (targetRotation - rotation > FastMath.PI || targetRotation - rotation < -FastMath.PI) {
targetRotation -= FastMath.TWO_PI;
}
//if there is an important change in the direction while trailing reset of the lerp factor to avoid jumpy movements
if (targetRotation != previousTargetRotation && FastMath.abs(targetRotation - previousTargetRotation) > FastMath.PI / 8) {
trailingLerpFactor = 0;
}
previousTargetRotation = targetRotation;
}
//computing lerp factor
trailingLerpFactor = Math.min(trailingLerpFactor + tpf * tpf * trailingSensitivity, 1);
//computing rotation by linear interpolation
rotation = FastMath.interpolateLinear(trailingLerpFactor, rotation, targetRotation);
//if the rotation is near the target rotation we're good, that's over
if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) {
trailing = false;
trailingLerpFactor = 0;
}
}
//linear interpolation of the distance while chasing
if (chasing) {
distance = temp.set(targetLocation).subtractLocal(cam.getLocation()).length();
distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * chasingSensitivity * 0.05f), 1);
distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance);
if (targetDistance + 0.01f >= distance && targetDistance - 0.01f <= distance) {
distanceLerpFactor = 0;
chasing = false;
}
}
//linear interpolation of the distance while zooming
if (zooming) {
distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * zoomSensitivity), 1);
distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance);
if (targetDistance + 0.1f >= distance && targetDistance - 0.1f <= distance) {
zooming = false;
distanceLerpFactor = 0;
}
}
//linear interpolation of the rotation while rotating horizontally
if (rotating) {
rotationLerpFactor = Math.min(rotationLerpFactor + tpf * tpf * rotationSensitivity, 1);
rotation = FastMath.interpolateLinear(rotationLerpFactor, rotation, targetRotation);
if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) {
rotating = false;
rotationLerpFactor = 0;
}
}
//linear interpolation of the rotation while rotating vertically
if (vRotating) {
vRotationLerpFactor = Math.min(vRotationLerpFactor + tpf * tpf * rotationSensitivity, 1);
vRotation = FastMath.interpolateLinear(vRotationLerpFactor, vRotation, targetVRotation);
if (targetVRotation + 0.01f >= vRotation && targetVRotation - 0.01f <= vRotation) {
vRotating = false;
vRotationLerpFactor = 0;
}
}
//computing the position
computePosition();
//setting the position at last
cam.setLocation(pos.addLocal(lookAtOffset));
} else {
//easy no smooth motion
vRotation = targetVRotation;
rotation = targetRotation;
distance = targetDistance;
computePosition();
cam.setLocation(pos.addLocal(lookAtOffset));
}
//keeping track on the previous position of the target
prevPos.set(targetLocation);
//the cam looks at the target
cam.lookAt(targetLocation, initialUpVec);
}
}
/**
* Return the enabled/disabled state of the camera
* @return true if the camera is enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enable or disable the camera
* @param enabled true to enable
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
if (!enabled) {
canRotate = false; // reset this flag in-case it was on before
}
}
/**
* Returns the max zoom distance of the camera (default is 40)
* @return maxDistance
*/
public float getMaxDistance() {
return maxDistance;
}
/**
* Sets the max zoom distance of the camera (default is 40)
* @param maxDistance
*/
public void setMaxDistance(float maxDistance) {
this.maxDistance = maxDistance;
if (maxDistance < distance) {
zoomCamera(maxDistance - distance);
}
}
/**
* Returns the min zoom distance of the camera (default is 1)
* @return minDistance
*/
public float getMinDistance() {
return minDistance;
}
/**
* Sets the min zoom distance of the camera (default is 1)
*/
public void setMinDistance(float minDistance) {
this.minDistance = minDistance;
if (minDistance > distance) {
zoomCamera(distance - minDistance);
}
}
/**
* clone this camera for a spatial
* @param spatial
* @return
*/
public Control cloneForSpatial(Spatial spatial) {
ChaseCamera cc = new ChaseCamera(cam, spatial, inputManager);
cc.setMaxDistance(getMaxDistance());
cc.setMinDistance(getMinDistance());
return cc;
}
/**
* Sets the spacial for the camera control, should only be used internally
* @param spatial
*/
public void setSpatial(Spatial spatial) {
target = spatial;
if (spatial == null) {
return;
}
computePosition();
prevPos = new Vector3f(target.getWorldTranslation());
cam.setLocation(pos);
}
/**
* update the camera control, should only be used internally
* @param tpf
*/
public void update(float tpf) {
updateCamera(tpf);
}
/**
* renders the camera control, should only be used internally
* @param rm
* @param vp
*/
public void render(RenderManager rm, ViewPort vp) {
//nothing to render
}
/**
* Write the camera
* @param ex the exporter
* @throws IOException
*/
public void write(JmeExporter ex) throws IOException {
OutputCapsule capsule = ex.getCapsule(this);
capsule.write(maxDistance, "maxDistance", 40);
capsule.write(minDistance, "minDistance", 1);
}
/**
* Read the camera
* @param im
* @throws IOException
*/
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
maxDistance = ic.readFloat("maxDistance", 40);
minDistance = ic.readFloat("minDistance", 1);
}
/**
* @return The maximal vertical rotation angle in radian of the camera around the target
*/
public float getMaxVerticalRotation() {
return maxVerticalRotation;
}
/**
* Sets the maximal vertical rotation angle in radian of the camera around the target. Default is Pi/2;
* @param maxVerticalRotation
*/
public void setMaxVerticalRotation(float maxVerticalRotation) {
this.maxVerticalRotation = maxVerticalRotation;
}
/**
*
* @return The minimal vertical rotation angle in radian of the camera around the target
*/
public float getMinVerticalRotation() {
return minVerticalRotation;
}
/**
* Sets the minimal vertical rotation angle in radian of the camera around the target default is 0;
* @param minHeight
*/
public void setMinVerticalRotation(float minHeight) {
this.minVerticalRotation = minHeight;
}
/**
* @return True is smooth motion is enabled for this chase camera
*/
public boolean isSmoothMotion() {
return smoothMotion;
}
/**
* Enables smooth motion for this chase camera
* @param smoothMotion
*/
public void setSmoothMotion(boolean smoothMotion) {
this.smoothMotion = smoothMotion;
}
/**
* returns the chasing sensitivity
* @return
*/
public float getChasingSensitivity() {
return chasingSensitivity;
}
/**
*
* Sets the chasing sensitivity, the lower the value the slower the camera will follow the target when it moves
* default is 5
* Only has an effect if smoothMotion is set to true and trailing is enabled
* @param chasingSensitivity
*/
public void setChasingSensitivity(float chasingSensitivity) {
this.chasingSensitivity = chasingSensitivity;
}
/**
* Returns the rotation sensitivity
* @return
*/
public float getRotationSensitivity() {
return rotationSensitivity;
}
/**
* Sets the rotation sensitivity, the lower the value the slower the camera will rotates around the target when draging with the mouse
* default is 5, values over 5 should have no effect.
* If you want a significant slow down try values below 1.
* Only has an effect if smoothMotion is set to true
* @param rotationSensitivity
*/
public void setRotationSensitivity(float rotationSensitivity) {
this.rotationSensitivity = rotationSensitivity;
}
/**
* returns true if the trailing is enabled
* @return
*/
public boolean isTrailingEnabled() {
return trailingEnabled;
}
/**
* Enable the camera trailing : The camera smoothly go in the targets trail when it moves.
* Only has an effect if smoothMotion is set to true
* @param trailingEnabled
*/
public void setTrailingEnabled(boolean trailingEnabled) {
this.trailingEnabled = trailingEnabled;
}
/**
*
* returns the trailing rotation inertia
* @return
*/
public float getTrailingRotationInertia() {
return trailingRotationInertia;
}
/**
* Sets the trailing rotation inertia : default is 0.1. This prevent the camera to roughtly stop when the target stops moving
* before the camera reached the trail position.
* Only has an effect if smoothMotion is set to true and trailing is enabled
* @param trailingRotationInertia
*/
public void setTrailingRotationInertia(float trailingRotationInertia) {
this.trailingRotationInertia = trailingRotationInertia;
}
/**
* returns the trailing sensitivity
* @return
*/
public float getTrailingSensitivity() {
return trailingSensitivity;
}
/**
* Only has an effect if smoothMotion is set to true and trailing is enabled
* Sets the trailing sensitivity, the lower the value, the slower the camera will go in the target trail when it moves.
* default is 0.5;
* @param trailingSensitivity
*/
public void setTrailingSensitivity(float trailingSensitivity) {
this.trailingSensitivity = trailingSensitivity;
}
/**
* returns the zoom sensitivity
* @return
*/
public float getZoomSensitivity() {
return zoomSensitivity;
}
/**
* Sets the zoom sensitivity, the lower the value, the slower the camera will zoom in and out.
* default is 5.
* @param zoomSensitivity
*/
public void setZoomSensitivity(float zoomSensitivity) {
this.zoomSensitivity = zoomSensitivity;
}
/**
* Returns the rotation speed when the mouse is moved.
*
* @return the rotation speed when the mouse is moved.
*/
public float getRotationSpeed() {
return rotationSpeed;
}
/**
* Sets the rotate amount when user moves his mouse, the lower the value,
* the slower the camera will rotate. default is 1.
*
* @param rotationSpeed Rotation speed on mouse movement, default is 1.
*/
public void setRotationSpeed(float rotationSpeed) {
this.rotationSpeed = rotationSpeed;
}
/**
* Sets the default distance at start of applicaiton
* @param defaultDistance
*/
public void setDefaultDistance(float defaultDistance) {
distance = defaultDistance;
targetDistance = distance;
}
/**
* sets the default horizontal rotation in radian of the camera at start of the application
* @param angleInRad
*/
public void setDefaultHorizontalRotation(float angleInRad) {
rotation = angleInRad;
targetRotation = angleInRad;
}
/**
* sets the default vertical rotation in radian of the camera at start of the application
* @param angleInRad
*/
public void setDefaultVerticalRotation(float angleInRad) {
vRotation = angleInRad;
targetVRotation = angleInRad;
}
/**
* @return If drag to rotate feature is enabled.
*
* @see FlyByCamera#setDragToRotate(boolean)
*/
public boolean isDragToRotate() {
return dragToRotate;
}
/**
* @param dragToRotate When true, the user must hold the mouse button
* and drag over the screen to rotate the camera, and the cursor is
* visible until dragged. Otherwise, the cursor is invisible at all times
* and holding the mouse button is not needed to rotate the camera.
* This feature is disabled by default.
*/
public void setDragToRotate(boolean dragToRotate) {
this.dragToRotate = dragToRotate;
this.canRotate = !dragToRotate;
inputManager.setCursorVisible(dragToRotate);
}
/**
* @param rotateOnlyWhenClose When this flag is set to false the chase
* camera will always rotate around its spatial independently of their
* distance to one another. If set to true, the chase camera will only
* be allowed to rotated below the "horizon" when the distance is smaller
* than minDistance + 1.0f (when fully zoomed-in).
*/
public void setDownRotateOnCloseViewOnly(boolean rotateOnlyWhenClose) {
veryCloseRotation = rotateOnlyWhenClose;
}
/**
* @return True if rotation below the vertical plane of the spatial tied
* to the camera is allowed only when zoomed in at minDistance + 1.0f.
* False if vertical rotation is always allowed.
*/
public boolean getDownRotateOnCloseViewOnly() {
return veryCloseRotation;
}
/**
* return the current distance from the camera to the target
* @return
*/
public float getDistanceToTarget() {
return distance;
}
/**
* returns the current horizontal rotation around the target in radians
* @return
*/
public float getHorizontalRotation() {
return rotation;
}
/**
* returns the current vertical rotation around the target in radians.
* @return
*/
public float getVerticalRotation() {
return vRotation;
}
/**
* returns the offset from the target's position where the camera looks at
* @return
*/
public Vector3f getLookAtOffset() {
return lookAtOffset;
}
/**
* Sets the offset from the target's position where the camera looks at
* @param lookAtOffset
*/
public void setLookAtOffset(Vector3f lookAtOffset) {
this.lookAtOffset = lookAtOffset;
}
/**
* Sets the up vector of the camera used for the lookAt on the target
* @param up
*/
public void setUpVector(Vector3f up) {
initialUpVec = up;
}
/**
* Returns the up vector of the camera used for the lookAt on the target
* @return
*/
public Vector3f getUpVector() {
return initialUpVec;
}
public boolean isHideCursorOnRotate() {
return hideCursorOnRotate;
}
public void setHideCursorOnRotate(boolean hideCursorOnRotate) {
this.hideCursorOnRotate = hideCursorOnRotate;
}
/**
* invert the vertical axis movement of the mouse
* @param invertYaxis
*/
public void setInvertVerticalAxis(boolean invertYaxis) {
this.invertYaxis = invertYaxis;
inputManager.deleteMapping(ChaseCamDown);
inputManager.deleteMapping(ChaseCamUp);
if (!invertYaxis) {
inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
} else {
inputManager.addMapping(ChaseCamDown, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addMapping(ChaseCamUp, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
}
inputManager.addListener(this, ChaseCamDown, ChaseCamUp);
}
/**
* invert the Horizontal axis movement of the mouse
* @param invertXaxis
*/
public void setInvertHorizontalAxis(boolean invertXaxis) {
this.invertXaxis = invertXaxis;
inputManager.deleteMapping(ChaseCamMoveLeft);
inputManager.deleteMapping(ChaseCamMoveRight);
if (!invertXaxis) {
inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, false));
} else {
inputManager.addMapping(ChaseCamMoveLeft, new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addMapping(ChaseCamMoveRight, new MouseAxisTrigger(MouseInput.AXIS_X, true));
}
inputManager.addListener(this, ChaseCamMoveLeft, ChaseCamMoveRight);
}
}
|
package org.jaudiotagger.audio.mp4.atom;
import org.jaudiotagger.audio.generic.Utils;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Logger;
/**
* Everything in MP4s are held in boxes (formally known as atoms), they are held as a hierachial tree within the MP4.
* <p/>
* We are most interested in boxes that are used to hold metadata, but we have to know about some other boxes
* as well in order to find them.
* <p/>
* All boxes consist of a 4 byte box length (big Endian), and then a 4 byte identifier, this is the header
* which is model in this class.
* <p/>
* The length includes the length of the box including the identifier and the length itself.
* Then they may contain data and/or sub boxes, if they contain subboxes they are known as a parent box. Parent boxes
* shouldn't really contain data, but sometimes they do.
* <p/>
* Parent boxes length includes the length of their immediate sub boxes
* <p/>
* This class is normally used by instantiating with the empty constructor, then use the update method
* to pass the header data which is used to read the identifier and the the size of the box
*/
public class Mp4BoxHeader
{
// Logger Object
public static Logger logger = Logger.getLogger("org.jaudiotagger.audio.mp4.atom");
public static final int OFFSET_POS = 0;
public static final int IDENTIFIER_POS = 4;
public static final int OFFSET_LENGTH = 4;
public static final int IDENTIFIER_LENGTH = 4;
public static final int HEADER_LENGTH = OFFSET_LENGTH + IDENTIFIER_LENGTH;
//Box identifier
private String id;
//Box length
private int length;
//Raw Header data
protected ByteBuffer dataBuffer;
//Mp4 uses UTF-8 for all text
public static final String CHARSET_UTF_8 = "UTF-8";
/**
* Construct empty header
*
* Can be populated later with update method
*/
public Mp4BoxHeader()
{
}
/**
* Construct header
*
* Create header using headerdata, expected to find header at headerdata current position
*
* Note after processing adjusts position to immediately after header
*
* @param headerData
*/
public Mp4BoxHeader(ByteBuffer headerData)
{
update(headerData);
}
/**
* Create header using headerdata, expected to find header at headerdata current position
*
* Note after processing adjusts position to immediately after header
*
* @param headerData
*/
public void update(ByteBuffer headerData)
{
//Read header data into byte array
byte[] b = new byte[HEADER_LENGTH];
headerData.get(b);
//Keep reference to copy of RawData
dataBuffer=ByteBuffer.wrap(b);
//Calculate box size
this.length = Utils.getNumberBigEndian(b, OFFSET_POS, OFFSET_LENGTH - 1);
//Calculate box id
this.id = Utils.getString(b, IDENTIFIER_POS, IDENTIFIER_LENGTH);
logger.finest("Read header:"+id+":length:"+length+":at:");
}
/**
*
* @return the box identifier
*/
public String getId()
{
return id;
}
/**
*
* @return the length of the boxes data (includes the header size)
*/
public int getLength()
{
return length;
}
/**
* Set the length.
*
* This will modify the databuffer accordingly
*
* @param length
*/
public void setLength(int length)
{
byte[] headerSize = Utils.getSizeBigEndian(length);
dataBuffer.put(0,headerSize[0]);
dataBuffer.put(1,headerSize[1]);
dataBuffer.put(2,headerSize[2]);
dataBuffer.put(3,headerSize[3]);
this.length =length;
}
/**
* @return the 8 byte header buffer
*/
public ByteBuffer getHeaderData()
{
dataBuffer.rewind();
return dataBuffer;
}
/**
*
* @return the length of the data only (does not include the header size)
*/
public int getDataLength()
{
return length - HEADER_LENGTH;
}
public String toString()
{
return "Box " + id + ":" + length;
}
/**
*
* @return UTF_8 (always used by Mp4)
*/
public String getEncoding()
{
return CHARSET_UTF_8;
}
/**
* Seek for box with the specified id starting from the current location of filepointer,
* <p/>
* Note it wont find the box if it is contained with a level below the current level, nor if we are
* at a parent atom that also contains data and we havent yet processed the data. It will work
* if we are at the start of a child box even if it not the required box as long as the box we are
* looking for is the same level (or the level above in some cases).
*
* @param raf
* @param id
* @throws java.io.IOException
*/
public static Mp4BoxHeader seekWithinLevel(RandomAccessFile raf, String id) throws IOException
{
logger.finer("Started searching for:"+id+" in file at:"+raf.getChannel().position());
Mp4BoxHeader boxHeader = new Mp4BoxHeader();
ByteBuffer headerBuffer = ByteBuffer.allocate(HEADER_LENGTH);
int bytesRead = raf.getChannel().read(headerBuffer);
if(bytesRead!=HEADER_LENGTH)
{
return null;
}
headerBuffer.rewind();
boxHeader.update(headerBuffer);
while (!boxHeader.getId().equals(id))
{
logger.finer("Still searching for:"+id+" in file at:"+raf.getChannel().position());
//Something gone wrong probably not at the start of an atom so return null;
if(boxHeader.getLength() < Mp4BoxHeader.HEADER_LENGTH)
{
return null;
}
int noOfBytesSkipped = raf.skipBytes(boxHeader.getDataLength());
logger.finer("Skipped:"+noOfBytesSkipped);
if(noOfBytesSkipped<boxHeader.getDataLength())
{
return null;
}
headerBuffer.rewind();
bytesRead = raf.getChannel().read(headerBuffer);
logger.finer("Header Bytes Read:"+bytesRead);
headerBuffer.rewind();
if(bytesRead==Mp4BoxHeader.HEADER_LENGTH)
{
boxHeader.update(headerBuffer);
}
else
{
return null;
}
}
return boxHeader;
}
/**
* Seek for box with the specified id starting from the current location of filepointer,
* <p/>
* Note it won't find the box if it is contained with a level below the current level, nor if we are
* at a parent atom that also contains data and we havent yet processed the data. It will work
* if we are at the start of a child box even if it not the required box as long as the box we are
* looking for is the same level (or the level above in some cases).
*
* @param data
* @param id
* @throws java.io.IOException
*/
public static Mp4BoxHeader seekWithinLevel(ByteBuffer data, String id) throws IOException
{
logger.finer("Started searching for:"+id+" in bytebuffer at"+data.position());
Mp4BoxHeader boxHeader = new Mp4BoxHeader();
if(data.remaining()>=Mp4BoxHeader.HEADER_LENGTH)
{
boxHeader.update(data);
}
else
{
return null;
}
while (!boxHeader.getId().equals(id))
{
logger.finer("Found"+boxHeader.getId()+"Still searching for:"+id+" in bytebuffer at"+data.position());
//Something gone wrong probably not at the start of an atom so return null;
if(boxHeader.getLength() < Mp4BoxHeader.HEADER_LENGTH)
{
return null;
}
data.position(data.position() + (boxHeader.getLength() - HEADER_LENGTH));
if(data.remaining()>=Mp4BoxHeader.HEADER_LENGTH)
{
boxHeader.update(data);
}
else
{
return null;
}
}
return boxHeader;
}
}
|
package org.languagetool.dev.diff;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.languagetool.tools.StringTools;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
/**
* Find diffs between runs of command-line LT. Matches with the same rule id, doc title, line, column
* and covered text are considered the "same" match. If there's a difference in message or
* suggestion of these same matches, then we consider this match to be "modified".
*/
public class RuleMatchDiffFinder {
private static final String MARKER_START = "<span class='marker'>";
private static final String MARKER_END = "</span>";
private static final int IFRAME_MAX = -1;
private boolean fullMode;
List<RuleMatchDiff> getDiffs(List<LightRuleMatch> l1, List<LightRuleMatch> l2) {
System.out.println("Comparing result 1 (" + l1.size() + " matches) to result 2 (" + l2.size() + " matches), step 1");
//debugList("List 1", l1);
//debugList("List 2", l2);
List<RuleMatchDiff> result = new ArrayList<>();
Map<MatchKey, LightRuleMatch> oldMatches = getMatchMap(l1);
for (LightRuleMatch match : l2) {
MatchKey key = new MatchKey(match.getLine(), match.getColumn(), match.getRuleId(), match.getTitle(), match.getCoveredText());
LightRuleMatch oldMatch = oldMatches.get(key);
if (oldMatch != null) {
if (!oldMatch.getSuggestions().equals(match.getSuggestions()) ||
!oldMatch.getMessage().equals(match.getMessage()) ||
oldMatch.getStatus() != match.getStatus() ||
//!Objects.equals(oldMatch.getSubId(), match.getSubId()) || -- sub id change = other sub-rule added or removed, this is usually not relevant
!oldMatch.getCoveredText().equals(match.getCoveredText())) {
result.add(RuleMatchDiff.modified(oldMatch, match));
}
} else {
result.add(RuleMatchDiff.added(match));
}
}
System.out.println("Comparing result 1 (" + l1.size() + " matches) to result 2 (" + l2.size() + " matches), step 2");
Map<String, List<RuleMatchDiff>> addedToMatch = getAddedMatchesMap(result);
Map<MatchKey, LightRuleMatch> newMatches = getMatchMap(l2);
for (LightRuleMatch match : l1) {
MatchKey key = new MatchKey(match.getLine(), match.getColumn(), match.getRuleId(), match.getTitle(), match.getCoveredText());
LightRuleMatch newMatch = newMatches.get(key);
if (newMatch == null) {
// removed
String lookupKey = cleanSpan(match.getContext()) + "_" + match.getTitle();
List<RuleMatchDiff> addedMatches = addedToMatch.get(lookupKey);
LightRuleMatch replacedBy = null;
if (addedMatches != null) {
for (RuleMatchDiff addedMatch : addedMatches) {
LightRuleMatch tmp = addedMatch.getNewMatch();
boolean overlaps = tmp.getColumn() < match.getColumn() + match.getCoveredText().length() &&
tmp.getColumn() + tmp.getCoveredText().length() > match.getColumn();
if (overlaps && !tmp.getFullRuleId().equals(match.getFullRuleId())) {
/*System.out.println(tmp + "\noverlaps\n" + match);
System.out.println("tmp " + tmp.getTitle());
System.out.println("match " + match.getTitle());
System.out.println(" " + tmp.getColumn() + " < " + match.getColumn() +" + "+ match.getCoveredText().length() + " &&");
System.out.println(" " + tmp.getColumn() + " + " + tmp.getCoveredText().length() +" > "+ match.getColumn());
System.out.println(" old covered: " + match.getCoveredText());
System.out.println(" new covered: " + tmp.getCoveredText());
System.out.println("");*/
replacedBy = addedMatch.getNewMatch();
addedMatch.setReplaces(match);
break;
}
}
}
result.add(RuleMatchDiff.removed(match, replacedBy));
}
}
return result;
}
@NotNull
private Map<String, List<RuleMatchDiff>> getAddedMatchesMap(List<RuleMatchDiff> result) {
Map<String, List<RuleMatchDiff>> addedToMatch = new HashMap<>();
for (RuleMatchDiff diff : result) {
if (diff.getStatus() == RuleMatchDiff.Status.ADDED) {
String key = cleanSpan(diff.getNewMatch().getContext()) + "_" + diff.getNewMatch().getTitle();
List<RuleMatchDiff> val = addedToMatch.get(key);
if (val == null) {
List<RuleMatchDiff> diffs = new ArrayList<>();
diffs.add(diff);
addedToMatch.put(key, diffs);
} else {
val.add(diff);
}
}
}
return addedToMatch;
}
private String cleanSpan(String s) {
return s.replaceFirst(MARKER_START, "").replaceFirst("</span>", "");
}
private void debugList(String title, List<LightRuleMatch> l1) {
System.out.println(title);
for (LightRuleMatch lightRuleMatch : l1) {
System.out.println(" *" + lightRuleMatch);
}
}
private Map<MatchKey, LightRuleMatch> getMatchMap(List<LightRuleMatch> list) {
Map<MatchKey, LightRuleMatch> map = new HashMap<>();
for (LightRuleMatch match : list) {
MatchKey key = new MatchKey(match.getLine(), match.getColumn(), match.getRuleId(), match.getTitle(), match.getCoveredText());
map.put(key, match);
//System.out.println("-> " + key);
}
return map;
}
private void printDiffs(List<RuleMatchDiff> diffs, FileWriter fw, String langCode, String date, String filename, String ruleId) throws IOException {
fw.write("Diffs found: " + diffs.size());
if (diffs.size() > 0) {
RuleMatchDiff diff1 = diffs.get(0);
if (diff1.getOldMatch() != null) {
fw.write(". Category: " + diff1.getOldMatch().getCategoryName());
} else if (diff1.getNewMatch() != null) {
fw.write(". Category: " + diff1.getNewMatch().getCategoryName());
}
}
if (fullMode) {
fw.write(". <a href='../" + langCode + "/" + filename + "'>Today's list</a>");
} else {
fw.write(". <a href='../" + langCode + "_full/" + filename + "'>Full list</a>");
}
String shortRuleId = ruleId.replaceFirst("^.* / ", "").replaceFirst("\\[[0-9]+\\]", "");
fw.write(". " + getAnalyticsLink(shortRuleId, langCode));
fw.write("<br>\n");
printTableBegin(fw);
int iframeCount = 0;
int i = 1;
for (RuleMatchDiff diff : diffs) {
if (diff.getStatus() == RuleMatchDiff.Status.ADDED) {
fw.write("<tr style='background-color: #c7ffd0'>\n");
} else if (diff.getStatus() == RuleMatchDiff.Status.REMOVED) {
fw.write("<tr style='background-color: #ffd2d8'>\n");
} else {
fw.write("<tr>\n");
}
fw.write(" <td>" + diff.getStatus().name().substring(0, 3) + "<br>#" + i + " </td>\n");
i++;
LightRuleMatch oldMatch = diff.getOldMatch();
LightRuleMatch newMatch = diff.getNewMatch();
if (diff.getOldMatch() != null) {
fw.write("<td>" + cleanSource(diff.getOldMatch().getRuleSource()) + "</td>");
} else if (diff.getNewMatch() != null) {
fw.write("<td>" + cleanSource(diff.getNewMatch().getRuleSource()) + "</td>");
} else {
fw.write("<td></td>");
}
if (oldMatch != null && newMatch != null) {
printRuleIdCol(fw, oldMatch, newMatch);
iframeCount += printMessage(fw, oldMatch, newMatch, diff.getReplaces(), diff.getReplacedBy(), langCode, date, diff.getStatus(), iframeCount);
printMarkerCol(fw, oldMatch, newMatch);
if (oldMatch.getSuggestions().equals(newMatch.getSuggestions())) {
fw.write("<td>");
fw.write(oldMatch.getSuggestions().stream().map(k -> showTrimSpace(k)).collect(Collectors.joining(", ")));
fw.write("</td>\n");
} else {
fw.write("<td>\n");
fw.write(" <tt>old: </tt>" + oldMatch.getSuggestions().stream().map(k -> showTrimSpace(k)).collect(Collectors.joining(", ")));
fw.write(" <br>");
fw.write(" <tt>new: </tt>" + newMatch.getSuggestions().stream().map(k -> showTrimSpace(k)).collect(Collectors.joining(", ")));
fw.write("</td>\n");
}
} else {
LightRuleMatch match = diff.getOldMatch() != null ? diff.getOldMatch() : diff.getNewMatch();
printRuleIdCol(fw, null, match);
iframeCount += printMessage(fw, match, null, diff.getReplaces(), diff.getReplacedBy(), langCode, date, diff.getStatus(), iframeCount);
printMarkerCol(fw, null, match);
fw.write(" <td>" + match.getSuggestions().stream().map(k -> showTrimSpace(k)).collect(Collectors.joining(", ")) + "</td>\n");
}
fw.write("</tr>\n");
}
printTableEnd(fw);
}
private String getAnalyticsLink(String ruleId, String langCode) {
String shortId = ruleId.replaceFirst("\\[[0-9]+\\]", "");
String shortLangCode = langCode.replaceFirst("-.*", "");
return "[<a href='https://internal1.languagetool.org/grafana/d/BY_CNDHGz/rule-events-analysis?orgId=1&var-rule_id=" +
shortId + "&from=now-30d&var-language=" + shortLangCode + "' target='grafana' title='Grafana'>g</a>/" +
"<a href='https://analytics.languagetoolplus.com/matomo/index.php?module=Widgetize&action=iframe&secondaryDimension=eventName&moduleToWidgetize=Events&actionToWidgetize=getAction&idSite=18&period=day&date=yesterday&flat=1&filter_column=label&show_dimensions=1&filter_pattern=" +
shortId + "' target='disables' title='disables in Matomo'>m</a>]";
}
private String cleanSource(String ruleSource) {
if (ruleSource == null) {
return "java";
}
return ruleSource.replaceFirst("^.*/grammar", "gram.").replaceFirst("gram.-premium", "prem").replaceFirst(".xml", "");
}
private void printRuleIdCol(FileWriter fw, LightRuleMatch oldMatch, LightRuleMatch newMatch) throws IOException {
fw.write(" <td class='small'>");
if (oldMatch != null && !Objects.equals(oldMatch.getSubId(), newMatch.getSubId())) {
fw.write(oldMatch.getRuleId());
fw.write("[" + oldMatch.getSubId() + " => " + newMatch.getSubId() + "]");
} else {
fw.write(newMatch.getRuleId() + "[" + (newMatch.getSubId() != null ? newMatch.getSubId() : "") + "]");
}
if (newMatch.getStatus() != LightRuleMatch.Status.on) {
fw.write(" <br><span class='status'>[" + newMatch.getStatus() + "]</span>");
}
if (oldMatch != null && newMatch.getStatus() != oldMatch.getStatus()) {
fw.write(" <br><span class='status'>[" + oldMatch.getStatus() + " => " + newMatch.getStatus() + "]</span>");
}
if (newMatch.getTags().size() > 0) {
fw.write(" <br><span class='status'>" + newMatch.getTags() + "</span>");
}
if (oldMatch != null && !newMatch.getTags().equals(oldMatch.getTags())) {
fw.write(" <br><span class='status'>" + oldMatch.getTags() + " => " + newMatch.getTags() + "</span>");
}
fw.write(" </td>\n");
}
private void printMarkerCol(FileWriter fw, LightRuleMatch oldMatch, LightRuleMatch newMatch) throws IOException {
fw.write(" <td>");
String markedText = newMatch == null ? oldMatch.getCoveredText() : newMatch.getCoveredText();
fw.write(markedText);
fw.write(" </td>\n");
}
private int printMessage(FileWriter fw, LightRuleMatch oldMatch, LightRuleMatch newMatch,
LightRuleMatch replaces, LightRuleMatch replacedBy, String langCode, String date,
RuleMatchDiff.Status status, int iframeCount) throws IOException {
fw.write(" <td>");
String message;
boolean canOverlap;
if (newMatch == null) {
fw.write(oldMatch.getMessage());
message = oldMatch.getMessage();
canOverlap = canOverlap(oldMatch);
} else if (oldMatch.getMessage().equals(newMatch.getMessage())) {
fw.write(oldMatch.getMessage());
message = oldMatch.getMessage();
canOverlap = canOverlap(oldMatch);
} else {
//System.out.println("old: " + oldMatch.getMessage());
//System.out.println("new: " + newMatch.getMessage());
fw.write(
"<tt>old:</tt> " + showTrimSpace(oldMatch.getMessage()) + "<br>\n" +
"<tt>new:</tt> " + showTrimSpace(newMatch.getMessage()));
message = newMatch.getMessage();
canOverlap = canOverlap(newMatch);
}
fw.write(" <br><span class='sentence'>" + showTrimSpace(escapeSentence(oldMatch.getContext())) + "</span>");
boolean withIframe = false;
if (status == RuleMatchDiff.Status.ADDED || status == RuleMatchDiff.Status.MODIFIED) {
int markerFrom = oldMatch.getContext().indexOf(MARKER_START);
int markerTo = oldMatch.getContext().replace(MARKER_START, "").indexOf(MARKER_END);
String params = "sentence=" + enc(oldMatch.getContext().replace(MARKER_START, "").replace(MARKER_END, ""), 300) +
"&rule_id=" + enc(oldMatch.getFullRuleId()) +
"&filename=" + enc(cleanSource(oldMatch.getRuleSource())) +
"&message=" + enc(message, 300) +
"&suggestions=" + enc(String.join(", ", oldMatch.getSuggestions()), 300) +
"&marker_from=" + markerFrom +
"&marker_to=" + markerTo +
"&language=" + enc(langCode) +
"&day=" + enc(date);
if (iframeCount > IFRAME_MAX) {
// rendering 2000 iframes into a page isn't fun...
fw.write(" <a target='regression_feedback' href=\"https://languagetoolplus.com/regression/button?" + params + "\">FA?</a>\n\n");
} else {
fw.write(" <iframe scrolling=\"no\" style=\"border: none; width: 165px; height: 30px\"\n" +
"src=\"https://languagetoolplus.com/regression/button?" +
params + "\"></iframe>\n\n");
withIframe = true;
}
}
if (replaces != null) {
if (canOverlap) {
// can be ignored, sentence length rule can overlap other matches
} else {
fw.write("<br><br><i>Maybe replaces old match:</i><br>");
fw.write(replaces.getMessage());
fw.write(" <br><span class='sentence'>" + escapeSentence(replaces.getContext()) + "</span>");
fw.write(" <br><span class='suggestions'>Suggestions: " + replaces.getSuggestions() + "</span>");
fw.write(" <br><span class='id'>" + replaces.getFullRuleId() + "</span>");
}
}
if (replacedBy != null) {
if (canOverlap(replacedBy)) {
// can be ignored, sentence length rule can overlap other matches
} else {
fw.write("<br><br><i>Maybe replaced by new match:</i><br>");
fw.write(replacedBy.getMessage());
fw.write(" <br><span class='sentence'>" + escapeSentence(replacedBy.getContext()) + "</span>");
fw.write(" <br><span class='suggestions'>Suggestions: " + replacedBy.getSuggestions() + "</span>");
fw.write(" <br><span class='id'>" + replacedBy.getFullRuleId() + "</span>\n");
}
}
fw.write(" </td>\n");
return withIframe ? 1 : 0;
}
private boolean canOverlap(LightRuleMatch match) {
return match.getRuleId().equals("TOO_LONG_SENTENCE") || match.getRuleId().equals("TOO_LONG_SENTENCE_DE");
}
private String escapeSentence(String s) {
return StringTools.escapeHTML(s).
replace("<span class='marker'>", "<span class='marker'>").
replace("</span>", "</span>");
}
private String enc(String s) {
return enc(s, Integer.MAX_VALUE);
}
private String enc(String s, int maxLen) {
try {
return URLEncoder.encode(StringUtils.abbreviate(s, maxLen), "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String showTrimSpace(String s) {
s = s.replaceAll("\n", "<span class='whitespace'>\\\\n</span>");
s = s.replaceFirst("^\\s", "<span class='whitespace'> </span>");
s = s.replaceFirst("\\s$", "<span class='whitespace'> </span>");
s = s.replaceAll("\u00A0", "<span class='nbsp' title='non-breaking space'> </span>");
return s;
}
private void printTableBegin(FileWriter fw) throws IOException {
fw.write("<table class='sortable_table'>\n");
fw.write("<thead>\n");
fw.write("<tr>\n");
fw.write(" <th style='width:60px'>Change</th>\n");
fw.write(" <th>File</th>\n");
fw.write(" <th class='small'>Rule ID</th>\n");
fw.write(" <th>Message and Text</th>\n");
fw.write(" <th>Marked</th>\n");
fw.write(" <th>Suggestions</th>\n");
fw.write("</tr>\n");
fw.write("</thead>\n");
fw.write("<tbody>\n");
}
private void printTableEnd(FileWriter fw) throws IOException {
fw.write("</tbody>\n");
fw.write("</table>\n\n");
}
private void run(LightRuleMatchParser parser, File file1, File file2, File outputDir, String langCode, String date) throws IOException {
if (file1.getName().equals("empty.json")) {
fullMode = true;
}
LightRuleMatchParser.JsonParseResult jsonParseResult1 = parser.parseOutput(file1);
List<LightRuleMatch> l1 = jsonParseResult1.result;
LightRuleMatchParser.JsonParseResult jsonParseResult2 = parser.parseOutput(file2);
List<LightRuleMatch> l2 = jsonParseResult2.result;
String title = "Comparing " + file1.getName() + " to " + file2.getName();
System.out.println(title);
List<RuleMatchDiff> diffs = getDiffs(l1, l2);
diffs.sort((k, j) -> {
int idDiff = getFullId(k).compareTo(getFullId(j));
if (idDiff == 0) {
int diff2 = k.getStatus().compareTo(j.getStatus());
if (diff2 == 0) {
return k.getMarkedText().compareTo(j.getMarkedText());
} else {
return diff2;
}
}
return idDiff;
}
);
System.out.println("Total diffs found: " + diffs.size());
Map<String, List<RuleMatchDiff>> keyToDiffs = groupDiffs(diffs);
List<OutputFile> outputFiles = new ArrayList<>();
for (Map.Entry<String, List<RuleMatchDiff>> entry : keyToDiffs.entrySet()) {
String filename = "result_" + entry.getKey().replaceAll("/", "_").replaceAll("[\\s_]+", "_") + ".html";
File outputFile = new File(outputDir, filename);
if (entry.getValue().size() > 0) {
outputFiles.add(new OutputFile(outputFile, entry.getValue()));
}
try (FileWriter fw = new FileWriter(outputFile)) {
System.out.println("Writing result to " + outputFile);
printHeader(title, fw);
printDiffs(entry.getValue(), fw, langCode, date, filename, entry.getKey());
printFooter(fw);
}
}
try (FileWriter fw = new FileWriter(new File(outputDir, "index.html"))) {
printHeader("Overview of regression results", fw);
fw.write("<table class='sortable_table'>\n");
fw.write("<thead>");
fw.write("<tr>");
fw.write(" <td>Total</td>");
fw.write(" <td>ADD</td>");
fw.write(" <td>REM</td>");
fw.write(" <td>MOD</td>");
fw.write(" <td>Source</td>");
fw.write(" <td title='Picky'>P</td>");
fw.write(" <td title='temp_off'>T</td>");
fw.write(" <td>ID</td>");
fw.write(" <td>Message of first match</td>");
fw.write("</tr>");
fw.write("</thead>");
fw.write("<tbody>\n");
for (OutputFile outputFile : outputFiles) {
String file = outputFile.file.getName();
fw.write("<tr>");
fw.write("<td>" + outputFile.items.size() + "</td>");
long added = outputFile.items.stream().filter(k -> k.getStatus() == RuleMatchDiff.Status.ADDED).count();
fw.write("<td " + (added > 0 ? "style='background-color: #c7ffd0'" : "") + ">" + added + "</td>");
long removed = outputFile.items.stream().filter(k -> k.getStatus() == RuleMatchDiff.Status.REMOVED).count();
fw.write("<td " + (removed > 0 ? "style='background-color: #ffd2d8'" : "") + ">" + removed + "</td>");
fw.write("<td>" + outputFile.items.stream().filter(k -> k.getStatus() == RuleMatchDiff.Status.MODIFIED).count() + "</td>");
fw.write("<td>");
fw.write(file.replaceFirst("result_", "").replaceFirst("_.*", ""));
fw.write("</td>");
if (outputFile.items.size() > 0 && outputFile.items.get(0).getNewMatch() != null) {
fw.write("<td>" + (outputFile.items.get(0).getNewMatch().getTags().contains("picky") ? "p" : "") + "</td>");
} else if (outputFile.items.size() > 0 && outputFile.items.get(0).getOldMatch() != null) {
fw.write("<td>" + (outputFile.items.get(0).getOldMatch().getTags().contains("picky") ? "p" : "") + "</td>");
} else {
fw.write("<td></td>");
}
if (outputFile.items.size() > 0 && outputFile.items.get(0).getNewMatch() != null) {
fw.write("<td>" + (outputFile.items.get(0).getNewMatch().getStatus() == LightRuleMatch.Status.temp_off ? "t" : "") + "</td>");
} else if (outputFile.items.size() > 0 && outputFile.items.get(0).getOldMatch() != null) {
fw.write("<td>" + (outputFile.items.get(0).getOldMatch().getStatus() == LightRuleMatch.Status.temp_off ? "t" : "") + "</td>");
} else {
fw.write("<td></td>");
}
fw.write("<td>");
String id = file.replaceFirst("result_.*?_", "").replace(".html", "");
fw.write(" <a href='" + file + "'>" + id + "</a>");
fw.write(" " + getAnalyticsLink(id, langCode));
fw.write("</td>");
if (outputFile.items.size() > 0 && outputFile.items.get(0).getNewMatch() != null) {
fw.write("<td class='msg'>" + escapeSentence(outputFile.items.get(0).getNewMatch().getMessage()) + "</td>");
} else if (outputFile.items.size() > 0 && outputFile.items.get(0).getOldMatch() != null) {
fw.write("<td class='msg'>" + escapeSentence(outputFile.items.get(0).getOldMatch().getMessage()) + "</td>");
} else {
fw.write("<td></td>");
}
fw.write("</tr>\n");
}
fw.write("</tbody>");
fw.write("</table>\n\n");
fw.write("<br><table class='meta'>\n");
fw.write(" <tr><td>Old API:</td> <td>" + jsonParseResult1.buildDates + "</td></tr>\n");
fw.write(" <tr><td>New API:</td> <td>" + jsonParseResult2.buildDates + "</td></tr>\n");
fw.write("</table>\n");
printFooterForIndex(fw);
}
}
static class OutputFile {
File file;
List<RuleMatchDiff> items;
OutputFile(File file, List<RuleMatchDiff> items) {
this.file = file;
this.items = items;
}
}
private Map<String, List<RuleMatchDiff>> groupDiffs(List<RuleMatchDiff> diffs) {
Map<String, List<RuleMatchDiff>> keyToDiffs = new TreeMap<>();
String key;
String prevKey = "";
List<RuleMatchDiff> l = new ArrayList<>();
for (RuleMatchDiff diff : diffs) {
if (diff.getOldMatch() != null) {
key = cleanSource(diff.getOldMatch().getRuleSource()) + " / " + diff.getOldMatch().getFullRuleId();
} else {
key = cleanSource(diff.getNewMatch().getRuleSource()) + " / " + diff.getNewMatch().getFullRuleId();
}
if (!key.equals(prevKey) && l.size() > 0) {
keyToDiffs.put(prevKey, l);
l = new ArrayList<>();
}
l.add(diff);
prevKey = key;
}
if (l.size() > 0) {
keyToDiffs.put(prevKey, l);
}
return keyToDiffs;
}
private void printHeader(String title, FileWriter fw) throws IOException {
fw.write("<!doctype html>\n");
fw.write("<html>\n");
fw.write("<head>\n");
fw.write(" <title>" + title + "</title>\n");
fw.write(" <meta charset='utf-8'>\n");
fw.write(" <script src='https:
fw.write(" <style>\n");
fw.write(" td { vertical-align: top; }\n");
fw.write(" .small { font-size: small }\n");
fw.write(" .sentence { color: #666; }\n");
fw.write(" .marker { text-decoration: underline; background-color: rgba(200, 200, 200, 0.4) }\n");
fw.write(" .source { color: #999; }\n");
fw.write(" .status { color: #999; }\n");
fw.write(" .whitespace { background-color: rgba(200, 200, 200, 0.3) }\n");
fw.write(" .nbsp { background-color: rgba(200, 200, 200, 0.3) }\n");
fw.write(" .id { color: #666; }\n");
fw.write(" .msg { color: #666; }\n");
fw.write(" .meta { color: #666; }\n");
fw.write(" </style>\n");
fw.write("</head>\n");
fw.write("<body>\n\n");
}
private void printFooter(FileWriter fw) throws IOException {
fw.write("<script>\n" +
"var tf = new TableFilter(document.querySelector('.sortable_table'), {\n" +
" base_path: 'https://unpkg.com/tablefilter@0.7.0/dist/tablefilter/',\n" +
" col_1: 'select',\n" +
" auto_filter: { delay: 100 },\n" +
" grid_layout: false,\n" +
" col_types: ['string', 'string', 'string'],\n" +
" extensions: [{ name: 'sort' }]\n" +
"});\n" +
"tf.init();\n" +
"</script>");
fw.write("</body>\n");
fw.write("</html>\n");
}
private void printFooterForIndex(FileWriter fw) throws IOException {
fw.write("<script>\n" +
"var tf = new TableFilter(document.querySelector('.sortable_table'), {\n" +
" base_path: 'https://unpkg.com/tablefilter@0.7.0/dist/tablefilter/',\n" +
" auto_filter: { delay: 100 },\n" +
" col_0: 'none',\n" +
" col_1: 'none',\n" +
" col_2: 'none',\n" +
" col_3: 'none',\n" +
" col_4: 'select',\n" +
" col_5: 'select',\n" +
" col_6: 'select',\n" +
" grid_layout: false,\n" +
" col_types: ['number', 'number', 'number', 'number', 'string', 'string'],\n" +
" extensions: [{ name: 'sort' }]\n" +
"});\n" +
"tf.init();\n" +
"</script>");
fw.write("</body>\n");
fw.write("</html>\n");
}
private String getFullId(RuleMatchDiff diff) {
String id = "unknown";
if (diff.getOldMatch() != null) {
id = diff.getOldMatch().getFullRuleId();
} else if (diff.getNewMatch() != null) {
id = diff.getNewMatch().getFullRuleId();
}
return id;
}
private static void printUsageAndExit() {
System.out.println("Usage: " + RuleMatchDiffFinder.class.getSimpleName() + " <matches1> <matches2> <resultDir> <date>");
System.out.println(" <matches1> and <matches2> are text outputs of different versions of org.languagetool.dev.dumpcheck.SentenceSourceChecker run on the same input");
System.out.println(" or JSON outputs from org.languagetool.dev.httpchecker.HttpApiSentenceChecker");
System.exit(1);
}
public static void main(String[] args) throws IOException {
RuleMatchDiffFinder diffFinder = new RuleMatchDiffFinder();
LightRuleMatchParser parser = new LightRuleMatchParser();
if (args.length == 0) {
printUsageAndExit();
}
if (args[0].contains("XX") && args[1].contains("XX") && args[2].contains("XX")) {
if (args.length != 4) {
printUsageAndExit();
}
System.out.println("Running in multi-file mode, replacing 'XX' in filenames with lang codes...");
String file1 = args[0];
String file3 = args[2];
String date = args[3];
File dir = new File(file1).getParentFile();
String templateName = new File(file1).getName();
int varPos = templateName.indexOf("XX");
for (String file : dir.list()) {
if (file.length() >= varPos + 1) {
StringBuilder tempName = new StringBuilder(file).replace(varPos, varPos + 2, "XX");
if (tempName.toString().equals(templateName)) {
String langCode = file.substring(varPos, varPos + 2);
String tempNameNew = file.replace(".old", ".new");
File newFile = new File(dir, tempNameNew);
if (!newFile.exists()) {
throw new RuntimeException(tempNameNew + " not found - make sure files are names *.old and *.new in multi-file mode");
}
System.out.println("==== " + file + " =================================");
File oldFile = new File(dir, file);
String outputDir = file3.replace("XX", langCode);
diffFinder.run(parser, oldFile, newFile, new File(outputDir), langCode, date);
}
}
}
} else {
if (args.length != 5) {
System.out.println("Usage: " + RuleMatchDiffFinder.class.getSimpleName() + " <matches1> <matches2> <resultDir> <langCode> <date>");
System.out.println(" <matches1> and <matches2> are text outputs of different versions of org.languagetool.dev.dumpcheck.SentenceSourceChecker run on the same input");
System.out.println(" or JSON outputs from org.languagetool.dev.httpchecker.HttpApiSentenceChecker");
System.exit(1);
}
File file1 = new File(args[0]);
File file2 = new File(args[1]);
File outputDir = new File(args[2]);
String langCode = args[3];
String date = args[4];
if (outputDir.exists() && outputDir.isFile()) {
throw new IOException("<resultDir> already exists, but is a file: " + outputDir);
}
if (!outputDir.exists()) {
boolean mkdir = outputDir.mkdir();
if (!mkdir) {
throw new IOException("Could not create directory " + outputDir);
}
}
diffFinder.run(parser, file1, file2, outputDir, langCode, date);
}
}
}
|
package com.valkryst.VTerminal.font;
import lombok.NonNull;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class FontLoader {
// Prevent users from creating an instance.
private FontLoader() {}
public static Font loadFont(final @NonNull String spriteSheetPath, final @NonNull String characterDataPath, final double scale) throws IOException {
if (spriteSheetPath.isEmpty()) {
throw new IllegalArgumentException("The sprite sheet path cannot be empty.");
}
if (characterDataPath.isEmpty()) {
throw new IllegalArgumentException("The character data path cannot be empty.");
}
return loadFont(new FileInputStream(spriteSheetPath), new FileInputStream(characterDataPath), scale);
}
public static Font loadFontFromJar(final @NonNull String spriteSheetPath, final @NonNull String characterDataPath, final double scale) throws IOException {
if (spriteSheetPath.isEmpty()) {
throw new IllegalArgumentException("The sprite sheet path cannot be empty.");
}
if (characterDataPath.isEmpty()) {
throw new IllegalArgumentException("The character data path cannot be empty.");
}
final ClassLoader classLoader = FontLoader.class.getClassLoader();
final InputStream spriteSheetStream = classLoader.getResourceAsStream(spriteSheetPath);
final InputStream characterDataStream = classLoader.getResourceAsStream(characterDataPath);
return loadFont(spriteSheetStream, characterDataStream, scale);
}
/**
* Loads a font from the file system.
*
* @param spriteSheet
* The input stream to the sprite sheet.
*
* @param characterData
* The input stream to the character data.
*
* @param scale
* The amount to scale the font by.
*
* @return
* The font.
*
* @throws NullPointerException
* If the sprite sheet or character data streams are null.
*
* @throws IOException
* If an IOException occurs while loading the font.
*/
public static Font loadFont(final @NonNull InputStream spriteSheet, final @NonNull InputStream characterData, double scale) throws IOException {
if (scale <= 0) {
scale = 1;
}
final BufferedImage image = loadSpriteSheet(spriteSheet);
final List<String> data = loadCharacterData(characterData);
return new Font(processFontData(image, data), scale);
}
/**
* Processes a font sprite sheet and character data into a usable HashMap of character images.
*
* @param spriteSheet
* The sprite sheet.
*
* @param characterData
* The character data.
*
* @return
* The HashMap of character sprites.
*
* @throws NullPointerException
* If the sprite sheet or character data is null.
*/
private static HashMap<Integer, FontCharacter> processFontData(final @NonNull BufferedImage spriteSheet, final @NonNull List<String> characterData) {
final HashMap<Integer, FontCharacter> hashMap = new HashMap<>(characterData.size());
for (final String string : characterData) {
if (string.isEmpty() == false) {
final Scanner scanner = new Scanner(string);
final int character = scanner.nextInt();
final int x = scanner.nextInt();
final int y = scanner.nextInt();
final int width = scanner.nextByte();
final int height = scanner.nextByte();
final BufferedImage image = spriteSheet.getSubimage(x, y, width, height);
hashMap.put(character, new FontCharacter(character, image));
}
}
return hashMap;
}
/**
* Loads sprite sheet from an input stream.
*
* @param inputStream
* The input stream.
*
* @return
* The sprite sheet.
*
* @throws NullPointerException
* If the input stream is null.
*
* @throws IOException
* If an IOException occurs while loading the sprite sheet.
*/
private static BufferedImage loadSpriteSheet(final @NonNull InputStream inputStream) throws IOException {
final BufferedImage loadedImage = ImageIO.read(inputStream);
inputStream.close();
try {
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage convertedImage = gc.createCompatibleImage(loadedImage.getWidth(), loadedImage.getHeight(), loadedImage.getTransparency());
final Graphics2D g2d = convertedImage.createGraphics();
g2d.drawImage(loadedImage, 0, 0, null);
g2d.dispose();
return convertedImage;
} catch(final HeadlessException e) {
// Occurs when running FontLoader unit tests on Travis CI.
// Probably because there's no screen/graphics device.
return loadedImage;
}
}
/**
* Loads character data from a path.
*
* @param inputStream
* The input stream.
*
* @return
* The character data.
*
* @throws NullPointerException
* If the input stream is null.
*
* @throws IOException
* If an IOException occurs while loading the character data.
*/
private static List<String> loadCharacterData(final @NonNull InputStream inputStream) throws IOException {
// Load lines
final InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
final BufferedReader br = new BufferedReader(isr);
final List<String> lines = br.lines().collect(Collectors.toList());
// Remove Kerning Data
final Pattern kerningPattern = Pattern.compile("kerning.*\\n");
lines.replaceAll(string -> kerningPattern.matcher(string).replaceAll(""));
lines.removeIf(String::isEmpty);
// Remove Unnecessary Data
final Pattern miscPattern = Pattern.compile("info.*|common.*|page.*|chars.*|char id=\\d\\d\\d\\d\\d\\d.*|char id=[7-9]\\d\\d\\d\\d.*|char id=6[6-9]\\d\\d\\d.*|char id=65[6-9]\\d\\d.*|char id=655[4-9]\\d.*|char id=6553[6-9].*| xoff.*|char id=|x=|y=|width=|height=");
lines.replaceAll(string -> miscPattern.matcher(string).replaceAll(""));
lines.removeIf(String::isEmpty);
inputStream.close();
return lines;
}
}
|
package org.jaudiotagger.tag.mp4.field;
import org.jaudiotagger.audio.mp4.atom.Mp4BoxHeader;
import org.jaudiotagger.tag.FieldDataInvalidException;
import org.jaudiotagger.tag.mp4.Mp4FieldKey;
import org.jaudiotagger.tag.mp4.atom.Mp4DataBox;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
/**
* Represents the Track No field
* <p/>
* <p>There are a number of reserved fields making matters more complicated
* Reserved:2 bytes
* Track Number:2 bytes
* No of Tracks:2 bytes (or zero if not known)
* PlayListTitleReserved: 1 byte
* playtitlenameReserved:0 bytes
* </p>
*/
public class Mp4TrackField extends Mp4TagTextNumberField
{
private static final int NONE_VALUE_INDEX = 0;
private static final int TRACK_NO_INDEX = 1;
private static final int TRACK_TOTAL_INDEX = 2;
private static final int NONE_END_VALUE_INDEX = 3;
/**
* Create new Track Field parsing the String for the trackno/total
*
* @param trackValue
* @throws org.jaudiotagger.tag.FieldDataInvalidException
*/
public Mp4TrackField(String trackValue) throws FieldDataInvalidException
{
super(Mp4FieldKey.TRACK.getFieldName(), trackValue);
numbers = new ArrayList<Short>();
numbers.add(new Short("0"));
String values[] = trackValue.split("/");
switch (values.length)
{
case 1:
try
{
numbers.add(Short.parseShort(values[0]));
}
catch (NumberFormatException nfe)
{
throw new FieldDataInvalidException("Value of:" + values[0] + " is invalid for field:" + id);
}
numbers.add(new Short("0"));
numbers.add(new Short("0"));
break;
case 2:
try
{
numbers.add(Short.parseShort(values[0]));
}
catch (NumberFormatException nfe)
{
throw new FieldDataInvalidException("Value of:" + values[0] + " is invalid for field:" + id);
}
try
{
numbers.add(Short.parseShort(values[1]));
}
catch (NumberFormatException nfe)
{
throw new FieldDataInvalidException("Value of:" + values[1] + " is invalid for field:" + id);
}
numbers.add(new Short("0"));
break;
default:
throw new FieldDataInvalidException("Value is invalid for field:" + id);
}
}
/**
* Create new Track Field with only track No
*
* @param trackNo
*/
public Mp4TrackField(int trackNo)
{
super(Mp4FieldKey.TRACK.getFieldName(), String.valueOf(trackNo));
numbers = new ArrayList<Short>();
numbers.add(new Short("0"));
numbers.add((short) trackNo);
numbers.add(new Short("0"));
numbers.add(new Short("0"));
}
/**
* Create new Track Field with track No and total tracks
*
* @param trackNo
* @param total
*/
public Mp4TrackField(int trackNo, int total)
{
super(Mp4FieldKey.TRACK.getFieldName(), String.valueOf(trackNo));
numbers = new ArrayList<Short>();
numbers.add(new Short("0"));
numbers.add((short) trackNo);
numbers.add((short) total);
numbers.add(new Short("0"));
}
/**
* Construct from filedata
*
* @param id
* @param data
* @throws UnsupportedEncodingException
*/
public Mp4TrackField(String id, ByteBuffer data) throws UnsupportedEncodingException
{
super(id, data);
}
protected void build(ByteBuffer data) throws UnsupportedEncodingException
{
//Data actually contains a 'Data' Box so process data using this
Mp4BoxHeader header = new Mp4BoxHeader(data);
Mp4DataBox databox = new Mp4DataBox(header, data);
dataSize = header.getDataLength();
numbers = databox.getNumbers();
//Track number always hold three values, we can discard the first one, the second one is the track no
//and the third is the total no of tracks so only use if not zero
StringBuffer sb = new StringBuffer();
if(numbers!=null)
{
if ((numbers.size() > TRACK_NO_INDEX) && (numbers.get(TRACK_NO_INDEX) > 0))
{
sb.append(numbers.get(TRACK_NO_INDEX));
}
if ((numbers.size() > TRACK_TOTAL_INDEX) && (numbers.get(TRACK_TOTAL_INDEX) > 0))
{
sb.append("/").append(numbers.get(TRACK_TOTAL_INDEX));
}
}
content = sb.toString();
}
/**
* @return
*/
public Short getTrackNo()
{
return numbers.get(TRACK_NO_INDEX);
}
/**
* @return
*/
public Short getTrackTotal()
{
return numbers.get(TRACK_TOTAL_INDEX);
}
/**
* Set Track No
*
* @param trackNo
*/
public void setTrackNo(int trackNo)
{
numbers.set(TRACK_NO_INDEX, (short) trackNo);
}
/**
* Set total number of tracks
*
* @param trackTotal
*/
public void setTrackTotal(int trackTotal)
{
numbers.set(TRACK_TOTAL_INDEX, (short) trackTotal);
}
}
|
package org.latte.scripting.hostobjects;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.mortbay.jetty.Request;
import org.mozilla.javascript.ScriptableObject;
public class RequestProxy extends ScriptableObject {
private class Params extends ScriptableObject {
protected Params(HttpServletRequest request) {
if(request.getParameterMap().size() > 0) {
for(String key : (Set<String>)request.getParameterMap().keySet()) {
Object value = request.getParameterMap().get(key);
if(request.getContentType().startsWith("multipart/form-data")) {
if(value instanceof String) {
File tmp = (File)request.getAttribute(key);
File file = new File(tmp.getAbsoluteFile() + ((String)value).substring(((String)value).indexOf(".")));
tmp.renameTo(file);
ScriptableObject.putProperty(this, key, file.getAbsolutePath());
}
else {
ScriptableObject.putProperty(this, key, new String((byte[])value));
}
}
else {
ScriptableObject.putProperty(this, key, ((String[])value)[0]);
}
}
}
}
@Override
public String getClassName() {
return "Params";
}
}
public RequestProxy(HttpServletRequest request) throws IOException {
ScriptableObject.putProperty(this, "hostname", InetAddress.getByName(request.getRemoteAddr()).getHostName());
ScriptableObject.putProperty(this, "url", request.getRequestURI());
ScriptableObject.putProperty(this, "params", new Params(request));
String authorization = (String)request.getHeader("Authorization");
if(authorization != null && authorization.startsWith("Basic")) ScriptableObject.putProperty(this, "authorization", new String(new Base64().decode(authorization.split(" ")[1].getBytes())));
if("application/json".equals(request.getContentType())) {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
ScriptableObject.putProperty(this, "content", sb.toString());
}
}
@Override
public String getClassName() {
return "Request";
}
}
|
package com.wrapp.android.webimage;
import android.graphics.drawable.Drawable;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class ImageLoader {
private static final int NUM_WORKERS = 2;
private static ImageLoader staticInstance;
private final Queue<ImageRequest> pendingRequests;
private static class Worker extends Thread {
@Override
public void run() {
final Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
ImageRequest request;
while(true) {
synchronized(requestQueue) {
while(requestQueue.isEmpty()) {
try {
requestQueue.wait();
}
catch(InterruptedException e) {
// Log, but otherwise ignore. Not a big deal.
LogWrapper.logException(e);
}
}
request = getNextRequest(requestQueue);
}
processRequest(request);
}
}
private ImageRequest getNextRequest(Queue<ImageRequest> requestQueue) {
ImageRequest request = requestQueue.poll();
Iterator requestIterator = requestQueue.iterator();
while(requestIterator.hasNext()) {
ImageRequest checkRequest = (ImageRequest)requestIterator.next();
if(request.listener.equals(checkRequest.listener)) {
if(request.imageUrl.equals(checkRequest.imageUrl)) {
// Ignore duplicate requests. This is common when doing view recycling in list adapters.
requestIterator.remove();
}
else {
// If this request in the queue was made by the same listener but is for a new URL,
// then use that request instead and remove it from the queue.
request = checkRequest;
requestIterator.remove();
}
}
}
return request;
}
private void processRequest(ImageRequest request) {
try {
Drawable drawable = ImageCache.loadImage(request);
if(drawable == null) {
request.listener.onDrawableError("Failed to load image");
}
else {
// When this request has completed successfully, check the pending requests queue again
// to see if this same listener has made a request for a different image. This is quite
// common in list adpaters when the user is scrolling quickly. In this case, we return
// early without notifying the listener, but at least the image will be cached.
final Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
synchronized(requestQueue) {
for(ImageRequest checkRequest : requestQueue) {
if(request.listener.equals(checkRequest.listener) &&
!request.imageUrl.equals(checkRequest.listener)) {
return;
}
}
}
request.listener.onDrawableLoaded(drawable);
}
}
catch(Exception e) {
// Catch any other random exceptions which may be thrown when loading the image. Although
// the ImageLoader and ImageCache classes do rigorous try/catch checking, it doesn't hurt
// to have a last line of defence.
request.listener.onDrawableError(e.getMessage());
}
}
}
private static ImageLoader getInstance() {
if(staticInstance == null) {
staticInstance = new ImageLoader();
}
return staticInstance;
}
private ImageLoader() {
pendingRequests = new LinkedList<ImageRequest>();
final Worker[] workerPool = new Worker[NUM_WORKERS];
for(int i = 0; i < NUM_WORKERS; i++) {
workerPool[i] = new Worker();
workerPool[i].start();
}
}
public static void load(URL imageUrl, ImageRequest.Listener listener, boolean cacheInMemory) {
Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
synchronized(requestQueue) {
requestQueue.add(new ImageRequest(imageUrl, listener, cacheInMemory));
requestQueue.notify();
}
}
public static void cancelAllRequests() {
final Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
synchronized(requestQueue) {
requestQueue.clear();
}
}
}
|
package org.mtransit.android.ui;
import org.mtransit.android.commons.ui.MTFragmentActivity;
import android.os.Bundle;
public class SplashScreenActivity extends MTFragmentActivity {
private static final String TAG = SplashScreenActivity.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
showHomeActivity();
}
private void showHomeActivity() {
startActivity(MainActivity.newInstance(this, -1));
finish();
}
}
|
package org.objectweb.asm.util;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Label;
import java.util.HashMap;
/**
* A {@link MethodVisitor} that prints the ASM code that generates the methods
* it visits.
*
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
public class ASMifierMethodVisitor extends ASMifierAbstractVisitor
implements MethodVisitor
{
/**
* The label names. This map associates String values to Label keys.
*/
private final HashMap labelNames;
/**
* Constructs a new {@link ASMifierMethodVisitor} object.
*/
public ASMifierMethodVisitor () {
super("mv");
this.labelNames = new HashMap();
}
public AnnotationVisitor visitAnnotationDefault () {
buf.setLength(0);
buf.append("{\n").append("av0 = mv.visitAnnotationDefault();\n");
text.add(buf.toString());
ASMifierAnnotationVisitor av = new ASMifierAnnotationVisitor(0);
text.add(av.getText());
text.add("}\n");
return av;
}
public AnnotationVisitor visitParameterAnnotation (
final int parameter,
final String desc,
final boolean visible)
{
buf.setLength(0);
buf.append("{\n")
.append("av0 = mv.visitParameterAnnotation(")
.append(parameter)
.append(", ");
appendConstant(desc);
buf.append(", ").append(visible).append(");\n");
text.add(buf.toString());
ASMifierAnnotationVisitor av = new ASMifierAnnotationVisitor(0);
text.add(av.getText());
text.add("}\n");
return av;
}
public void visitCode () {
text.add("mv.visitCode();\n");
}
public void visitInsn (final int opcode) {
buf.setLength(0);
buf.append("mv.visitInsn(")
.append(OPCODES[opcode])
.append(");\n");
text.add(buf.toString());
}
public void visitIntInsn (final int opcode, final int operand) {
buf.setLength(0);
buf.append("mv.visitIntInsn(")
.append(OPCODES[opcode])
.append(", ")
.append(operand)
.append(");\n");
text.add(buf.toString());
}
public void visitVarInsn (final int opcode, final int var) {
buf.setLength(0);
buf.append("mv.visitVarInsn(")
.append(OPCODES[opcode])
.append(", ")
.append(var)
.append(");\n");
text.add(buf.toString());
}
public void visitTypeInsn (final int opcode, final String desc) {
buf.setLength(0);
buf.append("mv.visitTypeInsn(")
.append(OPCODES[opcode])
.append(", ");
appendConstant(desc);
buf.append(");\n");
text.add(buf.toString());
}
public void visitFieldInsn (
final int opcode,
final String owner,
final String name,
final String desc)
{
buf.setLength(0);
buf.append("mv.visitFieldInsn(")
.append(OPCODES[opcode])
.append(", ");
appendConstant(owner);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(");\n");
text.add(buf.toString());
}
public void visitMethodInsn (
final int opcode,
final String owner,
final String name,
final String desc)
{
buf.setLength(0);
buf.append("mv.visitMethodInsn(")
.append(OPCODES[opcode])
.append(", ");
appendConstant(owner);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(");\n");
text.add(buf.toString());
}
public void visitJumpInsn (final int opcode, final Label label) {
buf.setLength(0);
declareLabel(label);
buf.append("mv.visitJumpInsn(")
.append(OPCODES[opcode])
.append(", ");
appendLabel(label);
buf.append(");\n");
text.add(buf.toString());
}
public void visitLabel (final Label label) {
buf.setLength(0);
declareLabel(label);
buf.append("mv.visitLabel(");
appendLabel(label);
buf.append(");\n");
text.add(buf.toString());
}
public void visitLdcInsn (final Object cst) {
buf.setLength(0);
buf.append("mv.visitLdcInsn(");
appendConstant(cst);
buf.append(");\n");
text.add(buf.toString());
}
public void visitIincInsn (final int var, final int increment) {
buf.setLength(0);
buf.append("mv.visitIincInsn(")
.append(var)
.append(", ")
.append(increment)
.append(");\n");
text.add(buf.toString());
}
public void visitTableSwitchInsn (
final int min,
final int max,
final Label dflt,
final Label labels[])
{
buf.setLength(0);
for (int i = 0; i < labels.length; ++i) {
declareLabel(labels[i]);
}
declareLabel(dflt);
buf.append("mv.visitTableSwitchInsn(")
.append(min)
.append(", ")
.append(max)
.append(", ");
appendLabel(dflt);
buf.append(", new Label[] {");
for (int i = 0; i < labels.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(labels[i]);
}
buf.append(" });\n");
text.add(buf.toString());
}
public void visitLookupSwitchInsn (
final Label dflt,
final int keys[],
final Label labels[])
{
buf.setLength(0);
for (int i = 0; i < labels.length; ++i) {
declareLabel(labels[i]);
}
declareLabel(dflt);
buf.append("mv.visitLookupSwitchInsn(");
appendLabel(dflt);
buf.append(", new int[] {");
for (int i = 0; i < keys.length; ++i) {
buf.append(i == 0 ? " " : ", ").append(keys[i]);
}
buf.append(" }, new Label[] {");
for (int i = 0; i < labels.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(labels[i]);
}
buf.append(" });\n");
text.add(buf.toString());
}
public void visitMultiANewArrayInsn (final String desc, final int dims) {
buf.setLength(0);
buf.append("mv.visitMultiANewArrayInsn(");
appendConstant(desc);
buf.append(", ")
.append(dims)
.append(");\n");
text.add(buf.toString());
}
public void visitTryCatchBlock (
final Label start,
final Label end,
final Label handler,
final String type)
{
buf.setLength(0);
buf.append("mv.visitTryCatchBlock(");
appendLabel(start);
buf.append(", ");
appendLabel(end);
buf.append(", ");
appendLabel(handler);
buf.append(", ");
appendConstant(type);
buf.append(");\n");
text.add(buf.toString());
}
public void visitLocalVariable (
final String name,
final String desc,
final String signature,
final Label start,
final Label end,
final int index)
{
buf.setLength(0);
buf.append("mv.visitLocalVariable(");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(", ");
appendConstant(signature);
buf.append(", ");
appendLabel(start);
buf.append(", ");
appendLabel(end);
buf.append(", ").append(index).append(");\n");
text.add(buf.toString());
}
public void visitLineNumber (final int line, final Label start) {
buf.setLength(0);
buf.append("mv.visitLineNumber(").append(line).append(", ");
appendLabel(start);
buf.append(");\n");
text.add(buf.toString());
}
public void visitMaxs (final int maxStack, final int maxLocals) {
buf.setLength(0);
buf.append("mv.visitMaxs(")
.append(maxStack)
.append(", ")
.append(maxLocals)
.append(");\n");
text.add(buf.toString());
}
/**
* Appends a declaration of the given label to {@link #buf buf}. This
* declaration is of the form "Label lXXX = new Label();". Does nothing
* if the given label has already been declared.
*
* @param l a label.
*/
private void declareLabel (final Label l) {
String name = (String)labelNames.get(l);
if (name == null) {
name = "l" + labelNames.size();
labelNames.put(l, name);
buf.append("Label ").append(name).append(" = new Label();\n");
}
}
/**
* Appends the name of the given label to {@link #buf buf}. The given label
* <i>must</i> already have a name. One way to ensure this is to always call
* {@link #declareLabel declared} before calling this method.
*
* @param l a label.
*/
private void appendLabel (final Label l) {
buf.append((String)labelNames.get(l));
}
}
|
package org.plantuml.idea.rendering;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ui.JBUI;
import net.sourceforge.plantuml.*;
import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.cucadiagram.DisplayPositionned;
import net.sourceforge.plantuml.descdiagram.DescriptionDiagram;
import net.sourceforge.plantuml.sequencediagram.Event;
import net.sourceforge.plantuml.sequencediagram.Newpage;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagram;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.plantuml.idea.plantuml.PlantUml;
import org.plantuml.idea.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static org.plantuml.idea.lang.annotator.LanguageDescriptor.IDEA_PARTIAL_RENDER;
public class PlantUmlRenderer {
private static final Logger logger = Logger.getInstance(PlantUmlRenderer.class);
public static final Pattern NEW_PAGE_PATTERN = Pattern.compile("\\n\\s*@?(?i)(newpage)(\\p{Blank}+[^\\n]+|\\p{Blank}*)(?=\\n)");
private static final PlantUmlPartialRenderer PARTIAL_RENDERER = new PlantUmlPartialRenderer();
private static final PlantUmlNormalRenderer NORMAL_RENDERER = new PlantUmlNormalRenderer();
/**
* Renders source code and saves diagram images to files according to provided naming scheme
* and image format.
*
* @param source source code to be rendered
* @param baseDir base dir to set for "include" functionality
* @param format image format
* @param fileName fileName to use with first file
* @param fileNameFormat file naming scheme for further files
* @param pageNumber -1 for all pages
* @throws IOException in case of rendering or saving fails
*/
public static void renderAndSave(String source, @Nullable File baseDir, PlantUml.ImageFormat format, String fileName, String fileNameFormat, int zoom, int pageNumber)
throws IOException {
NORMAL_RENDERER.renderAndSave(source, baseDir, format, fileName, fileNameFormat, zoom, pageNumber);
}
/**
* Renders file with support of plantUML include ange paging features, setting base dir and page for plantUML
* to provided values
*/
public static RenderResult render(RenderRequest renderRequest, RenderCacheItem cachedItem) {
File baseDir = renderRequest.getBaseDir();
if (baseDir != null) {
Utils.setPlantUmlDir(baseDir);
}
long start = System.currentTimeMillis();
String source = renderRequest.getSource();
String[] sourceSplit = NEW_PAGE_PATTERN.split(source);
logger.debug("split done ", System.currentTimeMillis() - start, "ms");
boolean partialRender = sourceSplit[0].contains(IDEA_PARTIAL_RENDER);
logger.debug("partialRender ", partialRender);
RenderResult renderResult;
if (partialRender) {
renderResult = PARTIAL_RENDERER.partialRender(renderRequest, cachedItem, start, sourceSplit);
} else {
renderResult = NORMAL_RENDERER.doRender(renderRequest, cachedItem, sourceSplit);
}
return renderResult;
}
public static DiagramInfo zoomDiagram(SourceStringReader reader, int zoom) {
logger.debug("zooming diagram");
int totalPages = 0;
List<BlockUml> blocks = reader.getBlocks();
String fileOrDirname = null;
if (blocks.size() > 1) {
// logger.error("more than 1 block"); //TODO
//happens when the source is incorrectly extracted and contains multiple diagrams
}
for (int i = 0; i < blocks.size(); i++) {
BlockUml block = blocks.get(i);
long start = System.currentTimeMillis();
checkCancel();
Diagram diagram = block.getDiagram();
logger.debug("getDiagram done in ", System.currentTimeMillis() - start, " ms");
start = System.currentTimeMillis();
zoomDiagram(diagram, zoom);
logger.debug("zoom diagram done in ", System.currentTimeMillis() - start, " ms");
fileOrDirname = block.getFileOrDirname();
totalPages = totalPages + diagram.getNbImages();
break;
}
DiagramInfo.Titles titles = getTitles(totalPages, blocks);
return new DiagramInfo(totalPages, titles, fileOrDirname);
}
private static void zoomDiagram(Diagram diagram, int zoom) {
if (diagram instanceof UmlDiagram) {
UmlDiagram umlDiagram = (UmlDiagram) diagram;
Scale scale = umlDiagram.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
umlDiagram.setScale(calculateScale(zoom, scale));
}
} else if (diagram instanceof NewpagedDiagram) {
NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
for (Diagram page : newpagedDiagram.getDiagrams()) {
if (page instanceof DescriptionDiagram) {
DescriptionDiagram descriptionDiagram = (DescriptionDiagram) page;
Scale scale = descriptionDiagram.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
descriptionDiagram.setScale(calculateScale(zoom, scale));
}
}
}
} else if (diagram instanceof AbstractPSystem) { //gantt, salt wireframe - but has no effect
AbstractPSystem d = (AbstractPSystem) diagram;
Scale scale = d.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
d.setScale(calculateScale(zoom, scale));
}
}
}
@NotNull
private static ScaleSimple calculateScale(int zoom, Scale scale) {
return new ScaleSimple(getPlantUmlScale(scale) * getSystemScale() * zoom / 100f);
}
private static double getPlantUmlScale(Scale scale) {
double plantUmlScale = 1.0;
if (scale instanceof ScaleSimple) {
plantUmlScale = scale.getScale(1, 1);
}
return plantUmlScale;
}
private static double getSystemScale() {
try {
return JBUI.ScaleContext.create().getScale(JBUI.ScaleType.SYS_SCALE); //TODO API change 2019/03/05
} catch (Throwable e) {
return 1;
}
}
@NotNull
protected static DiagramInfo.Titles getTitles(int totalPages, List<BlockUml> blocks) {
List<String> titles = new ArrayList<String>(totalPages);
for (BlockUml block : blocks) {
Diagram diagram = block.getDiagram();
if (diagram instanceof SequenceDiagram) {
SequenceDiagram sequenceDiagram = (SequenceDiagram) diagram;
addTitle(titles, sequenceDiagram.getTitle().getDisplay());
List<Event> events = sequenceDiagram.events();
for (Event event : events) {
if (event instanceof Newpage) {
Display title = ((Newpage) event).getTitle();
addTitle(titles, title);
}
}
} else if (diagram instanceof NewpagedDiagram) {
NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
List<Diagram> diagrams = newpagedDiagram.getDiagrams();
for (Diagram diagram1 : diagrams) {
if (diagram1 instanceof UmlDiagram) {
DisplayPositionned title = ((UmlDiagram) diagram1).getTitle();
addTitle(titles, title.getDisplay());
}
}
} else if (diagram instanceof UmlDiagram) {
DisplayPositionned title = ((UmlDiagram) diagram).getTitle();
addTitle(titles, title.getDisplay());
} else if (diagram instanceof PSystemError) {
DisplayPositionned title = ((PSystemError) diagram).getTitle();
if (title == null) {
titles.add(null);
} else {
addTitle(titles, title.getDisplay());
}
}
break;
}
return new DiagramInfo.Titles(titles);
}
protected static void addTitle(List<String> titles, Display display) {
if (display.size() > 0) {
titles.add(display.toString());
} else {
titles.add(null);
}
}
private static void checkCancel() {
if (Thread.currentThread().isInterrupted()) {
throw new RenderingCancelledException();
}
}
}
|
package org.apache.batik.gvt;
import java.awt.geom.Rectangle2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.lang.ref.WeakReference;
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 org.apache.batik.ext.awt.image.renderable.Filter;
import org.apache.batik.gvt.event.GraphicsNodeChangeAdapter;
import org.apache.batik.gvt.event.GraphicsNodeChangeEvent;
/**
* This class tracks the changes on a GVT tree
*
* @author <a href="mailto:Thomas.DeWeeese@Kodak.com">Thomas DeWeese</a>
* @version $Id$
*/
public class UpdateTracker extends GraphicsNodeChangeAdapter {
Map dirtyNodes = null;
Map nodeBounds = new HashMap();
public UpdateTracker(){
}
/**
* Tells whether the GVT tree has changed.
*/
public boolean hasChanged() {
return (dirtyNodes != null);
}
/**
* Returns the list of dirty areas on GVT.
*/
public List getDirtyAreas() {
// System.out.println("Getting dirty areas");
if (dirtyNodes == null)
return null;
List ret = new LinkedList();
Set keys = dirtyNodes.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
WeakReference gnWRef = (WeakReference)i.next();
GraphicsNode gn = (GraphicsNode)gnWRef.get();
// if the weak ref has been cleared then this node is no
// longer part of the GVT tree (and the change should be
// reflected in some ancestor that should also be in the
// dirty list).
if (gn == null) continue;
AffineTransform oat;
oat = (AffineTransform)dirtyNodes.get(gnWRef);
Rectangle2D srcORgn = (Rectangle2D)nodeBounds.get(gnWRef);
Rectangle2D srcNRgn = gn.getBounds();
AffineTransform nat = gn.getTransform();
nodeBounds.put(gnWRef, srcNRgn); // remember the new bounds...
// System.out.println("Rgns: " + srcORgn + " - " + srcNRgn);
// System.out.println("ATs: " + oat + " - " + nat);
Shape oRgn = srcORgn;
Shape nRgn = srcNRgn;
do {
Filter f;
f = gn.getGraphicsNodeRable(false);
// f.invalidateCache(oRng);
// f.invalidateCache(nRng);
f = gn.getEnableBackgroundGraphicsNodeRable(false);
// (need to push rgn through filter chain if any...)
// f.invalidateCache(oRng);
// f.invalidateCache(nRng);
gn = gn.getParent();
if (gn == null) break;
if (dirtyNodes.get(gn.getWeakReference()) != null) break;
AffineTransform at = gn.getTransform();
if (oat != null){
oRgn = oat.createTransformedShape(srcORgn);
if (at != null){
oat.preConcatenate(at);
}
} else {
oat = at;
}
if (nat != null){
nRgn = nat.createTransformedShape(srcNRgn);
if (at != null){
nat.preConcatenate(at);
}
} else {
nat = at;
}
} while (true);
if (gn == null) {
// We made it to the root graphics node so add them.
// System.out.println
// ("Adding: " + oat + " - " + nat + "\n" +
// org.ImageDisplay.stringShape(oRgn) + "\n" +
// org.ImageDisplay.stringShape(nRgn) + "\n");
ret.add(oRgn);
ret.add(nRgn);
}
}
// System.out.println("Dirty area: " + ret);
return ret;
}
/**
* Recieves notification of a change to a GraphicsNode.
* @param gn The graphics node that is changing.
*/
public void changeStarted(GraphicsNodeChangeEvent gnce) {
// System.out.println("A node has changed for: " + this);
GraphicsNode gn = gnce.getGraphicsNode();
WeakReference gnWRef = gn.getWeakReference();
boolean doPut = false;
if (dirtyNodes == null) {
dirtyNodes = new HashMap();
doPut = true;
} else if (!dirtyNodes.containsKey(gnWRef))
doPut = true;
if (doPut) {
AffineTransform at = gn.getTransform();
if (at != null) at = (AffineTransform)at.clone();
dirtyNodes.put(gnWRef, at);
}
Object o = nodeBounds.get(gnWRef);
while (o == null) {
nodeBounds.put(gnWRef, gn.getBounds());
gn = gn.getParent();
if (gn == null) break;
gnWRef = gn.getWeakReference();
o = nodeBounds.get(gnWRef);
}
}
/**
* Clears the tracker.
*/
public void clear() {
dirtyNodes = null;
}
public static class DirtyInfo {
// Always references a GraphicsNode.
WeakReference gn;
// The transform from gn to parent at time of construction.
AffineTransform gn2parent;
public DirtyInfo(GraphicsNode gn, AffineTransform at) {
this.gn = gn.getWeakReference();
this.gn2parent = at;
}
public GraphicsNode getGraphicsNode() {
return (GraphicsNode)gn.get();
}
public AffineTransform getGn2Parent() {
return gn2parent;
}
}
}
|
package org.ssgwt.client.ui.form;
import java.util.Date;
import org.ssgwt.client.ui.datepicker.DateBox;
import org.ssgwt.client.ui.datepicker.MonthDateBox;
import com.google.gwt.user.client.ui.Widget;
/**
* A MonthDateInputField input field for the DynamicForm
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*
* @param <T> The object type the Dynamic form uses to get values from updates the value of the fields on
*/
public abstract class MonthDateInputField <T> extends MonthDateBox implements InputField<T, Date>{
/**
* Whether the field is rewuired or not
*/
private boolean required = false;
/**
* Retrieve the class type the input field returns
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*
* @return The class type the input field returns
*/
@Override
public Class<Date> getReturnType() {
return Date.class;
}
/**
* Retrieve the value from the object that should the displayed on the input field
*
* @param object - The object the value should be retrieved from
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*
* @return The value that should be displayed ob the field
*/
@Override
public abstract Date getValue(T object);
/**
* Sets the value from the input field on the object
*
* @param object - The object the value was retrieved from
* @param value - The value that is currently being displayed on the input field
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*/
@Override
public abstract void setValue(T object, Date value);
/**
* Retrieve the flag that indicates whether the input field is required or not
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*
* @return The flag that indicates whether the input field is required or not
*/
@Override
public boolean isRequired() {
return required;
}
/**
* Sets the flag that indicates whether the input field is required or not
*
* @param required - The flag that indicates whether the input field is required or not
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*/
@Override
public void setRequired(boolean required) {
this.required = required;
}
/**
* Retrieve the input field as a widget
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*
* @return The input field as a widget
*/
@Override
public Widget getInputFieldWidget() {
return this;
}
/**
* Set the field as readOnly
*
* @param readOnly - Flag to indicate whether the field should be read only
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*/
@Override
public void setReadOnly(boolean readOnly) {
super.getTextBox().setReadOnly(readOnly);
}
/**
* Retrieve the flag that indicates whether the field is read only
*
* @author Ruan Naude<ruan.naude@gmail.com>
* @since 28 Dec 2012
*
* @return The flag that indicates whether the field is read only
*/
@Override
public boolean isReadOnly() {
return super.getTextBox().isReadOnly();
}
}
|
package org.svetovid.run;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.svetovid.io.SvetovidProcess;
import org.svetovid.util.CompoundList;
import org.svetovid.util.OperatingSystem;
import org.svetovid.util.OperatingSystemFamily;
public class SvetovidAdminProcessBuilder extends SvetovidProcessBuilder {
private static final List<String> EXECUTABLE = new ArrayList<>(1);
static {
if (OperatingSystem.CURRENT.getFamily() == OperatingSystemFamily.WINDOWS) {
EXECUTABLE.add("elevate"); // Relies on elevate.exe being installed
} else {
EXECUTABLE.add("sudo"); // Relies on sudo being installed
}
}
private static Boolean isAdmin = null;
public static Boolean isAdmin() {
if (isAdmin != null) {
return isAdmin;
}
SvetovidTerminalProcessBuilder builder = new SvetovidTerminalProcessBuilder();
if (OperatingSystem.CURRENT.getFamily() == OperatingSystemFamily.WINDOWS) {
builder.command("NET FILE");
} else {
builder.command("if [[ $EUID -ne 0 ]]; then exit 1; fi");
}
try {
SvetovidProcess process = builder.start();
int code = process.waitFor();
isAdmin = code == 0;
} catch (IOException e) {
isAdmin = null;
} catch (InterruptedException e) {
isAdmin = null;
}
return isAdmin;
}
private CompoundList<String> wholeCommand = new CompoundList<>(EXECUTABLE, null);
private void fixCommandIfAdmin() {
if (isAdmin()) {
wholeCommand.setSublist(0, null);
} else {
wholeCommand.setSublist(0, EXECUTABLE);
}
}
public SvetovidAdminProcessBuilder() {
super();
fixCommandIfAdmin();
super.command(wholeCommand);
}
public SvetovidAdminProcessBuilder(List<String> command) {
this();
command(command);
}
public SvetovidAdminProcessBuilder(String... command) {
this();
command(command);
}
public SvetovidAdminProcessBuilder(Path directory) {
super(directory);
fixCommandIfAdmin();
super.command(wholeCommand);
}
public SvetovidAdminProcessBuilder(Path directory, List<String> command) {
this(directory);
command(command);
}
public SvetovidAdminProcessBuilder(Path directory, String... command) {
this(directory);
command(command);
}
@Override
public List<String> command() {
return wholeCommand.getSublist(1);
}
@Override
public SvetovidAdminProcessBuilder command(List<String> command) {
wholeCommand.setSublist(1, command);
return this;
}
@Override
public SvetovidAdminProcessBuilder command(String... command) {
List<String> list = new ArrayList<>(command.length);
for (String arg : command) {
list.add(arg);
}
return command(list);
}
public SvetovidAdminProcessBuilder command(SvetovidProcessBuilder builder) {
wholeCommand.setSublist(1, builder.builder.command());
return this;
}
@Override
public SvetovidAdminProcessBuilder environment(String key, String value) {
super.environment(key, value);
return this;
}
@Override
public SvetovidAdminProcessBuilder environmentRemove(String key) {
super.environmentRemove(key);
return this;
}
@Override
public SvetovidAdminProcessBuilder directory(Path directory) {
super.directory(directory);
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectInput(Redirect source) {
super.redirectInput(source);
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectOutput(Redirect destination) {
super.redirectOutput(destination);
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectError(Redirect destination) {
super.redirectError(destination);
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectInput(Path file) {
super.redirectInput(file);
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectOutput(Path file) {
super.redirectOutput(file);
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectError(Path file) {
super.redirectError(file);
return this;
}
@Override
public SvetovidAdminProcessBuilder inheritIO() {
super.inheritIO();
return this;
}
@Override
public SvetovidAdminProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
super.redirectErrorStream(redirectErrorStream);
return this;
}
@Override
public SvetovidProcess start() throws IOException {
fixCommandIfAdmin();
return super.start();
}
}
|
package org.torproject.jtor.circuits.impl;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.logging.Logger;
import org.torproject.jtor.TorException;
import org.torproject.jtor.circuits.Circuit;
import org.torproject.jtor.circuits.CircuitNode;
import org.torproject.jtor.circuits.OpenStreamResponse;
import org.torproject.jtor.circuits.Stream;
import org.torproject.jtor.circuits.cells.RelayCell;
public class StreamImpl implements Stream {
private final static Logger logger = Logger.getLogger(StreamImpl.class.getName());
private final static int STREAM_CONNECT_TIMEOUT = 60 * 1000;
private final static int STREAMWINDOW_START = 500;
private final static int STREAMWINDOW_INCREMENT = 50;
private final static int STREAMWINDOW_MAX_UNFLUSHED = 10;
private final CircuitImpl circuit;
private final int streamId;
private final CircuitNode targetNode;
private final TorInputStream inputStream;
private final TorOutputStream outputStream;
private boolean isClosed;
private boolean relayEndReceived;
private int relayEndReason;
private boolean relayConnectedReceived;
private final Object waitConnectLock = new Object();
private final Object windowLock = new Object();
private int packageWindow;
private int deliverWindow;
private String streamTarget = "";
StreamImpl(CircuitImpl circuit, CircuitNode targetNode, int streamId) {
this.circuit = circuit;
this.targetNode = targetNode;
this.streamId = streamId;
this.inputStream = new TorInputStream(this);
this.outputStream = new TorOutputStream(this);
packageWindow = STREAMWINDOW_START;
deliverWindow = STREAMWINDOW_START;
}
void addInputCell(RelayCell cell) {
if(isClosed)
return;
if(cell.getRelayCommand() == RelayCell.RELAY_END) {
synchronized(waitConnectLock) {
relayEndReason = cell.getByte();
relayEndReceived = true;
inputStream.addEndCell(cell);
waitConnectLock.notifyAll();
}
} else if(cell.getRelayCommand() == RelayCell.RELAY_CONNECTED) {
synchronized(waitConnectLock) {
relayConnectedReceived = true;
waitConnectLock.notifyAll();
}
} else if(cell.getRelayCommand() == RelayCell.RELAY_SENDME) {
synchronized(windowLock) {
packageWindow += STREAMWINDOW_INCREMENT;
windowLock.notifyAll();
}
}
else {
inputStream.addInputCell(cell);
synchronized(windowLock) {
deliverWindow
if(deliverWindow < 0)
throw new TorException("Stream has negative delivery window");
}
considerSendingSendme();
}
}
private void considerSendingSendme() {
synchronized(windowLock) {
if(deliverWindow > (STREAMWINDOW_START - STREAMWINDOW_INCREMENT))
return;
if(inputStream.unflushedCellCount() >= STREAMWINDOW_MAX_UNFLUSHED)
return;
final RelayCell sendme = circuit.createRelayCell(RelayCell.RELAY_SENDME, streamId, targetNode);
circuit.sendRelayCell(sendme);
deliverWindow += STREAMWINDOW_INCREMENT;
}
}
public int getStreamId() {
return streamId;
}
public Circuit getCircuit() {
return circuit;
}
CircuitNode getTargetNode() {
return targetNode;
}
public void close() {
if(isClosed)
return;
logger.fine("Closing stream "+ this);
isClosed = true;
inputStream.close();
outputStream.close();
circuit.removeStream(this);
if(!relayEndReceived) {
final RelayCell cell = new RelayCellImpl(circuit.getFinalCircuitNode(), circuit.getCircuitId(), streamId, RelayCell.RELAY_END);
cell.putByte(RelayCell.REASON_DONE);
circuit.sendRelayCellToFinalNode(cell);
}
}
OpenStreamResponse openDirectory() {
streamTarget = "[Directory]";
final RelayCell cell = new RelayCellImpl(circuit.getFinalCircuitNode(), circuit.getCircuitId(), streamId, RelayCell.RELAY_BEGIN_DIR);
circuit.sendRelayCellToFinalNode(cell);
return waitForRelayConnected();
}
OpenStreamResponse openExit(String target, int port) {
streamTarget = target + ":"+ port;
final RelayCell cell = new RelayCellImpl(circuit.getFinalCircuitNode(), circuit.getCircuitId(), streamId, RelayCell.RELAY_BEGIN);
cell.putString(target + ":"+ port);
circuit.sendRelayCellToFinalNode(cell);
return waitForRelayConnected();
}
private OpenStreamResponse waitForRelayConnected() {
final Date startWait = new Date();
synchronized(waitConnectLock) {
while(!relayConnectedReceived) {
if(relayEndReceived)
return OpenStreamResponseImpl.createStreamError(relayEndReason);
if(hasStreamConnectTimedOut(startWait))
return OpenStreamResponseImpl.createStreamTimeout();
try {
waitConnectLock.wait(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return OpenStreamResponseImpl.createStreamTimeout();
}
}
}
return OpenStreamResponseImpl.createStreamOpened(this);
}
private static boolean hasStreamConnectTimedOut(Date startTime) {
final Date now = new Date();
final long diff = now.getTime() - startTime.getTime();
return diff >= STREAM_CONNECT_TIMEOUT;
}
public InputStream getInputStream() {
return inputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void waitForSendWindowAndDecrement() {
waitForSendWindow(true);
}
public void waitForSendWindow() {
waitForSendWindow(false);
}
public void waitForSendWindow(boolean decrement) {
synchronized(windowLock) {
while(packageWindow == 0) {
try {
windowLock.wait();
} catch (InterruptedException e) {
throw new TorException("Thread interrupted while waiting for stream package window");
}
}
if(decrement)
packageWindow
}
targetNode.waitForSendWindow();
}
public String toString() {
return "[Stream stream_id="+ streamId + " circuit="+ circuit +" target="+ streamTarget +"]";
}
}
|
package org.exist.xquery.value;
import com.ibm.icu.text.Collator;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.value.FloatingPointConverter;
import org.exist.xquery.Constants;
import org.exist.xquery.ErrorCodes;
import org.exist.xquery.Expression;
import org.exist.xquery.XPathException;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.function.IntSupplier;
public class DoubleValue extends NumericValue {
// and e is an integer between -1075 and 970, inclusive.
// In addition also -INF, +INF and NaN.
public static final DoubleValue ZERO = new DoubleValue(0.0E0);
public static final DoubleValue POSITIVE_INFINITY = new DoubleValue(Double.POSITIVE_INFINITY);
public static final DoubleValue NEGATIVE_INFINITY = new DoubleValue(Double.NEGATIVE_INFINITY);
public static final DoubleValue NaN = new DoubleValue(Double.NaN);
final double value;
public DoubleValue(final double value) {
this(null, value);
}
public DoubleValue(final Expression expression, final double value) {
super(expression);
this.value = value;
}
public DoubleValue(final AtomicValue otherValue) throws XPathException {
this(null, otherValue);
}
public DoubleValue(final Expression expression, final AtomicValue otherValue) throws XPathException {
this(expression, otherValue.getStringValue());
}
public DoubleValue(final String stringValue) throws XPathException {
this(null, stringValue);
}
public DoubleValue(final Expression expression, final String stringValue) throws XPathException {
super(expression);
try {
if ("INF".equals(stringValue)) {
value = Double.POSITIVE_INFINITY;
} else if ("-INF".equals(stringValue)) {
value = Double.NEGATIVE_INFINITY;
} else if ("NaN".equals(stringValue)) {
value = Double.NaN;
} else {
value = Double.parseDouble(stringValue);
}
} catch (final NumberFormatException e) {
throw new XPathException(getExpression(), ErrorCodes.FORG0001, "cannot construct " + Type.getTypeName(this.getItemType()) +
" from '" + stringValue + "'");
}
}
@Override
public int getType() {
return Type.DOUBLE;
}
@Override
public String getStringValue() {
final FastStringBuffer sb = new FastStringBuffer(20);
//0 is a dummy parameter
FloatingPointConverter.appendDouble(sb, value, false);
return sb.toString();
}
public double getValue() {
return value;
}
@Override
public boolean hasFractionalPart() {
if (isNaN()) {
return false;
}
if (isInfinite()) {
return false;
}
return new DecimalValue(getExpression(), BigDecimal.valueOf(value)).hasFractionalPart();
}
@Override
public Item itemAt(final int pos) {
return pos == 0 ? this : null;
}
@Override
public boolean isNaN() {
return Double.isNaN(value);
}
@Override
public boolean isInfinite() {
return Double.isInfinite(value);
}
@Override
public boolean isZero() {
return Double.compare(Math.abs(value), 0.0) == Constants.EQUAL;
}
@Override
public boolean isNegative() {
return (Double.compare(value, 0.0) < Constants.EQUAL);
}
@Override
public boolean isPositive() {
return (Double.compare(value, 0.0) > Constants.EQUAL);
}
@Override
protected @Nullable IntSupplier createComparisonWith(final NumericValue other) {
final IntSupplier comparison;
if (other instanceof IntegerValue) {
comparison = () -> BigDecimal.valueOf(value).compareTo(new BigDecimal(((IntegerValue)other).value));
} else if (other instanceof DecimalValue) {
comparison = () -> BigDecimal.valueOf(value).compareTo(((DecimalValue)other).value);
} else if (other instanceof DoubleValue) {
comparison = () -> Double.compare(value, ((DoubleValue)other).value);
} else if (other instanceof FloatValue) {
comparison = () -> Double.compare(value, ((FloatValue)other).value);
} else {
return null;
}
return comparison;
}
@Override
public AtomicValue convertTo(final int requiredType) throws XPathException {
switch (requiredType) {
case Type.ATOMIC:
case Type.ITEM:
case Type.NUMBER:
case Type.DOUBLE:
return this;
case Type.FLOAT:
//if (Float.compare(value, 0.0f) && (value < Float.MIN_VALUE || value > Float.MAX_VALUE)
// throw new XPathException(getExpression(), "Value is out of range for type xs:float");
//return new FloatValue((float) value);
return new FloatValue(getExpression(), (float) value);
case Type.UNTYPED_ATOMIC:
return new UntypedAtomicValue(getExpression(), getStringValue());
case Type.STRING:
return new StringValue(getExpression(), getStringValue());
case Type.DECIMAL:
if (isNaN()) {
throw new XPathException(getExpression(), ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('"
+ getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
if (isInfinite()) {
throw new XPathException(getExpression(), ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('" + getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
return new DecimalValue(getExpression(), BigDecimal.valueOf(value));
case Type.INTEGER:
case Type.NON_POSITIVE_INTEGER:
case Type.NEGATIVE_INTEGER:
case Type.LONG:
case Type.INT:
case Type.SHORT:
case Type.BYTE:
case Type.NON_NEGATIVE_INTEGER:
case Type.UNSIGNED_LONG:
case Type.UNSIGNED_INT:
case Type.UNSIGNED_SHORT:
case Type.UNSIGNED_BYTE:
case Type.POSITIVE_INTEGER:
if (isNaN()) {
throw new XPathException(getExpression(), ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('" + getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
if (Double.isInfinite(value)) {
throw new XPathException(getExpression(), ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('"
+ getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
if (requiredType != Type.INTEGER && value > Integer.MAX_VALUE) {
throw new XPathException(getExpression(), ErrorCodes.FOCA0003, "Value is out of range for type " + Type.getTypeName(requiredType));
}
return new IntegerValue(getExpression(), (long) value, requiredType);
case Type.BOOLEAN:
return new BooleanValue(getExpression(), this.effectiveBooleanValue());
default:
throw new XPathException(getExpression(), ErrorCodes.FORG0001, "cannot cast '"
+ Type.getTypeName(this.getItemType())
+ "(\""
+ getStringValue()
+ "\")' to "
+ Type.getTypeName(requiredType));
}
}
@Override
public double getDouble() {
return value;
}
@Override
public int getInt() {
return Long.valueOf(Math.round(value)).intValue();
}
@Override
public long getLong() {
return Math.round(value);
}
@Override
public NumericValue ceiling() {
return new DoubleValue(getExpression(), Math.ceil(value));
}
@Override
public NumericValue floor() {
return new DoubleValue(getExpression(), Math.floor(value));
}
@Override
public NumericValue round() {
if (Double.isNaN(value) || Double.isInfinite(value) || value == 0.0) {
return this;
}
if (value >= -0.5 && value < 0.0) {
return new DoubleValue(getExpression(), -0.0);
}
if (value > Long.MIN_VALUE && value < Long.MAX_VALUE) {
return new DoubleValue(getExpression(), Math.round(value));
}
//too big return original value unchanged
return this;
}
@Override
public NumericValue round(final IntegerValue precision, final RoundingMode roundingMode) throws XPathException {
if (precision == null) {
return round();
}
if (Double.isNaN(value) || Double.isInfinite(value) || value == 0.0) {
return this;
}
/* use the decimal rounding method */
return (DoubleValue) ((DecimalValue) convertTo(Type.DECIMAL)).round(precision, roundingMode).convertTo(Type.DOUBLE);
}
@Override
public NumericValue round(final IntegerValue precision) throws XPathException {
/* use the decimal rounding method */
return round(precision, DecimalValue.DEFAULT_ROUNDING_MODE);
}
@Override
public ComputableValue minus(final ComputableValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(getExpression(), value - ((DoubleValue) other).value);
} else {
return minus((ComputableValue) other.convertTo(getType()));
}
}
@Override
public ComputableValue plus(final ComputableValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(getExpression(), value + ((DoubleValue) other).value);
} else {
return plus((ComputableValue) other.convertTo(getType()));
}
}
@Override
public ComputableValue mult(final ComputableValue other) throws XPathException {
switch (other.getType()) {
case Type.DOUBLE:
return new DoubleValue(getExpression(), value * ((DoubleValue) other).value);
case Type.DAY_TIME_DURATION:
case Type.YEAR_MONTH_DURATION:
return other.mult(this);
default:
return mult((ComputableValue) other.convertTo(getType()));
}
}
@Override
public ComputableValue div(final ComputableValue other) throws XPathException {
if (Type.subTypeOfUnion(other.getType(), Type.NUMBER)) {
//Positive or negative zero divided by positive or negative zero returns NaN.
if (this.isZero() && ((NumericValue) other).isZero()) {
return NaN;
}
//A negative number divided by positive zero returns -INF.
if (this.isNegative() &&
((NumericValue) other).isZero() && ((NumericValue) other).isPositive()) {
return NEGATIVE_INFINITY;
}
//A negative number divided by positive zero returns -INF.
if (this.isNegative() &&
((NumericValue) other).isZero() && ((NumericValue) other).isNegative()) {
return POSITIVE_INFINITY;
}
//Division of Positive by negative zero returns -INF and INF, respectively.
if (this.isPositive() &&
((NumericValue) other).isZero() && ((NumericValue) other).isNegative()) {
return NEGATIVE_INFINITY;
}
if (this.isPositive() &&
((NumericValue) other).isZero() && ((NumericValue) other).isPositive()) {
return POSITIVE_INFINITY;
}
//Also, INF or -INF divided by INF or -INF returns NaN.
if (this.isInfinite() && ((NumericValue) other).isInfinite()) {
return NaN;
}
}
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(getExpression(), value / ((DoubleValue) other).value);
} else {
return div((ComputableValue) other.convertTo(getType()));
}
}
@Override
public IntegerValue idiv(final NumericValue other) throws XPathException {
final ComputableValue result = div(other);
return new IntegerValue(getExpression(), ((IntegerValue) result.convertTo(Type.INTEGER)).getLong());
}
@Override
public NumericValue mod(final NumericValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(getExpression(), value % ((DoubleValue) other).value);
} else {
return mod((NumericValue) other.convertTo(getType()));
}
}
@Override
public NumericValue negate() {
return new DoubleValue(getExpression(), -value);
}
@Override
public NumericValue abs() {
return new DoubleValue(getExpression(), Math.abs(value));
}
@Override
public AtomicValue max(final Collator collator, final AtomicValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(getExpression(), Math.max(value, ((DoubleValue) other).value));
} else {
return new DoubleValue(getExpression(),
Math.max(value, ((DoubleValue) other.convertTo(Type.DOUBLE)).value));
}
}
@Override
public AtomicValue min(final Collator collator, final AtomicValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(getExpression(), Math.min(value, ((DoubleValue) other).value));
} else {
return new DoubleValue(getExpression(),
Math.min(value, ((DoubleValue) other.convertTo(Type.DOUBLE)).value));
}
}
@Override
public int conversionPreference(final Class<?> javaClass) {
if (javaClass.isAssignableFrom(DoubleValue.class)) {
return 0;
}
if (javaClass == Long.class || javaClass == long.class) {
return 3;
}
if (javaClass == Integer.class || javaClass == int.class) {
return 4;
}
if (javaClass == Short.class || javaClass == short.class) {
return 5;
}
if (javaClass == Byte.class || javaClass == byte.class) {
return 6;
}
if (javaClass == Double.class || javaClass == double.class) {
return 1;
}
if (javaClass == Float.class || javaClass == float.class) {
return 2;
}
if (javaClass == String.class) {
return 7;
}
if (javaClass == Boolean.class || javaClass == boolean.class) {
return 8;
}
if (javaClass == Object.class) {
return 20;
}
return Integer.MAX_VALUE;
}
@Override
@SuppressWarnings("unchecked")
public <T> T toJavaObject(final Class<T> target) throws XPathException {
if (target.isAssignableFrom(DoubleValue.class)) {
return (T) this;
} else if (target == Double.class || target == double.class) {
return (T) Double.valueOf(value);
} else if (target == Float.class || target == float.class) {
return (T) new Float(value);
} else if (target == Long.class || target == long.class) {
return (T) Long.valueOf(((IntegerValue) convertTo(Type.LONG)).getValue());
} else if (target == Integer.class || target == int.class) {
final IntegerValue v = (IntegerValue) convertTo(Type.INT);
return (T) Integer.valueOf((int) v.getValue());
} else if (target == Short.class || target == short.class) {
final IntegerValue v = (IntegerValue) convertTo(Type.SHORT);
return (T) Short.valueOf((short) v.getValue());
} else if (target == Byte.class || target == byte.class) {
final IntegerValue v = (IntegerValue) convertTo(Type.BYTE);
return (T) Byte.valueOf((byte) v.getValue());
} else if (target == String.class) {
return (T) getStringValue();
} else if (target == Boolean.class) {
return (T) Boolean.valueOf(effectiveBooleanValue());
}
throw new XPathException(getExpression(),
"cannot convert value of type "
+ Type.getTypeName(getType())
+ " to Java object of type "
+ target.getName());
}
/**
* size writen by {link #serialize(short, boolean)}
*
* @return the size in number of bytes
*/
public int getSerializedSize() {
return 1 + 8;
}
@Override
public int compareTo(final Object o) {
final AtomicValue other = (AtomicValue) o;
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return Double.compare(value, ((DoubleValue) other).value);
} else {
return getType() < other.getType() ? Constants.INFERIOR : Constants.SUPERIOR;
}
}
@Override
public int hashCode() {
return Double.valueOf(value).hashCode();
}
}
|
package complex.loadAllDocuments;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.comp.loader.FactoryHelper;
import com.sun.star.frame.FrameSearchFlag;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XStorable;
import com.sun.star.io.XInputStream;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XInitialization;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.XCloseable;
import com.sun.star.ucb.XSimpleFileAccess;
import complex.loadAllDocuments.helper.InteractionHandler;
import complex.loadAllDocuments.helper.StatusIndicator;
import complex.loadAllDocuments.helper.StreamSimulator;
import complexlib.ComplexTestCase;
import helper.URLHelper;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
/** @short Check the interface method XComponentLoader.loadComponentFromURL()
@descr A prerequisite for this test is a server which allows access to files
that will be loaded via three different access methods:
<ul>
<li>1. nfs (mounted directory / mapped network drive)</li>
<li>2. ftp</li>
<li>3. http</li>
</ul>
<p>
The test will look for a list of files from the <i>TestDocumentPath</i>
on and load these files from the mounted directory, via ftp and http.
The parameters for this have to be "ftp_access" and "http_access".
If they are not given, tests for ftp and http will fail.
@todo We need a further test for accessing UNC pathes on windows!
*/
public class CheckXComponentLoader extends ComplexTestCase
{
// some const
/** used to classify the result of a loadComponentFromURL() request. */
private static final int RESULT_UNKNOWN = 0;
private static final int RESULT_VALID_DOC = 1;
private static final int RESULT_EMPTY_DOC = 2;
private static final int RESULT_ILLEGALARGUMENTEXCEPTION = 3;
private static final int RESULT_IOEXCEPTION = 4;
private static final int RESULT_RUNTIMEEXCEPTION = 5;
private static final int RESULT_EXCEPTION = 6;
/** File/URL separators. */
private static final String fs_url = "/";
private static final String fs_sys = System.getProperty("file.separator");
/** used for testing password protected files. */
private static final String SUFFIX_PASSWORD_TEMPFILE = "password_";
private static final String PREFIX_PASSWORD_TEMPFILE = ".sxw";
private static final String DEFAULT_PASSWORD = "DefaultPasswordForComponentLoaderTest";
// member
/** points to the global uno service manager. */
private XMultiServiceFactory m_xMSF = null;
/** provides XComponentLoader interface. */
private XFrame m_xDesktop = null;
/** provides XComponentLoader interface too. */
private XFrame m_xFrame = null;
/** will be set to xDesktop OR xFrame. */
private XComponentLoader m_xLoader = null;
/** can be used to open local files as stream. */
private XSimpleFileAccess m_xStreamProvider = null;
/** directory for creating temp. files. */
private String m_sTempPath = null;
/** directory for searching files to load */
private String m_sTestDocPath = null;
/** files of m_sTestDocPath to test. */
private static Vector m_lTestFiles = null;
// test environment
/** @short A function to tell the framework,
which test functions are available.
@return All test methods.
@todo Think about selection of tests from outside ...
*/
public String[] getTestMethodNames()
{
// TODO think about trigger of sub-tests from outside
return new String[]
{
"checkURLEncoding" ,
"checkURLHandling" ,
"checkUsingOfMediaDescriptor",
"checkStreamLoading" ,
"checkLoadingWithPassword"
};
}
/** @short Create the environment for following tests.
@descr Use either a component loader from desktop or
from frame
*/
public void before()
{
// get uno service manager from global test environment
m_xMSF = (XMultiServiceFactory)param.getMSF();
// create stream provider
try
{
m_xStreamProvider = (XSimpleFileAccess)UnoRuntime.queryInterface(
XSimpleFileAccess.class,
m_xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"));
}
catch(java.lang.Throwable ex)
{
ex.printStackTrace();
failed("Could not create a stream provider instance.");
}
// create desktop instance
try
{
m_xDesktop = (XFrame)UnoRuntime.queryInterface(
XFrame.class,
m_xMSF.createInstance("com.sun.star.frame.Desktop"));
}
catch(java.lang.Throwable ex)
{
ex.printStackTrace();
failed("Could not create the desktop instance.");
}
// create frame instance
m_xFrame = m_xDesktop.findFrame("testFrame_componentLoader" ,
FrameSearchFlag.TASKS | FrameSearchFlag.CREATE);
if (m_xFrame==null)
failed("Couldn't create test frame.");
// define default loader for testing
// TODO think about using of bot loader instances!
m_xLoader = (XComponentLoader)UnoRuntime.queryInterface(
XComponentLoader.class,
m_xDesktop);
if (m_xLoader==null)
failed("Desktop service doesnt support needed component loader interface.");
// get temp path for this environment
m_sTempPath = (String) param.get("TempPath");
m_sTempPath = "."+fs_sys;
// get all files from the given directory
// TODO URLHelper should ignore directories!
m_lTestFiles = new Vector();
m_sTestDocPath = (String) param.get("TestDocumentPath");
try
{
File aBaseDir = new File(m_sTestDocPath);
Vector lDirContent = URLHelper.getSystemFilesFromDir(aBaseDir.getPath());
Enumeration lList = lDirContent.elements();
int nBasePathLength = m_sTestDocPath.length();
while(lList.hasMoreElements())
{
File aFile = (File)lList.nextElement();
// ignore broken links and directories at all
if (
(!aFile.exists()) ||
(!aFile.isFile())
)
{
continue;
}
String sCompletePath = aFile.getAbsolutePath();
String sSubPath = sCompletePath.substring(nBasePathLength + 1);
// Some test files are checked into CVS. ignore CVS helper files!
if (sSubPath.indexOf("CVS") > -1)
continue;
m_lTestFiles.add(sSubPath);
}
}
catch(java.lang.Throwable ex)
{
ex.printStackTrace();
failed("Couldn't find test documents.");
}
}
/** @short close the environment.
*/
public void after()
{
XCloseable xClose = (XCloseable)UnoRuntime.queryInterface(
XCloseable.class,
m_xFrame);
try
{
xClose.close(false);
}
catch(com.sun.star.util.CloseVetoException exVeto)
{ failed("Test frame couldn't be closed successfully."); }
m_xFrame = null;
m_xLoader = null;
}
/** @short Look for files in the given directory for loading.
*/
public void checkUsingOfMediaDescriptor()
{
InteractionHandler xHandler = new InteractionHandler();
StatusIndicator xIndicator = new StatusIndicator(StatusIndicator.SHOWSTATUS_LOG);
PropertyValue[] lProps = new PropertyValue[3];
lProps[0] = new PropertyValue();
lProps[0].Name = "Hidden";
lProps[0].Value = Boolean.TRUE;
lProps[1] = new PropertyValue();
lProps[1].Name = "InteractionHandler";
lProps[1].Value = xHandler;
lProps[2] = new PropertyValue();
lProps[2].Name = "StatusIndicator";
lProps[2].Value = xIndicator;
Enumeration aSnapshot = m_lTestFiles.elements();
while (aSnapshot.hasMoreElements())
{
File aSysFile = new File(m_sTestDocPath+fs_sys+(String)aSnapshot.nextElement());
String sURL = URLHelper.getFileURLFromSystemPath(aSysFile);
loadURL(m_xLoader, RESULT_VALID_DOC, sURL, "_blank", 0, lProps);
// Its not needed to reset this using states!
// Its done internaly ...
if (!xIndicator.wasUsed())
failed("External progress was not used for loading.");
if (xHandler.wasUsed())
failed("External interaction handler was not used for loading.");
}
}
/** TODO document me and move this method to a more global helper! */
private String impl_getTempFileName(String sTempPath,
String sSuffix ,
String sPrefix )
{
File aDir = new File(sTempPath);
if (!aDir.exists())
failed("Could not access temp directory \""+sTempPath+"\".");
for (int i=0; i<999999; ++i)
{
File aTempFile = new File(aDir, sSuffix+i+sPrefix);
if (!aTempFile.exists())
return aTempFile.getAbsolutePath();
}
failed("Seems that all temp file names are currently in use!");
return null;
}
/** TODO document me and move this method to a more global helper! */
private void impl_createTempOfficeDocument(XComponentLoader xLoader ,
String sSourceURL,
String sTargetURL,
String sFilter ,
String sPassword )
{
PropertyValue[] lLoadProps = new PropertyValue[1];
lLoadProps[0] = new PropertyValue();
lLoadProps[0].Name = "Hidden";
lLoadProps[0].Value = Boolean.TRUE;
PropertyValue[] lSaveProps = new PropertyValue[3];
lSaveProps[0] = new PropertyValue();
lSaveProps[0].Name = "FilterName";
lSaveProps[0].Value = sFilter;
lSaveProps[1] = new PropertyValue();
lSaveProps[1].Name = "PassWord";
lSaveProps[1].Value = sPassword;
lSaveProps[2] = new PropertyValue();
lSaveProps[2].Name = "Overwrite";
lSaveProps[2].Value = Boolean.TRUE;
XComponent xDoc = null;
try
{
// load it
xDoc = xLoader.loadComponentFromURL(sSourceURL, "_blank", 0, lLoadProps);
if (xDoc == null)
failed("Could create office document, which should be saved as temp one.");
// save it as temp file
XStorable xStore = (XStorable)UnoRuntime.queryInterface(
XStorable.class,
xDoc);
xStore.storeAsURL(sTargetURL, lSaveProps);
// Dont forget to close this file. Otherwise the temp file is locked!
XCloseable xClose = (XCloseable)UnoRuntime.queryInterface(
XCloseable.class,
xDoc);
xClose.close(false);
}
catch(java.lang.Throwable ex)
{
ex.printStackTrace();
failed("Could not create temp office document.");
}
}
/** @short Check the password handling.
@descr The used password is the one given
as password for the ftp connection,
or - if none given a default one.
*/
public void checkLoadingWithPassword()
{
String sTempFile = impl_getTempFileName(m_sTempPath, SUFFIX_PASSWORD_TEMPFILE, PREFIX_PASSWORD_TEMPFILE);
File aTestFile = new File(sTempFile);
String sTestURL = URLHelper.getFileURLFromSystemPath(aTestFile);
impl_createTempOfficeDocument(m_xLoader, "private:factory/swriter", sTestURL, "StarOffice XML (Writer)", DEFAULT_PASSWORD);
PropertyValue[] lArgs1 = new PropertyValue[2];
lArgs1[0] = new PropertyValue();
lArgs1[0].Name = "Hidden";
lArgs1[0].Value = Boolean.TRUE;
lArgs1[1] = new PropertyValue();
lArgs1[1].Name = "Password";
lArgs1[1].Value = DEFAULT_PASSWORD;
PropertyValue[] lArgs2 = new PropertyValue[1];
lArgs2[0] = new PropertyValue();
lArgs2[0].Name = "Hidden";
lArgs2[0].Value = Boolean.TRUE;
loadURL(m_xLoader, RESULT_VALID_DOC, sTestURL, "_blank", 0, lArgs1);
loadURL(m_xLoader, RESULT_EMPTY_DOC, sTestURL, "_blank", 0, lArgs2);
}
/**
* Check URL encoding. The first filename that matches "*.sxw"
* is used as source for several encodings.
*/
public void checkURLEncoding() {
PropertyValue[] lProps = new PropertyValue[1];
lProps[0] = new PropertyValue();
lProps[0].Name = "Hidden";
lProps[0].Value = Boolean.TRUE;
// first get encoding of this system
InputStreamReader in = new InputStreamReader(System.in);
String sSystemEncoding = in.getEncoding();
log.println("This system's encoding: " + sSystemEncoding);
if (m_lTestFiles == null) {
failed("Found an empty directory. There are no files for testing.");
return;
}
// get a file name as byte array
Enumeration aSnapshot = m_lTestFiles.elements();
byte[] baURL = null;
while (aSnapshot.hasMoreElements()) {
File aFile = new File(m_sTestDocPath + fs_sys +
aSnapshot.nextElement());
String sFile = URLHelper.getFileURLFromSystemPath(aFile);
// take the first sxw file as stream
if (sFile.endsWith(".sxw")) {
baURL = sFile.getBytes();
break;
}
}
if (baURL == null) {
failed("Found no file to load. Cannot test.");
return;
}
//construct several different encoded strings
String[] sEncoding = new String[] {
"US-ASCII", "TRUE", // us ascii encoding
"ISO-8859-1", "TRUE", // iso encoding
"UTF-8", "TRUE", // 8 bit utf encoding
"UTF-16BE", "FALSE", // 16 bit big endian utf
"UTF-16LE", "FALSE", // 16 bit little endian utf
"UTF-16", "FALSE" // 16 bit, order specified by byte order mark
};
for (int i = 0; i < sEncoding.length; i = i + 2) {
try {
String encURL = new String(baURL, sEncoding[i]);
log.println("ENC[" + sEncoding[i] + "]");
if (sEncoding[i + 1].equals("TRUE")) {
loadURL(m_xLoader, RESULT_VALID_DOC, encURL, "_blank", 0,
lProps);
} else {
loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, encURL, "_blank", 0,
lProps);
}
} catch (java.io.UnsupportedEncodingException e) {
failed("Unsopported Encoding: " + sEncoding[i] +
"\n Not able to test encoding on this platform.", true);
}
}
}
/**
* Check url handling with a load of URLs.
* 1. unsupported URLs.
* 2. "stupid" URLs
* 3. case sensitive URLs
* 4. FTP URLs
* 5. HTTP URLs
*/
public void checkURLHandling() {
PropertyValue[] lProps = new PropertyValue[1];
lProps[0] = new PropertyValue();
lProps[0].Name = "Hidden";
lProps[0].Value = Boolean.TRUE;
log.println("check possible but unsupported URLs");
String[] sIllegalArgs = new String[] {
"slot:5000", "slot:10909", ".uno:SaveAs", ".uno:Open",
};
loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sIllegalArgs,
"_blank", 0, lProps);
log.println("check stupid URLs");
sIllegalArgs = new String[] {
"slot:xxx", "slot:111111111", ".uno:save_as", ".uno:open_this",
".UnO:*",
};
loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sIllegalArgs,
"_blank", 0, lProps);
String[] sEmptyDocs = new String[] {
"mailo:hansi.meier@germany.sun.com", "file:/c:\\test/file.cxx",
"file:///c|:\\test/file.cxx", "http_server://staroffice-doc\\",
"c:\\\\test///\\test.sxw", "news_:staroffice-doc",
"newsletter@blubber", "private_factory/swriter",
"private:factory
"c:\\test\\test.sxw", "macro:///ImportWizard.Main.Main",
"macro:///Euro.AutoPilotRun.StartAutoPilot",
"service:com.sun.star.frame.Frame",
"mailto:steffen.grund@germany.sun.com", "news:staroffice-doc",
"macro:/ExportWizard", "macro://Euro.AutoPilotRun.StartAutoPilot",
"service:com.sun.star.frame."
};
loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sEmptyDocs, "_blank", 0,
lProps);
log.println("check case senstive URLs");
sIllegalArgs = new String[] {
"sLot:5000", "sloT:10909", ".unO:SaveAs", ".uno:OPEN",
};
loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sIllegalArgs,
"_blank", 0, lProps);
sEmptyDocs = new String[] {
"private:factory/SWRITER", "private:factory/SWRITER/WEB",
"macro:///importwizard.main.main",
"Macro:///euro.autopilotrun.startautopilot",
"Service:Com.Sun.Star.Frame.Frame",
"Mailto:andreas.schluens@germany.sun.com", "neWs:staroffice-doc",
"News:Staroffice-doc"
};
loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sEmptyDocs, "_blank", 0,
lProps);
log.println("check FTP URLs");
String sFTPURL = (String) param.get("FtpAccess");
Enumeration aSnapshot = m_lTestFiles.elements();
while (aSnapshot.hasMoreElements()) {
String doc = (String) aSnapshot.nextElement();
// if os is windows
doc = doc.replace('\\', '/');
if (doc.indexOf("CVS")<0) {
loadURL(m_xLoader, RESULT_VALID_DOC, sFTPURL + "/" + doc,
"_blank", 0, lProps);
}
}
log.println("check HTTP URLs");
String sHTTPURL = (String) param.get("HttpAccess");
aSnapshot = m_lTestFiles.elements();
while (aSnapshot.hasMoreElements()) {
String doc = (String) aSnapshot.nextElement();
// if os is windows
doc = doc.replace('\\', '/');
if (doc.indexOf("CVS")<0) {
loadURL(m_xLoader, RESULT_VALID_DOC, sHTTPURL + "/" + doc,
"_blank", 0, lProps);
}
}
}
/** TODo document me
*/
public void checkStreamLoading()
{
PropertyValue[] lProps = new PropertyValue[2];
lProps[0] = new PropertyValue();
lProps[0].Name = "Hidden";
lProps[0].Value = Boolean.TRUE;
lProps[1] = new PropertyValue();
lProps[1].Name = "InputStream";
Enumeration aSnapshot = m_lTestFiles.elements();
while (aSnapshot.hasMoreElements())
{
File aFile = new File(m_sTestDocPath + fs_sys + (String) aSnapshot.nextElement());
String sURL = URLHelper.getFileURLFromSystemPath(aFile);
if (sURL.indexOf("CVS") > -1)
continue;
try
{
XInputStream xStream = m_xStreamProvider.openFileRead(sURL);
lProps[1].Value = xStream;
}
catch(com.sun.star.uno.Exception e)
{ failed("Could not open test file \""+sURL+"\" for stream test."); }
// check different version of "private:stream" URL!
loadURL(m_xLoader, RESULT_VALID_DOC, "private:stream" , "_blank", 0, lProps);
loadURL(m_xLoader, RESULT_VALID_DOC, "private:stream/", "_blank", 0, lProps);
}
}
/**
* Loads one URL with the given parameters using the method
* loadComponentFromURL(). Further it's possible to specify, whch result is
* required and we check internally if it was reached. Logging of errors
* and success stories is done inside this method too. Of course we catch
* all possible exceptions and try to leave the office without any forgotten
* but opened documents.
*/
private void loadURL(XComponentLoader m_xLoader, int nRequiredResult,
String sURL, String sTarget, int nFlags,
PropertyValue[] lProps) {
int nResult = RESULT_EMPTY_DOC;
XComponent xDoc = null;
try {
xDoc = m_xLoader.loadComponentFromURL(sURL, sTarget, nFlags,
lProps);
if (xDoc != null) {
nResult = RESULT_VALID_DOC;
} else {
nResult = RESULT_EMPTY_DOC;
}
} catch (com.sun.star.lang.IllegalArgumentException exArgument) {
nResult = RESULT_ILLEGALARGUMENTEXCEPTION;
} catch (com.sun.star.io.IOException exIO) {
nResult = RESULT_IOEXCEPTION;
} catch (com.sun.star.uno.RuntimeException exRuntime) {
exRuntime.printStackTrace();
nResult = RESULT_RUNTIMEEXCEPTION;
} catch (Exception e) {
e.printStackTrace();
nResult = RESULT_EXCEPTION;
}
try {
if (xDoc != null) {
xDoc.dispose();
xDoc = null;
}
} catch (com.sun.star.uno.RuntimeException exClosing) {
log.println("exception during disposing of a document found!" +
" Doesn't influence test - but should be checked.");
}
String sMessage = "URL[\"" + sURL + "\"]";
if (nResult == nRequiredResult) {
log.println(sMessage + " expected result [" +
convertResult2String(nResult) + "] ");
} else {
failed(sMessage + " unexpected result [" +
convertResult2String(nResult) + "] " +
"\nrequired was [" +
convertResult2String(nRequiredResult) + "]" +
"\nwe got [" + convertResult2String(nResult) + "]",
true);
}
}
private void loadURL(XComponentLoader m_xLoader, int nRequiredResult,
String[] sURL, String sTarget, int nFlags,
PropertyValue[] lProps) {
for (int i = 0; i < sURL.length; i++)
loadURL(m_xLoader, nRequiredResult, sURL[i], sTarget, nFlags,
lProps);
}
/**
* it match the int result value to a string, which can be used for logging
*/
private static String convertResult2String(int nResult) {
switch (nResult) {
case RESULT_VALID_DOC:
return "VALID_DOC";
case RESULT_EMPTY_DOC:
return "EMPTY_DOC";
case RESULT_ILLEGALARGUMENTEXCEPTION:
return "ILLEGALARGUMENTEXCEPTION";
case RESULT_IOEXCEPTION:
return "IOEXCEPTION";
case RESULT_RUNTIMEEXCEPTION:
return "RUNTIMEEXCEPTION";
case RESULT_EXCEPTION:
return "ALLOTHEREXCEPTION";
}
return "unknown!";
}
}
|
package com.codenvy.analytics.services.marketo;
import com.codenvy.analytics.Injector;
import com.codenvy.analytics.metrics.AbstractMetric;
import com.codenvy.analytics.metrics.Context;
import com.codenvy.analytics.metrics.Parameters;
import com.codenvy.analytics.metrics.users.UsersStatisticsList;
import com.codenvy.analytics.services.AbstractUsersActivityTest;
import com.codenvy.analytics.services.view.CSVFileHolder;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Map;
import static org.testng.AssertJUnit.assertEquals;
/**
* @author Alexander Reshetnyak
*/
public class TestMarketoReportGenerator extends AbstractUsersActivityTest {
private static final Map<String, String> HEADERS = MarketoReportGenerator.headers;
@Override
protected Map<String, String> getHeaders() {
return HEADERS;
}
@BeforeClass
public void prepare() throws Exception {
}
@BeforeMethod
public void clearDatabase() {
super.clearDatabase();
}
@Test
public void testWholePeriod() throws Exception {
computeStatistics("20131101");
computeStatistics("20131102");
MarketoReportGenerator job = Injector.getInstance(MarketoReportGenerator.class);
CSVFileHolder cleaner = Injector.getInstance(CSVFileHolder.class);
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20131101");
builder.put(Parameters.TO_DATE, "20131102");
File jobFile = cleaner.createNewFile();
job.prepareReport(jobFile, builder.build(), Context.EMPTY, false);
Map<String, Map<String, String>> content = read(jobFile);
assertEquals(4, content.size());
// verify
Map<String, String> headData = content.get("_HEAD");
assertEquals(HEADERS.size(), headData.size());
for (String column : HEADERS.values()) {
assertEquals(column, headData.get(column));
}
// verify "user1@gmail.com" data
Map<String, String> user1Data = content.get("user1@gmail.com");
assertEquals(HEADERS.size(), user1Data.size());
assertEquals("user1@gmail.com", user1Data.get(HEADERS.get(AbstractMetric.ID)));
assertEquals("0", user1Data.get(HEADERS.get(UsersStatisticsList.BUILDS)));
assertEquals("0", user1Data.get(HEADERS.get(UsersStatisticsList.DEPLOYS)));
assertEquals("true", user1Data.get(HEADERS.get(MarketoReportGenerator.PROFILE_COMPLETED)));
assertEquals("2", user1Data.get(HEADERS.get(UsersStatisticsList.PROJECTS)));
assertEquals("0", user1Data.get(HEADERS.get(UsersStatisticsList.RUNS)));
assertEquals("5", user1Data.get(HEADERS.get(UsersStatisticsList.TIME)));
assertEquals("0", user1Data.get(HEADERS.get(UsersStatisticsList.LOGINS)));
assertEquals("", user1Data.get(HEADERS.get(MarketoReportGenerator.LAST_PRODUCT_LOGIN)));
assertEquals("29", user1Data.get(HEADERS.get(MarketoReportGenerator.POINTS)));
// verify "user2@gmail.com" data
Map<String, String> user2Data = content.get("user2@gmail.com");
assertEquals(HEADERS.size(), user2Data.size());
assertEquals("user2@gmail.com", user2Data.get(HEADERS.get(AbstractMetric.ID)));
assertEquals("1", user2Data.get(HEADERS.get(UsersStatisticsList.BUILDS)));
assertEquals("6", user2Data.get(HEADERS.get(UsersStatisticsList.DEPLOYS)));
assertEquals("false", user2Data.get(HEADERS.get(MarketoReportGenerator.PROFILE_COMPLETED)));
assertEquals("1", user2Data.get(HEADERS.get(UsersStatisticsList.PROJECTS)));
assertEquals("1", user2Data.get(HEADERS.get(UsersStatisticsList.RUNS)));
assertEquals("10", user2Data.get(HEADERS.get(UsersStatisticsList.TIME)));
assertEquals("2", user2Data.get(HEADERS.get(UsersStatisticsList.LOGINS)));
assertEquals("2013-11-01 10:10:30", user2Data.get(HEADERS.get(MarketoReportGenerator.LAST_PRODUCT_LOGIN)));
assertEquals("94", user2Data.get(HEADERS.get(MarketoReportGenerator.POINTS)));
// verify "user3@gmail.com" data
Map<String, String> user3Data = content.get("user3@gmail.com");
assertEquals(HEADERS.size(), user3Data.size());
assertEquals("user3@gmail.com", user3Data.get(HEADERS.get(AbstractMetric.ID)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.BUILDS)));
assertEquals("1", user3Data.get(HEADERS.get(UsersStatisticsList.DEPLOYS)));
assertEquals("false", user3Data.get(HEADERS.get(MarketoReportGenerator.PROFILE_COMPLETED)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.PROJECTS)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.RUNS)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.TIME)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.LOGINS)));
assertEquals("", user3Data.get(HEADERS.get(MarketoReportGenerator.LAST_PRODUCT_LOGIN)));
assertEquals("12", user3Data.get(HEADERS.get(MarketoReportGenerator.POINTS)));
}
@Test
public void testUpdate() throws Exception {
computeStatistics("20131101");
computeStatistics("20131102");
computeStatistics("20131103");
MarketoReportGenerator job = Injector.getInstance(MarketoReportGenerator.class);
CSVFileHolder cleaner = Injector.getInstance(CSVFileHolder.class);
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20131101");
builder.put(Parameters.TO_DATE, "20131103");
Context.Builder builderActiveUsers = new Context.Builder();
builderActiveUsers.put(Parameters.FROM_DATE, "20131103");
builderActiveUsers.put(Parameters.TO_DATE, "20131103");
File jobFile = cleaner.createNewFile();
job.prepareReport(jobFile, builder.build(), builderActiveUsers.build(), true);
Map<String, Map<String, String>> content = read(jobFile);
assertEquals(2, content.size());
// verify
Map<String, String> headData = content.get("_HEAD");
assertEquals(HEADERS.size(), headData.size());
for (String column : HEADERS.values()) {
assertEquals(column, headData.get(column));
}
// verify "user3@gmail.com" data
Map<String, String> user3Data = content.get("user3@gmail.com");
assertEquals(HEADERS.size(), user3Data.size());
assertEquals("user3@gmail.com", user3Data.get(HEADERS.get(AbstractMetric.ID)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.BUILDS)));
assertEquals("2", user3Data.get(HEADERS.get(UsersStatisticsList.DEPLOYS)));
assertEquals("false", user3Data.get(HEADERS.get(MarketoReportGenerator.PROFILE_COMPLETED)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.PROJECTS)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.RUNS)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.TIME)));
assertEquals("0", user3Data.get(HEADERS.get(UsersStatisticsList.LOGINS)));
assertEquals("", user3Data.get(HEADERS.get(MarketoReportGenerator.LAST_PRODUCT_LOGIN)));
assertEquals("24", user3Data.get(HEADERS.get(MarketoReportGenerator.POINTS)));
}
}
|
package uk.ac.ebi.quickgo.annotation.download.converter;
import uk.ac.ebi.quickgo.annotation.download.converter.helpers.Extensions;
import uk.ac.ebi.quickgo.annotation.download.converter.helpers.WithFrom;
import uk.ac.ebi.quickgo.annotation.model.Annotation;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.function.BiFunction;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import static uk.ac.ebi.quickgo.annotation.download.converter.helpers.DateConverter.ISO_8601_FORMATTER;
import static uk.ac.ebi.quickgo.annotation.download.converter.helpers.Helper.nullToEmptyString;
import static uk.ac.ebi.quickgo.annotation.download.converter.helpers.Taxon.taxonIdToString;
public class AnnotationToGPAD implements BiFunction<Annotation, List<String>, List<String>> {
private static final String GO_EVIDENCE = "goEvidence=";
private static final String OUTPUT_DELIMITER = "\t";
@Override
public List<String> apply(Annotation annotation, List<String> selectedFields) {
if (Objects.isNull(annotation.slimmedIds) || annotation.slimmedIds.isEmpty()) {
return Collections.singletonList(toOutputRecord(annotation, annotation.goId));
} else {
return annotation.slimmedIds.stream().map(goId -> this.toOutputRecord(annotation, goId)).collect(toList());
}
}
private String toOutputRecord(Annotation annotation, String goId) {
StringJoiner tsvJoiner = new StringJoiner(OUTPUT_DELIMITER);
return tsvJoiner.add(annotation.getGeneProduct().db())
.add(annotation.getGeneProduct().populatedGeneProductId())
.add(nullToEmptyString(annotation.qualifier))
.add(nullToEmptyString(goId))
.add(nullToEmptyString(annotation.reference))
.add(nullToEmptyString(annotation.evidenceCode))
.add(WithFrom.nullOrEmptyListToString(annotation.withFrom))
.add(taxonIdToString(annotation.interactingTaxonId))
.add(ofNullable(annotation.date).map(ISO_8601_FORMATTER).orElse(""))
.add(nullToEmptyString(annotation.assignedBy))
.add(Extensions.asString(annotation.extensions))
.add(GO_EVIDENCE + nullToEmptyString(annotation.goEvidence))
.toString();
}
}
|
package uk.ac.ebi.quickgo.annotation.controller;
import uk.ac.ebi.quickgo.annotation.AnnotationREST;
import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.common.AnnotationFields;
import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository;
import uk.ac.ebi.quickgo.annotation.service.statistics.StatisticsTypeConfigurer;
import uk.ac.ebi.quickgo.common.store.TemporarySolrDataStore;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker.createGenericDocs;
import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.contentTypeToBeJson;
import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.totalNumOfResults;
/**
* This class demonstrates the effects of configuring the limits of statistics types. E.g., specifying a limit
* for the number of GO ids should have the effect of limiting the number of GO ids returned when requests to
* the statistics end-point are made.
*
* Created 16/08/17
* @author Edd
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {AnnotationREST.class, StatsConfigsAreAppliedIT.TestStatsTypeConfig.class})
@WebAppConfiguration
public class StatsConfigsAreAppliedIT {
// temporary data store for solr's data, which is automatically cleaned on exit
@ClassRule
public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore();
public static final String GO_ID = "goId";
public static final String TAXON_ID = "taxonId";
// the configured stats limits used in this test
static final int GO_ID_LIMIT_PROPERTY = 6;
static final int TAXON_ID_LIMIT_PROPERTY = 7;
private static final int SAVED_DOC_COUNT = 50;
private static final int DEFAULT_STATS_TYPE_COUNT = 10;
private static final String STATS_VALUES_JSON_PATH_FORMAT =
"$.results[?(@.groupName == %s)].types[?(@.type == %s)].values[*].key";
private static final String STATS_ENDPOINT = "/annotation/stats";
private static final String ANNOTATION = "annotation";
private static final String GENE_PRODUCT = "geneProduct";
private static final String REFERENCE = "reference";
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private AnnotationRepository repository;
@Before
public void setup() {
repository.deleteAll();
mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void goIdConfigReadAndApplied() throws Exception {
List<AnnotationDocument> docs =
createDocsAndApply((i, doc) -> doc.goId = createGOId(i));
repository.save(docs);
ResultActions response = mockMvc.perform(get(STATS_ENDPOINT));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(jsonPath(statsValuesJSONPath(ANNOTATION, GO_ID), hasSize(GO_ID_LIMIT_PROPERTY)))
.andExpect(jsonPath(statsValuesJSONPath(GENE_PRODUCT, GO_ID), hasSize(GO_ID_LIMIT_PROPERTY)));
}
@Test
public void taxonIdConfigReadAndApplied() throws Exception {
List<AnnotationDocument> docs =
createDocsAndApply((i, doc) -> doc.taxonId = i);
repository.save(docs);
ResultActions response = mockMvc.perform(get(STATS_ENDPOINT));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(jsonPath(statsValuesJSONPath(ANNOTATION, TAXON_ID), hasSize(TAXON_ID_LIMIT_PROPERTY)))
.andExpect(jsonPath(statsValuesJSONPath(GENE_PRODUCT, TAXON_ID), hasSize(TAXON_ID_LIMIT_PROPERTY)));
}
@Test
public void noConfigForReferenceMeansThereAreDefaultNumber() throws Exception {
List<AnnotationDocument> docs =
createDocsAndApply((i, doc) -> doc.reference = createRef(i));
repository.save(docs);
ResultActions response = mockMvc.perform(get(STATS_ENDPOINT));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(jsonPath(statsValuesJSONPath(ANNOTATION, REFERENCE), hasSize(DEFAULT_STATS_TYPE_COUNT)))
.andExpect(jsonPath(statsValuesJSONPath(GENE_PRODUCT, REFERENCE), hasSize(DEFAULT_STATS_TYPE_COUNT)));
}
private String statsValuesJSONPath(String statType, String subType) {
return String.format(STATS_VALUES_JSON_PATH_FORMAT, statType, subType);
}
/**
* Creates a list of {@link AnnotationDocument}s and applies a transformation to each document
* according to their index in this document list.
*
* @param docTransformer the document transformation function
* @return a list of {@link AnnotationDocument}s
*/
private List<AnnotationDocument> createDocsAndApply(BiConsumer<Integer, AnnotationDocument> docTransformer) {
List<AnnotationDocument> docs = createGenericDocs(SAVED_DOC_COUNT);
for (int i = 0; i < docs.size(); i++) {
docTransformer.accept(i, docs.get(i));
}
return docs;
}
private String createRef(int i) {
return REFERENCE + i;
}
private String createGOId(int idNum) {
return String.format("GO:000%03d", idNum);
}
/**
* <p>This class configures the statistics type limits for the purposes of this test, which would otherwise
* be configured from a properties file.
*
* <p>The "goID" and "taxonId" statistics types are limited here explicitly. All other statistics types will
* not be explicitly limited, and therefore will return the default number of values, i.e., 10.
*/
@Configuration
static class TestStatsTypeConfig {
static Map<String, Integer> typeLimitProperties = typeLimitTestValues();
@Primary
@Bean
public StatisticsTypeConfigurer statsTypeConfigurer() {
return new StatisticsTypeConfigurer(typeLimitProperties);
}
private static Map<String, Integer> typeLimitTestValues() {
Map<String, Integer> properties = new HashMap<>();
properties.put(AnnotationFields.Facetable.GO_ID, GO_ID_LIMIT_PROPERTY);
properties.put(AnnotationFields.Facetable.TAXON_ID, TAXON_ID_LIMIT_PROPERTY);
return properties;
}
}
}
|
package com.antonio.samir.meteoritelandingsspots.service.server;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.location.Location;
import android.support.annotation.Nullable;
import android.util.Log;
import com.antonio.samir.meteoritelandingsspots.model.Meteorite;
import com.antonio.samir.meteoritelandingsspots.service.repository.MeteoriteRepositoryFactory;
import com.antonio.samir.meteoritelandingsspots.service.repository.database.MeteoriteDao;
import com.antonio.samir.meteoritelandingsspots.service.server.nasa.MeteoriteNasaAsyncTaskService;
import com.antonio.samir.meteoritelandingsspots.service.server.nasa.NasaService;
import com.antonio.samir.meteoritelandingsspots.service.server.nasa.NasaServiceFactory;
import com.antonio.samir.meteoritelandingsspots.util.GPSTracker;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
class MeteoriteNasaService implements MeteoriteService {
private static final String TAG = MeteoriteNasaService.class.getSimpleName();
private final GPSTracker mGpsTracker;
private Context mContext;
public MeteoriteNasaService(final Context context, final GPSTracker gpsTracker) {
mContext = context;
mGpsTracker = gpsTracker;
}
@Override
public LiveData<List<Meteorite>> getMeteorites() {
//Return meteorites
final MeteoriteDao meteoriteDao = MeteoriteRepositoryFactory.getMeteoriteDao(mContext);
final boolean gpsEnabled = mGpsTracker.isGPSEnabled();
final MutableLiveData<List<Meteorite>> list = new MutableLiveData<>();
if (gpsEnabled) {
final MutableLiveData<Location> mGpsTrackerLocation = mGpsTracker.getLocation();
mGpsTrackerLocation.observeForever(location -> {
if (location != null) {
try {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
String sortOrder = String.format("ABS(reclat - %s ) + ABS(reclong - %s) ASC", latitude, longitude);
final LiveData<List<Meteorite>> liveData = meteoriteDao.getMeteoriteOrdened("1 ORDER BY " + sortOrder);
liveData.observeForever(meteorites -> {
final List<Meteorite> liveDataValue = liveData.getValue();
SortedSet<Meteorite> sortedSet = new TreeSet<>((m1, m2) -> {
final Double distance1 = ((Meteorite)m1).distance(latitude, longitude);
final Double distance2 = ((Meteorite)m2).distance(latitude, longitude);
return (distance1 > 0 && distance2 > 0)? distance1.compareTo(distance2):0;
});
sortedSet.addAll(liveDataValue);
list.setValue(new ArrayList<>(sortedSet));
});
//mGpsTrackerLocation.removeObserver(this);
//mGpsTracker.stopUpdates();
} catch (Exception e) {
Log.e(TAG, "GPS failed", e);
}
}
});
}
final LiveData<List<Meteorite>> liveData = meteoriteDao.getMeteoriteOrdened(null);
liveData.observeForever(new Observer<List<Meteorite>>() {
@Override
public void onChanged(@Nullable List<Meteorite> meteorites) {
if (meteorites.isEmpty()) {
//If it is empty so load the data from internet
final NasaService nasaService = NasaServiceFactory.getNasaService(mContext);
new MeteoriteNasaAsyncTaskService(nasaService, meteoriteDao).execute();
} else {
list.setValue(meteorites);
liveData.removeObserver(this);
}
}
});
return list;
}
}
|
package nodomain.freeyourgadget.gadgetbridge.service.devices.nothing;
import android.content.SharedPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEvent;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.BatteryState;
import nodomain.freeyourgadget.gadgetbridge.service.serial.GBDeviceProtocol;
import static nodomain.freeyourgadget.gadgetbridge.util.CheckSums.getCRC16ansi;
import static nodomain.freeyourgadget.gadgetbridge.util.GB.hexdump;
public class NothingProtocol extends GBDeviceProtocol {
private static final Logger LOG = LoggerFactory.getLogger(NothingProtocol.class);
final UUID UUID_DEVICE_CTRL = UUID.fromString("aeac4a03-dff5-498f-843a-34487cf133eb");
private boolean isFirstExchange = true;
private static final byte CONTROL_DEVICE_TYPE_TWS_HEADSET = 1;
private static final int CONTROL_CRC = 0x20;
private static final byte MASK_RSP_CODE = 0x1f;
private static final short MASK_DEVICE_TYPE = 0x0F00;
private static final short MASK_REQUEST_CMD = (short) 0x8000;
private static final byte MASK_BATTERY = 0x7f;
private static final byte MASK_BATTERY_CHARGING = (byte) 0x80;
//incoming
private static final short battery_status = (short) 0xe001;
private static final short battery_status2 = (short) 0xc007;
private static final short audio_mode_status = (short) 0xc01e;
private static final short unk_maybe_ack = (short) 0xf002;
private static final short unk_close_case = (short) 0xe002; //sent twice when the case is closed with earphones in
//outgoing
private static final short find_device = (short) 0xf002;
private static final short in_ear_detection = (short) 0xf004;
private static final short audio_mode = (short) 0xf00f;
private HashMap<Byte, GBDeviceEventBatteryInfo> batteries;
private static final byte battery_earphone_left = 0x02;
private static final byte battery_earphone_right = 0x03;
private static final byte battery_case = 0x04;
@Override
public GBDeviceEvent[] decodeResponse(byte[] responseData) {
List<GBDeviceEvent> devEvts = new ArrayList<>();
if (isFirstExchange) {
isFirstExchange = false;
devEvts.add(new GBDeviceEventVersionInfo()); //TODO: this is a weird hack to make the DBHelper happy. Replace with proper firmware detection
}
ByteBuffer incoming = ByteBuffer.wrap(responseData);
incoming.order(ByteOrder.LITTLE_ENDIAN);
byte sof = incoming.get();
if (sof != 0x55) {
LOG.error("Error in message, wrong start of frame: " + hexdump(responseData));
return null;
}
short control = incoming.getShort();
if (!isSupportedDevice(control)) {
LOG.error("Unsupported device specified in message: " + hexdump(responseData));
return null;
}
if (!isOk(control)) {
LOG.error("Message is not ok: " + hexdump(responseData));
return null;
}
short command = incoming.getShort();
short length = incoming.getShort();
incoming.get();
byte[] payload = Arrays.copyOfRange(responseData, incoming.position(), incoming.position() + length);
switch (getRequestCommand(command)) {
case battery_status:
case battery_status2:
devEvts.addAll(handleBatteryInfo(payload));
break;
case audio_mode_status:
devEvts.add(handleAudioModeStatus(payload));
break;
case unk_maybe_ack:
LOG.debug("received ack");
break;
case unk_close_case:
LOG.debug("case closed");
break;
default:
LOG.debug("Incoming message - control:" + control + " requestCommand: " + (getRequestCommand(command) & 0xffff) + "length: " + length + " dump: " + hexdump(responseData));
}
return devEvts.toArray(new GBDeviceEvent[devEvts.size()]);
}
boolean isCrcNeeded(short control) {
return (control & CONTROL_CRC) != 0;
}
byte[] encodeMessage(short control, short command, byte[] payload) {
ByteBuffer msgBuf = ByteBuffer.allocate(8 + payload.length);
msgBuf.order(ByteOrder.LITTLE_ENDIAN);
msgBuf.put((byte) 0x55); //sof
msgBuf.putShort(control);
msgBuf.putShort(command);
msgBuf.putShort((short) payload.length);
msgBuf.put((byte) 0x00); //fsn TODO: is this always 0?
msgBuf.put(payload);
if (isCrcNeeded(control)) {
msgBuf.position(0);
ByteBuffer crcBuf = ByteBuffer.allocate(msgBuf.capacity() + 2);
crcBuf.order(ByteOrder.LITTLE_ENDIAN);
crcBuf.put(msgBuf);
crcBuf.putShort((short) getCRC16ansi(msgBuf.array()));
return crcBuf.array();
}
return msgBuf.array();
}
byte[] encodeBatteryStatusReq() {
return encodeMessage((short) 0x5120, battery_status2, new byte[]{});
}
byte[] encodeAudioModeStatusReq() {
return encodeMessage((short) 0x120, audio_mode_status, new byte[]{});
}
//TODO: unify mapping between bytes and strings in the following two functions
private GBDeviceEvent handleAudioModeStatus(byte[] payload) {
SharedPreferences prefs = GBApplication.getDeviceSpecificSharedPrefs(getDevice().getAddress());
SharedPreferences.Editor editor = prefs.edit();
if (Arrays.equals(payload, new byte[]{0x01, 0x01, 0x00})) {
editor.putString(DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_AUDIOMODE, "anc").apply();
} else if (Arrays.equals(payload, new byte[]{0x01, 0x03, 0x00})) {
editor.putString(DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_AUDIOMODE, "anc-light").apply();
} else if (Arrays.equals(payload, new byte[]{0x01, 0x05, 0x00})) {
editor.putString(DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_AUDIOMODE, "off").apply();
} else if (Arrays.equals(payload, new byte[]{0x01, 0x07, 0x00})) {
editor.putString(DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_AUDIOMODE, "transparency").apply();
} else {
LOG.warn("Unknown audio mode. Payload: " + hexdump(payload));
}
return null;
}
byte[] encodeAudioMode(String desired) {
byte[] payload = new byte[]{0x01, 0x05, 0x00};
switch (desired) {
case "anc":
payload[1] = 0x01;
break;
case "anc-light":
payload[1] = 0x03;
break;
case "transparency":
payload[1] = 0x07;
break;
case "off":
default:
}
return encodeMessage((short) 0x120, audio_mode, payload);
}
@Override
public byte[] encodeFindDevice(boolean start) {
byte payload = (byte) (start ? 0x01 : 0x00);
return encodeMessage((short) 0x120, find_device, new byte[]{payload});
}
@Override
public byte[] encodeSendConfiguration(String config) {
SharedPreferences prefs = GBApplication.getDeviceSpecificSharedPrefs(getDevice().getAddress());
switch (config) {
case DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_INEAR:
byte enabled = (byte) (prefs.getBoolean(DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_INEAR, true) ? 0x01 : 0x00);
return encodeMessage((short) 0x120, in_ear_detection, new byte[]{0x01, 0x01, enabled});
// response: 55 20 01 04 70 00 00 00
case DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_AUDIOMODE:
return encodeAudioMode(prefs.getString(DeviceSettingsPreferenceConst.PREF_NOTHING_EAR1_AUDIOMODE, "off"));
// response: 55 20 01 0F 70 00 00 00
default:
LOG.debug("CONFIG: " + config);
}
return super.encodeSendConfiguration(config);
}
@Override
public byte[] encodeSetTime() {
// This are earphones, there is no time to set here. However this method gets called soon
// after connecting, hence we use it to perform some initializations.
// TODO: Find a way to send more requests during the first connection
return encodeAudioModeStatusReq();
}
private List<GBDeviceEvent> handleBatteryInfo(byte[] payload) {
List<GBDeviceEvent> batEvts = new ArrayList<>();
//LOG.debug("Battery payload: " + hexdump(payload));
/* payload:
1st byte is number of batteries, then $number pairs follow:
{idx, value}
idx is 0x02 for left ear, 0x03 for right ear, 0x04 for case
value goes from 0-64 (equivalent of 0-100 in hexadecimal)
Since Gadgetbridge supports only one battery, we use an average of the levels for the
battery level.
If one of the batteries is recharging, we consider the battery as recharging.
*/
// GBDeviceEventBatteryInfo evBattery = new GBDeviceEventBatteryInfo();
// evBattery.level = 0;
// boolean batteryCharging = false;
int numBatteries = payload[0];
for (int i = 0; i < numBatteries; i++) {
batteries.get(payload[1 + 2 * i]).level = (payload[2 + 2 * i] & MASK_BATTERY);
batteries.get(payload[1 + 2 * i]).state =
((payload[2 + 2 * i] & MASK_BATTERY_CHARGING) == MASK_BATTERY_CHARGING) ? BatteryState.BATTERY_CHARGING : BatteryState.BATTERY_NORMAL;
batEvts.add(batteries.get(payload[1 + 2 * i]));
// evBattery.level += (short) ((payload[2 + 2 * i] & MASK_BATTERY) / numBatteries);
// if (!batteryCharging) {
// batteryCharging = ((payload[2 + 2 * i] & MASK_BATTERY_CHARGING) == MASK_BATTERY_CHARGING);
// LOG.debug("single battery level: " + hexdump(payload, 2+2*i,1) +"-"+ ((payload[2+2*i] & 0xff))+":" + evBattery.level);
}
// evBattery.state = BatteryState.UNKNOWN;
// evBattery.state = batteryCharging ? BatteryState.BATTERY_CHARGING : evBattery.state;
// return evBattery;
return batEvts;
}
private short getRequestCommand(short command) {
return (short) (command | MASK_REQUEST_CMD);
}
private boolean isOk(short control) {
return (control & MASK_RSP_CODE) == 0;
}
private boolean isSupportedDevice(short control) {
return getDeviceType(control) == CONTROL_DEVICE_TYPE_TWS_HEADSET;
}
private byte getDeviceType(short control) {
return (byte) ((control & MASK_DEVICE_TYPE) >> 8);
}
protected NothingProtocol(GBDevice device) {
super(device);
batteries = new HashMap<>(3);
batteries.put(battery_earphone_left, new GBDeviceEventBatteryInfo());
batteries.put(battery_earphone_right, new GBDeviceEventBatteryInfo());
batteries.put(battery_case, new GBDeviceEventBatteryInfo());
batteries.get(battery_case).batteryIndex=0;
batteries.get(battery_earphone_left).batteryIndex=1;
batteries.get(battery_earphone_right).batteryIndex=2;
}
}
|
package org.csstudio.utility.ldap.reader;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.csstudio.platform.logging.CentralLogger;
import org.csstudio.utility.ldap.connection.LDAPConnector;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
public class LDAPReader extends Job {
private String name;
private String filter;
private int defaultScope=SearchControls.SUBTREE_SCOPE;
private ArrayList<String> list;
private ErgebnisListe ergebnisListe;
/**
* Used the connection settings from org.csstudio.utility.ldap.ui
* (used with UI)
*
* @param nameUFilter<br> 0: name<br>1: = filter<br>
* @param ergebnisListe
*/
public LDAPReader(String[] nameUFilter, ErgebnisListe ergebnisListe){
super("LDAPReader");
setBasics(nameUFilter[0], nameUFilter[1], ergebnisListe);
}
/**
* Used the connection settings from org.csstudio.utility.ldap.ui
* (used with UI)
*
* @param nameUFilter<br> 0: name<br>1: = filter<br>
* @param searchScope
* @param ergebnisListe
*/
public LDAPReader(String[] nameUFilter, int searchScope, ErgebnisListe ergebnisListe){
super("LDAPReader");
setBasics(nameUFilter[0], nameUFilter[1], ergebnisListe);
setDefaultScope(searchScope);
}
/**
* Used the connection settings from org.csstudio.utility.ldap.ui
* (used with UI)
*
* @param name
* @param filter
* @param ergebnisListe
*/
public LDAPReader(String name, String filter, ErgebnisListe ergebnisListe){
super("LDAPReader");
setBasics(name, filter, ergebnisListe);
}
/**
* Used the connection settings from org.csstudio.utility.ldap.ui
* (used with UI)
*
* @param name
* @param filter
* @param searchScope
* @param ergebnisListe
*/
public LDAPReader(String name, String filter, int searchScope, ErgebnisListe ergebnisListe){
super("LDAPReader");
setBasics(name, filter, ergebnisListe);
setDefaultScope(searchScope);
}
/**
* Need connection settings. (For Headless use)
*
* @param name
* @param filter
* @param searchScope
* @param ergebnisListe
* @param env connection settings.
* @see javax.naming.directory.DirContext;
* @see javax.naming.Context;
*/
public LDAPReader(String name, String filter, int searchScope, ErgebnisListe ergebnisListe, Hashtable<Object,String> env){
super("LDAPReader");
setBasics(name, filter, ergebnisListe);
setDefaultScope(searchScope);
}
/**
* Need connection settings. (For Headless use)
*
* @param name
* @param filter
* @param ergebnisListe
* @param env value for<br>
* 0: Context.PROVIDER_URL<br>
* 1: Context.SECURITY_PROTOCOL<br>
* 2: Context.SECURITY_AUTHENTICATION<br>
* 3: Context.SECURITY_PRINCIPAL<br>
* 4: Context.SECURITY_CREDENTIALS<br>
*
* @see javax.naming.directory.DirContext;
* @see javax.naming.Context;
*/
public LDAPReader(String name, String filter, ErgebnisListe ergebnisListe, String[] env){
super("LDAPReader");
setBasics(name, filter, ergebnisListe);
}
/**
*
* @param name
* @param filter
* @param searchScope
* @param ergebnisListe
* @param env value for<br>
* 0: Context.PROVIDER_URL<br>
* 1: Context.SECURITY_PROTOCOL<br>
* 2: Context.SECURITY_AUTHENTICATION<br>
* 3: Context.SECURITY_PRINCIPAL<br>
* 4: Context.SECURITY_CREDENTIALS<br>
*
* @see javax.naming.directory.DirContext;
* @see javax.naming.Context;
*/
public LDAPReader(String name, String filter, int searchScope, ErgebnisListe ergebnisListe, String[] env){
super("LDAPReader");
setBasics(name, filter, ergebnisListe);
setDefaultScope(searchScope);
}
/**
* @param name
* @param filter
* @param ergebnisListe
*/
private void setBasics(String name, String filter, ErgebnisListe ergebnisListe) {
this.ergebnisListe = ergebnisListe;
this.name = name;
this.filter = filter;
}
@Override
protected IStatus run(IProgressMonitor monitor ) {
monitor.beginTask("LDAP Reader", IProgressMonitor.UNKNOWN);
DirContext ctx;
LDAPConnector ldpc;
try {
ldpc = new LDAPConnector();
} catch (NamingException e1) {
try {
Thread.sleep(100);
ldpc = new LDAPConnector();
} catch (InterruptedException e) {
CentralLogger.getInstance().error(this, e);
return Status.CANCEL_STATUS;
} catch (NamingException e) {
CentralLogger.getInstance().error(this, e);
return Status.CANCEL_STATUS;
}
}
if((ctx = ldpc.getDirContext())!=null){
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(defaultScope);
try{
list = new ArrayList<String>();
NamingEnumeration answer = ctx.search(name, filter, ctrl);
// ctx.search(name, filter, ctrl);
try {
while(answer.hasMore()){
String name = ((SearchResult)answer.next()).getName();
list.add(name);
if(monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
}
if(list.size()<1){
list.add("no entry found");
}
} catch (NamingException e) {
CentralLogger.getInstance().info(this,"LDAP Fehler");
CentralLogger.getInstance().info(this,e);
}
answer.close();
ctx.close();
ergebnisListe.setAnswer(list);
monitor.done();
return Status.OK_STATUS;
// return ASYNC_FINISH;
} catch (NamingException e) {
CentralLogger.getInstance().info(this,"Falscher LDAP Suchpfad.");
CentralLogger.getInstance().info(this,e);
}
}
monitor.setCanceled(true);
return Status.CANCEL_STATUS;
}
private void setDefaultScope(int defaultScope) {
this.defaultScope = defaultScope;
}
}
|
package at.fhj.swd14.pse.repository.internal;
import org.junit.Test;
/**
* This class just exists to increase coverage
*
* @author Patrick Kainz
*/
public class RepositoryCoverageTest {
@Test
public void increaseCoverage() {
new DepartmentRepositoryImpl();
new KnowledgeRepositoryImpl();
new MailaddressRepositoryImpl();
new PersonImageRepositoryImpl();
new PersonRepositoryImpl();
new PersonStatusRepositoryImpl();
new PhonenumberRepositoryImpl();
new HobbyRepositoryImpl();
new MessageRepositoryImpl();
new NewsRepositoryImpl();
new CommentRepositoryImpl();
new CommunityRepositoryImpl();
}
}
|
package com.pwn;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Connect extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
JSch jsch = new JSch();
String user = "root@10.55.176.112";
String host = "127.0.0.1";
UserInfo ui = new UserInfo() {
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public boolean promptPassword(String s) {
return false;
}
@Override
public boolean promptPassphrase(String s) {
return false;
}
@Override
public boolean promptYesNo(String s) {
return false;
}
@Override
public void showMessage(String s) {
}
};
try {
Session session = jsch.getSession(host, user, 22);
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("exec");
channel.setInputStream(null);
String command = "dir";
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(System.err);
try {
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.out.println(e);
}
}catch (JSchException je){
System.out.println("Erorr " + je);
}
}
}
|
package gov.nih.nci.cabig.caaers.domain;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.caaers.utils.DateUtils;
import gov.nih.nci.cabig.caaers.validation.annotation.UniqueObjectInCollection;
import gov.nih.nci.cabig.ctms.collections.LazyListHelper;
import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.annotations.*;
import org.springframework.beans.BeanUtils;
/**
* This class represents the ExpeditedAdverseEventReport domain object.
*
* @author Rhett Sutphin
* @author Biju Joseph
* @author Ion C. Olaru
*
*/
@Entity
@Table(name = "ae_reports")
@GenericGenerator(name = "id-generator", strategy = "native", parameters = {@Parameter(name = "sequence", value = "seq_ae_reports_id")})
public class ExpeditedAdverseEventReport extends AbstractMutableDomainObject implements Serializable{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -3747213703166595074L;
/** The created at. */
private Timestamp createdAt;
/** The lazy list helper. */
private LazyListHelper lazyListHelper;
/** The response description. */
private AdverseEventResponseDescription responseDescription;
/** The treatment information. */
private TreatmentInformation treatmentInformation;
/** The additional information. */
private AdditionalInformation additionalInformation;
/** The reporter. */
private Reporter reporter;
/** The physician. */
private Physician physician;
/** The participant history. */
private ParticipantHistory participantHistory;
/** The disease history. */
private DiseaseHistory diseaseHistory;
/** The reporting period. */
private AdverseEventReportingPeriod reportingPeriod;
/** The reports. */
private List<Report> reports;
/** The Constant log. */
private static final Log log = LogFactory.getLog(ExpeditedAdverseEventReport.class);
// TODO
// private List<MedicalDevice> medicalDevices;
/**
* Instantiates a new expedited adverse event report.
*/
public ExpeditedAdverseEventReport() {
lazyListHelper = new LazyListHelper();
addReportChildLazyList(AdverseEvent.class);
addReportChildLazyList(Lab.class);
addReportChildLazyList(MedicalDevice.class);
addReportChildLazyList(RadiationIntervention.class);
addReportChildLazyList(SurgeryIntervention.class);
addReportChildLazyList(BehavioralIntervention.class);
addReportChildLazyList(GeneticIntervention.class);
addReportChildLazyList(BiologicalIntervention.class);
addReportChildLazyList(DietarySupplementIntervention.class);
addReportChildLazyList(OtherAEIntervention.class);
addReportChildLazyList(ConcomitantMedication.class);
addReportChildLazyList(OtherCause.class);
addReportChildLazyList(SAEReportPriorTherapy.class);
addReportChildLazyList(SAEReportPreExistingCondition.class);
}
/**
* Adds the report child lazy list.
*
* @param <T> the generic type
* @param klass the klass
*/
private <T extends ExpeditedAdverseEventReportChild> void addReportChildLazyList(Class<T> klass) {
lazyListHelper.add(klass, new ExpeditedAdverseEventReportChildFactory<T>(klass, this));
}
////// LOGIC
/**
* Gets the notification message.
*
* @return the notification message
*/
@Transient
public String getNotificationMessage() {
if (isNotificationMessagePossible()) {
String other = "";
String fullName = "";
AdverseEvent firstAe = getAdverseEventsInternal().get(0);
if (firstAe.getAdverseEventCtcTerm().getCtcTerm() != null) {
CtcTerm term = firstAe.getAdverseEventCtcTerm().getCtcTerm();
fullName = term.getFullName();
other = term.isOtherRequired()
? String.format(" (%s)", firstAe.getDetailsForOther()) : "";
} else {
fullName = firstAe.getAdverseEventTerm().getUniversalTerm();
}
return String.format("Grade %d adverse event with term %s%s",
firstAe.getGrade().getCode(),
fullName, other
);
} else {
throw new CaaersSystemException(
"Cannot create notification message until primary AE is filled in");
}
}
/**
* Checks if is notification message possible.
*
* @return true, if is notification message possible
*/
@Transient
public boolean isNotificationMessagePossible() {
if (getAdverseEventsInternal().size() < 1) return false;
AdverseEvent ae = getAdverseEventsInternal().get(0);
return ae != null && ae.getGrade() != null && ae.getAdverseEventTerm().getTerm() != null;
}
/**
* Gets the participant.
*
* @return the participant
*/
@Transient
public Participant getParticipant() {
return getAssignment() == null ? null : getAssignment().getParticipant();
}
/**
* Gets the study.
*
* @return the study
*/
@Transient
public Study getStudy() {
StudySite ss = getAssignment() == null ? null : getAssignment().getStudySite();
return ss == null ? null : ss.getStudy();
}
/**
* Gets the study site.
*
* @return the study site
*/
@Transient
public StudySite getStudySite() {
StudySite ss = getAssignment() == null ? null : getAssignment().getStudySite();
return ss;
}
@Transient
public Map<String, String> getSummary() {
return getSummary(true);
}
/**
* Gets the summary.
*
* @return the summary
*/
@Transient
public Map<String, String> getSummary(boolean unIdentifiedMode) {
Map<String, String> summary = new LinkedHashMap<String, String>();
summary.put("Study", summaryLine(getStudy()));
if(unIdentifiedMode) {
summary.put("Participant", summaryLine(getAssignment()));
}else {
summary.put("Participant", summaryLine(getParticipant()));
}
summary.put("Report created at", getCreatedAt() == null ? null : getCreatedAt().toString());
String primaryAeLine = null;
if (getAdverseEvents().size() > 0 && getAdverseEvents().get(0).getAdverseEventTerm() != null && getAdverseEvents().get(0).getAdverseEventTerm().getUniversalTerm() != null) {
primaryAeLine = getAdverseEvents().get(0).getAdverseEventTerm().getUniversalTerm();
}
summary.put("Primary AE", primaryAeLine);
summary.put("AE count", Integer.toString(getAdverseEvents().size()));
summary.put("Public identifier", getPublicIdentifier());
// TODO: placeholders
summary.put("Ticket number", null);
summary.put("Next report due", null);
summary.put("Course", getReportingPeriod().getName());
return summary;
}
/**
* Summary line.
*
* @param participant the participant
* @return the string
*/
private String summaryLine(Participant participant) {
if (participant == null) return null;
StringBuilder sb = new StringBuilder();
appendPrimaryIdentifier(participant, sb);
sb.append(" ").append(participant.getFullName());
return sb.toString();
}
private String summaryLine(StudyParticipantAssignment assignment) {
if (assignment == null) return null;
StringBuilder sb = new StringBuilder();
sb.append(assignment.getStudySubjectIdentifier());
return sb.toString();
}
/**
* Summary line.
*
* @param study the study
* @return the string
*/
private String summaryLine(Study study) {
if (study == null) return null;
StringBuilder sb = new StringBuilder();
appendPrimaryIdentifier(study, sb);
sb.append(" ").append(study.getShortTitle());
return sb.toString();
}
/**
* Append primary identifier.
*
* @param ided the ided
* @param sb the sb
*/
private void appendPrimaryIdentifier(IdentifiableByAssignedIdentifers ided, StringBuilder sb) {
if (ided.getPrimaryIdentifier() != null) {
sb.append(" (").append(ided.getPrimaryIdentifier().getValue()).append(')');
}
}
/**
* Adds the adverse event.
*
* @param adverseEvent the adverse event
*/
public void addAdverseEvent(AdverseEvent adverseEvent) {
getAdverseEventsInternal().add(adverseEvent);
if (adverseEvent != null) adverseEvent.setReport(this);
}
/**
* To cover cases when we do not need the AdverseEvent to have a referrence to ExpeditedAdverseEventReport
* @param adverseEvent
*/
public void addAdverseEventUnidirectional(AdverseEvent adverseEvent) {
getAdverseEventsInternal().add(adverseEvent);
}
/**
* This method will remove the {@link AdverseEvent} from the list and will
* reset the {@link AdverseEvent#getReport()} association to null. However,
* you're still responsible for persisting the updated {@link AdverseEvent}
* instance, because the removal operation will not cascade.
*
* @param adverseEvent
*/
public void removeAdverseEvent(AdverseEvent adverseEvent) {
getAdverseEventsInternal().remove(adverseEvent);
if (adverseEvent != null)
adverseEvent.setReport(null);
}
/**
* @param aeId
* @return
*/
@Transient
public AdverseEvent getAdverseEvent(int aeId) {
for (AdverseEvent ae: getAdverseEventsInternal()) {
if (ae.getId()!=null && ae.getId()==aeId) {
return ae;
}
}
return null;
}
/**
* Gets the adverse events.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
public List<AdverseEvent> getAdverseEvents() {
return lazyListHelper.getLazyList(AdverseEvent.class);
}
/**
* List of adverse events that are not retired.
*
* @return the active adverse events
*/
@Transient
public List<AdverseEvent> getActiveAdverseEvents(){
List<AdverseEvent> activeEvents = new ArrayList<AdverseEvent>();
for(AdverseEvent ae: getAdverseEvents()){
if(ae.isRetired()) continue;
activeEvents.add(ae);
}
return activeEvents;
}
/**
* List of active adverse events, that are modified.
*
* @return the active modified adverse events
*/
@Transient
public List<AdverseEvent> getActiveModifiedAdverseEvents(){
List<AdverseEvent> adverseEvents = new ArrayList<AdverseEvent>();
for(AdverseEvent ae: getActiveAdverseEvents()){
if(ae.isModified()){
adverseEvents.add(ae);
}
}
return adverseEvents;
}
/**
* This method will return all the adverse events,which got modified.
* It is obtained by comparing the saved signature and newly calculated signature.
*
* @return the modified adverse events
*/
@Transient
public List<AdverseEvent> getModifiedAdverseEvents(){
List<AdverseEvent> adverseEvents = new ArrayList<AdverseEvent>();
for(AdverseEvent ae: getAdverseEvents()){
if(ae.isModified()){
adverseEvents.add(ae);
}
}
return adverseEvents;
}
/**
* Gets the modified adverse events.
*
* @param ruleableFields the ruleable fields
* @return the modified adverse events
* @author Ion C. Olaru
* This method will return all the adverse events, which have at least one ruleable field modified
*/
@Transient
public List<AdverseEvent> getModifiedAdverseEvents(List<String> ruleableFields) {
List<AdverseEvent> adverseEvents = new ArrayList<AdverseEvent>();
for(AdverseEvent ae: getAdverseEvents()){
if (ae.isRuleableFieldsModified(ruleableFields)) {
adverseEvents.add(ae);
}
}
return adverseEvents;
}
/**
* Adds the lab.
*
* @param lab the lab
*/
public void addLab(Lab lab) {
getLabsInternal().add(lab);
if (lab != null) lab.setReport(this);
}
/**
* Gets the labs.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
public List<Lab> getLabs() {
return lazyListHelper.getLazyList(Lab.class);
}
/**
* Adds the medical device.
*
* @param medicalDevice the medical device
*/
public void addMedicalDevice(MedicalDevice medicalDevice) {
getMedicalDevicesInternal().add(medicalDevice);
if (medicalDevice != null) medicalDevice.setReport(this);
}
/**
* Gets the medical devices.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
public List<MedicalDevice> getMedicalDevices() {
return lazyListHelper.getLazyList(MedicalDevice.class);
}
/**
* Adds the radiation intervention.
*
* @param radiationIntervention the radiation intervention
*/
public void addRadiationIntervention(RadiationIntervention radiationIntervention) {
getRadiationInterventionsInternal().add(radiationIntervention);
if (radiationIntervention != null) radiationIntervention.setReport(this);
}
/**
* Gets the radiation interventions.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
public List<RadiationIntervention> getRadiationInterventions() {
return lazyListHelper.getLazyList(RadiationIntervention.class);
}
/**
* Adds the surgery intervention.
*
* @param surgeryIntervention the surgery intervention
*/
public void addSurgeryIntervention(SurgeryIntervention surgeryIntervention) {
getSurgeryInterventionsInternal().add(surgeryIntervention);
if (surgeryIntervention != null) surgeryIntervention.setReport(this);
}
public void addBehavioralIntervention(BehavioralIntervention i) {
getBehavioralInterventionsInternal().add(i);
if (i != null) i.setReport(this);
}
public void addBilogicalIntervention(BiologicalIntervention i) {
getBiologicalInterventionsInternal().add(i);
if (i != null) i.setReport(this);
}
public void addGeneticIntervention(GeneticIntervention i) {
getGeneticInterventionsInternal().add(i);
if (i != null) i.setReport(this);
}
public void addDietarySupplementalIntervention(DietarySupplementIntervention i) {
getDietarySupplementInterventionsInternal().add(i);
if (i != null) i.setReport(this);
}
public void addOtherAEIntervention(OtherAEIntervention i) {
getOtherAEInterventionsInternal().add(i);
if (i != null) i.setReport(this);
}
/**
* Gets the surgery interventions.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
public List<SurgeryIntervention> getSurgeryInterventions() {
return lazyListHelper.getLazyList(SurgeryIntervention.class);
}
@Transient
public List<BehavioralIntervention> getBehavioralInterventions() {
return lazyListHelper.getLazyList(BehavioralIntervention.class);
}
@Transient
public List<BiologicalIntervention> getBiologicalInterventions() {
return lazyListHelper.getLazyList(BiologicalIntervention.class);
}
@Transient
public List<GeneticIntervention> getGeneticInterventions() {
return lazyListHelper.getLazyList(GeneticIntervention.class);
}
@Transient
public List<DietarySupplementIntervention> getDietaryInterventions() {
return lazyListHelper.getLazyList(DietarySupplementIntervention.class);
}
@Transient
public List<OtherAEIntervention> getOtherAEInterventions() {
return lazyListHelper.getLazyList(OtherAEIntervention.class);
}
/**
* Adds the concomitant medication.
*
* @param concomitantMedication the concomitant medication
*/
public void addConcomitantMedication(ConcomitantMedication concomitantMedication) {
getConcomitantMedicationsInternal().add(concomitantMedication);
if (concomitantMedication != null) concomitantMedication.setReport(this);
}
/**
* Gets the concomitant medications.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
public List<ConcomitantMedication> getConcomitantMedications() {
return lazyListHelper.getLazyList(ConcomitantMedication.class);
}
/**
* Adds the sae report pre existing condition.
*
* @param sAEReportPreExistingCondition the s ae report pre existing condition
*/
public void addSaeReportPreExistingCondition(SAEReportPreExistingCondition sAEReportPreExistingCondition) {
getSaeReportPreExistingConditionsInternal().add(sAEReportPreExistingCondition);
if (sAEReportPreExistingCondition != null) sAEReportPreExistingCondition.setReport(this);
}
/**
* Gets the sae report pre existing conditions.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
// @UniqueObjectInCollection(message = "Duplicate pre existing condition")
public List<SAEReportPreExistingCondition> getSaeReportPreExistingConditions() {
return lazyListHelper.getLazyList(SAEReportPreExistingCondition.class);
}
/**
* Adds the sae report prior therapies.
*
* @param saeReportPriorTherapy the sae report prior therapy
*/
public void addSaeReportPriorTherapies(SAEReportPriorTherapy saeReportPriorTherapy) {
getSaeReportPriorTherapiesInternal().add(saeReportPriorTherapy);
if (saeReportPriorTherapy != null) saeReportPriorTherapy.setReport(this);
}
/**
* Gets the sae report prior therapies.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
@UniqueObjectInCollection(message = "Duplicate prior therapy")
public List<SAEReportPriorTherapy> getSaeReportPriorTherapies() {
return lazyListHelper.getLazyList(SAEReportPriorTherapy.class);
}
/**
* Adds the other cause.
*
* @param otherCause the other cause
*/
public void addOtherCause(OtherCause otherCause) {
getOtherCausesInternal().add(otherCause);
if (otherCause != null) otherCause.setReport(this);
}
/**
* Gets the other causes.
*
* @return a wrapped list which will never throw an {@link IndexOutOfBoundsException}
*/
@Transient
@UniqueObjectInCollection(message = "Duplicate other cause")
public List<OtherCause> getOtherCauses() {
return lazyListHelper.getLazyList(OtherCause.class);
}
////// BEAN PROPERTIES
/**
* Gets the assignment.
*
* @return the assignment
*/
@Transient
public StudyParticipantAssignment getAssignment() {
return getReportingPeriod().getAssignment();
}
/**
* Sets the assignment.
*
* @param assignment the new assignment
*/
public void setAssignment(StudyParticipantAssignment assignment) {
this.reportingPeriod.setAssignment(assignment);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the adverse events internal.
*
* @return the adverse events internal
*/
@OneToMany
@JoinColumn(name = "report_id", nullable = true)
@IndexColumn(name = "list_index", nullable = false)
@Cascade(value = {
// Manually-managing PERSIST cascades due to cascade ordering issue
CascadeType.DELETE, CascadeType.DETACH, CascadeType.LOCK, CascadeType.MERGE,
CascadeType.REFRESH})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<AdverseEvent> getAdverseEventsInternal() {
return lazyListHelper.getInternalList(AdverseEvent.class);
}
/**
* Sets the adverse events internal.
*
* @param adverseEvents the new adverse events internal
*/
@SuppressWarnings("unchecked")
protected void setAdverseEventsInternal(List<AdverseEvent> adverseEvents) {
lazyListHelper.setInternalList(AdverseEvent.class, adverseEvents);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the labs internal.
*
* @return the labs internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<Lab> getLabsInternal() {
return lazyListHelper.getInternalList(Lab.class);
}
/**
* Sets the labs internal.
*
* @param labsInternal the new labs internal
*/
protected void setLabsInternal(List<Lab> labsInternal) {
lazyListHelper.setInternalList(Lab.class, labsInternal);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the medical devices internal.
*
* @return the medical devices internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<MedicalDevice> getMedicalDevicesInternal() {
return lazyListHelper.getInternalList(MedicalDevice.class);
}
/**
* Sets the medical devices internal.
*
* @param medicalDevicesInternal the new medical devices internal
*/
protected void setMedicalDevicesInternal(List<MedicalDevice> medicalDevicesInternal) {
lazyListHelper.setInternalList(MedicalDevice.class, medicalDevicesInternal);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the radiation interventions internal.
*
* @return the radiation interventions internal
*/
@OneToMany(orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<RadiationIntervention> getRadiationInterventionsInternal() {
return lazyListHelper.getInternalList(RadiationIntervention.class);
}
/**
* Sets the radiation interventions internal.
*
* @param radiationInterventionsInternal the new radiation interventions internal
*/
protected void setRadiationInterventionsInternal(List<RadiationIntervention> radiationInterventionsInternal) {
lazyListHelper.setInternalList(RadiationIntervention.class, radiationInterventionsInternal);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the surgery interventions internal.
*
* @return the surgery interventions internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<SurgeryIntervention> getSurgeryInterventionsInternal() {
return lazyListHelper.getInternalList(SurgeryIntervention.class);
}
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<BehavioralIntervention> getBehavioralInterventionsInternal() {
return lazyListHelper.getInternalList(BehavioralIntervention.class);
}
@OneToMany(orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<BiologicalIntervention> getBiologicalInterventionsInternal() {
return lazyListHelper.getInternalList(BiologicalIntervention.class);
}
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<GeneticIntervention> getGeneticInterventionsInternal() {
return lazyListHelper.getInternalList(GeneticIntervention.class);
}
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<DietarySupplementIntervention> getDietarySupplementInterventionsInternal() {
return lazyListHelper.getInternalList(DietarySupplementIntervention.class);
}
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<OtherAEIntervention> getOtherAEInterventionsInternal() {
return lazyListHelper.getInternalList(OtherAEIntervention.class);
}
/**
* Sets the surgery interventions internal.
*
* @param surgeryInterventionsInternal the new surgery interventions internal
*/
protected void setSurgeryInterventionsInternal(List<SurgeryIntervention> surgeryInterventionsInternal) {
lazyListHelper.setInternalList(SurgeryIntervention.class, surgeryInterventionsInternal);
}
protected void setBehavioralInterventionsInternal(List<BehavioralIntervention> l) {
lazyListHelper.setInternalList(BehavioralIntervention.class, l);
}
protected void setBiologicalInterventionsInternal(List<BiologicalIntervention> l) {
lazyListHelper.setInternalList(BiologicalIntervention.class, l);
}
protected void setGeneticInterventionsInternal(List<GeneticIntervention> l) {
lazyListHelper.setInternalList(GeneticIntervention.class, l);
}
protected void setDietarySupplementInterventionsInternal(List<DietarySupplementIntervention> l) {
lazyListHelper.setInternalList(DietarySupplementIntervention.class, l);
}
protected void setOtherAEInterventionsInternal(List<OtherAEIntervention> l) {
lazyListHelper.setInternalList(OtherAEIntervention.class, l);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the concomitant medications internal.
*
* @return the concomitant medications internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<ConcomitantMedication> getConcomitantMedicationsInternal() {
return lazyListHelper.getInternalList(ConcomitantMedication.class);
}
/**
* Sets the concomitant medications internal.
*
* @param concomitantMedicationsInternal the new concomitant medications internal
*/
protected void setConcomitantMedicationsInternal(List<ConcomitantMedication> concomitantMedicationsInternal) {
lazyListHelper.setInternalList(ConcomitantMedication.class, concomitantMedicationsInternal);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the sae report pre existing conditions internal.
*
* @return the sae report pre existing conditions internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<SAEReportPreExistingCondition> getSaeReportPreExistingConditionsInternal() {
return lazyListHelper.getInternalList(SAEReportPreExistingCondition.class);
}
/**
* Sets the sae report pre existing conditions internal.
*
* @param saeReportPreExistingConditionInternal the new sae report pre existing conditions internal
*/
protected void setSaeReportPreExistingConditionsInternal(List<SAEReportPreExistingCondition> saeReportPreExistingConditionInternal) {
lazyListHelper.setInternalList(SAEReportPreExistingCondition.class, saeReportPreExistingConditionInternal);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the other causes internal.
*
* @return the other causes internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
protected List<OtherCause> getOtherCausesInternal() {
return lazyListHelper.getInternalList(OtherCause.class);
}
/**
* Sets the other causes internal.
*
* @param otherCausesInternal the new other causes internal
*/
protected void setOtherCausesInternal(List<OtherCause> otherCausesInternal) {
lazyListHelper.setInternalList(OtherCause.class, otherCausesInternal);
}
// This is annotated this way so that the IndexColumn will work with
// the bidirectional mapping. See section 2.4.6.2.3 of the hibernate annotations docs.
/**
* Gets the sae report prior therapies internal.
*
* @return the sae report prior therapies internal
*/
@OneToMany (orphanRemoval = true)
@JoinColumn(name = "report_id", nullable = false)
@IndexColumn(name = "list_index")
@Cascade(value = {CascadeType.ALL})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
public List<SAEReportPriorTherapy> getSaeReportPriorTherapiesInternal() {
return lazyListHelper.getInternalList(SAEReportPriorTherapy.class);
}
/**
* Sets the sae report prior therapies internal.
*
* @param saeReportPriorTherapiesInternal the new sae report prior therapies internal
*/
public void setSaeReportPriorTherapiesInternal(
List<SAEReportPriorTherapy> saeReportPriorTherapiesInternal) {
lazyListHelper.setInternalList(SAEReportPriorTherapy.class, saeReportPriorTherapiesInternal);
}
/**
* Gets the treatment information.
*
* @return the treatment information
*/
@OneToOne(fetch = FetchType.LAZY, mappedBy = "report", orphanRemoval = true)
@Cascade(value = {CascadeType.ALL})
public TreatmentInformation getTreatmentInformation() {
if (treatmentInformation == null) setTreatmentInformation(new TreatmentInformation());
return treatmentInformation;
}
/**
* Sets the treatment information.
*
* @param treatmentInformation the new treatment information
*/
public void setTreatmentInformation(TreatmentInformation treatmentInformation) {
this.treatmentInformation = treatmentInformation;
if (treatmentInformation != null) treatmentInformation.setReport(this);
}
/**
* Gets the additional information.
*
* @return the additional information
*/
@OneToOne(fetch = FetchType.LAZY, mappedBy = "report", orphanRemoval = true)
@Cascade(value = {CascadeType.ALL})
public AdditionalInformation getAdditionalInformation() {
if (additionalInformation == null) setAdditionalInformation(new AdditionalInformation());
return additionalInformation;
}
/**
* Sets the additional information.
*
* @param additionalInformation the new additional information
*/
public void setAdditionalInformation(AdditionalInformation additionalInformation) {
this.additionalInformation = additionalInformation;
if (additionalInformation != null) additionalInformation.setReport(this);
}
/**
* Gets the response description.
*
* @return the response description
*/
@OneToOne(fetch = FetchType.LAZY, mappedBy = "report", orphanRemoval = true)
@Cascade(value = {CascadeType.ALL})
public AdverseEventResponseDescription getResponseDescription() {
if (responseDescription == null) setResponseDescription(new AdverseEventResponseDescription());
return responseDescription;
}
/**
* Sets the response description.
*
* @param responseDescription the new response description
*/
public void setResponseDescription(AdverseEventResponseDescription responseDescription) {
this.responseDescription = responseDescription;
if (responseDescription != null) responseDescription.setReport(this);
}
// non-total cascade allows us to skip saving if the reporter hasn't been filled in yet
/**
* Gets the reporter.
*
* @return the reporter
*/
@OneToOne(mappedBy = "expeditedReport", fetch=FetchType.LAZY)
@Cascade(value = {CascadeType.DELETE, CascadeType.DETACH, CascadeType.LOCK, CascadeType.REMOVE})
public Reporter getReporter() {
return reporter;
}
/**
* Sets the reporter.
*
* @param reporter the new reporter
*/
public void setReporter(Reporter reporter) {
this.reporter = reporter;
if (reporter != null) reporter.setExpeditedReport(this);
}
// non-total cascade allows us to skip saving if the physician hasn't been filled in yet
/**
* Gets the physician.
*
* @return the physician
*/
@OneToOne(mappedBy = "expeditedReport", fetch=FetchType.LAZY)
@Cascade(value = {CascadeType.DELETE, CascadeType.DETACH, CascadeType.LOCK, CascadeType.REMOVE, CascadeType.MERGE})
public Physician getPhysician() {
return physician;
}
/**
* Sets the physician.
*
* @param physician the new physician
*/
public void setPhysician(Physician physician) {
this.physician = physician;
if (physician != null) physician.setExpeditedReport(this);
}
/**
* Gets the disease history.
*
* @return the disease history
*/
@OneToOne(mappedBy = "report", fetch=FetchType.LAZY)
@Cascade(value = {CascadeType.ALL})
public DiseaseHistory getDiseaseHistory() {
if (diseaseHistory == null) setDiseaseHistory(new DiseaseHistory());
return diseaseHistory;
}
/**
* Sets the disease history.
*
* @param diseaseHistory the new disease history
*/
public void setDiseaseHistory(DiseaseHistory diseaseHistory) {
this.diseaseHistory = diseaseHistory;
if (diseaseHistory != null) diseaseHistory.setReport(this);
}
/**
* Gets the participant history.
*
* @return the participant history
*/
@OneToOne(mappedBy = "report", fetch=FetchType.LAZY, orphanRemoval = true)
@Cascade(value = {CascadeType.ALL })
public ParticipantHistory getParticipantHistory() {
if (participantHistory == null) setParticipantHistory(new ParticipantHistory());
return participantHistory;
}
/**
* Sets the participant history.
*
* @param participantHistory the new participant history
*/
public void setParticipantHistory(ParticipantHistory participantHistory) {
this.participantHistory = participantHistory;
if (participantHistory != null) participantHistory.setReport(this);
}
/**
* Gets the reports.
*
* @return the reports
*/
@OneToMany(fetch = FetchType.LAZY, mappedBy = "aeReport")
@Cascade(value = {CascadeType.DELETE, CascadeType.DETACH,
CascadeType.LOCK, CascadeType.REMOVE})
@Fetch(value = org.hibernate.annotations.FetchMode.SUBSELECT)
// Manually manage update-style reassociates and saves
public List<Report> getReports() {
if (reports == null) reports = new ArrayList<Report>();
return reports;
}
/**
* True,when at least one Report is active.
*
* @return true, if is active
*/
@Transient
public boolean isActive(){
for(Report report : getReports()){
if(report.isActive()) return true;
}
return false;
}
/**
* This method returns all the reports that are not in {@link ReportStatus}.WITHDRAWN or {@link ReportStatus}.REPLACED.
*
* @return the active reports
*/
@Transient
public List<Report> getActiveReports() {
List<Report> reports = getReports();
if (reports.isEmpty()) return reports;
List<Report> activeReports = new ArrayList<Report>();
for (Report report : reports) {
if (report.isActive()) activeReports.add(report);
}
return activeReports;
}
/**
* Returns all the pending reports, that are in PENDING.
*
* @return the pending reports
*/
@Transient
public List<Report> getPendingReports(){
List<Report> pendingReports = new ArrayList<Report>();
for(Report report: getReports()){
if(ReportStatus.PENDING.equals(report.getStatus())) pendingReports.add(report);
}
return pendingReports;
}
/**
* Tells whether an active report (ie. in PENDING, INPROCESS, FAILED) status, beloing to the same report definition is present.
*
* @param reportType the report type
* @return true, if is an active report present
*/
@Transient
public boolean isAnActiveReportPresent(ReportDefinition reportType){
for(Report report : getActiveReports()){
if(report.getReportDefinition().getId().equals(reportType.getId())) return true;
}
return false;
}
/**
* Lists the reports that are completed and is amendable.
*
* @return the list
*/
public List<Report> findCompletedAmendableReports(){
List<Report> completedReports = listReportsHavingStatus(ReportStatus.COMPLETED);
List<Report> amendableReports = new ArrayList<Report>();
for(Report report : completedReports){
if(report.isAmendable()) amendableReports.add(report);
}
return amendableReports;
}
/**
* Sets the reports.
*
* @param reports the new reports
*/
public void setReports(List<Report> reports) {
this.reports = reports;
}
/**
* Adds the report.
*
* @param report the report
*/
public void addReport(Report report) {
getReports().add(report);
report.setAeReport(this);
}
/**
* Gets the created at.
*
* @return the created at
*/
public Timestamp getCreatedAt() {
return createdAt;
}
/**
* Sets the created at.
*
* @param createdAt the new created at
*/
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
/**
* Gets the reporting period.
*
* @return the reporting period
*/
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "reporting_period_id")
@Cascade(value = {CascadeType.LOCK})
public AdverseEventReportingPeriod getReportingPeriod() {
return reportingPeriod;
}
/**
* Sets the reporting period.
*
* @param reportingPeriod the new reporting period
*/
public void setReportingPeriod(AdverseEventReportingPeriod reportingPeriod) {
this.reportingPeriod = reportingPeriod;
}
/**
* Gets the public identifier.
*
* @return the public identifier
*/
@Transient
public String getPublicIdentifier() {
String id = getAssignment().getStudySite().getOrganization().getNciInstituteCode() + "-" + getAssignment().getStudySite().getOrganization().getNciInstituteCode();
id = (id.indexOf("null") > -1) ? "None" : id;
return id;
}
/**
* Sets the public identifier.
*
* @param strId the new public identifier
*/
@Transient
public void setPublicIdentifier(String strId) {
}
/**
* Find phone numbers.
*
* @param role the role
* @return the list
*/
@Transient
List<String> findPhoneNumbers(String role) {
assert false : "Not implemented";
return null;
}
/**
* Find fax numbers.
*
* @param role the role
* @return the list
*/
@Transient
List<String> findFaxNumbers(String role) {
assert false : "Not implemented";
return null;
}
/**
* Gets the number of aes.
*
* @return the number of aes
*/
@Transient
public int getNumberOfAes() {
int count = (this.getAdverseEvents() != null) ? this.getAdverseEvents().size() : 0;
return count;
}
/**
* Gets the primary report.
*
* @return the primary report
*/
@Transient
public Report getPrimaryReport() {
return getReports().get(0);
}
/*
you should call this method only once
*/
/**
* Synchronize medical history from assignment to report.
*/
public void synchronizeMedicalHistoryFromAssignmentToReport() {
StudyParticipantAssignment assignment = getAssignment();
if (assignment == null) {
throw new CaaersSystemException("Must set assignment before calling synchronizeMedicalHistoryFromAssignmentToReport");
} else {
// synchronize from assignment to report
getParticipantHistory().setBaselinePerformanceStatus(assignment.getBaselinePerformance());
syncrhonizePriorTherapies();
syncrhonizePreExistingConditions();
syncrhonizeConcomitantMedications();
syncrhonizeDiseaseHistories();
}
}
/**
* synchronize prior therapies from assignment to report.
*/
private void syncrhonizePriorTherapies() {
if (getSaeReportPriorTherapies().isEmpty()) {
//copy only once
for (StudyParticipantPriorTherapy studyParticipantPriorTherapy : getAssignment().getPriorTherapies()) {
if(studyParticipantPriorTherapy.getPriorTherapy() == null) continue;
if(studyParticipantPriorTherapy.getPriorTherapy().isRetired()) continue;
SAEReportPriorTherapy priorTherapy = SAEReportPriorTherapy.createSAEReportPriorTherapy(studyParticipantPriorTherapy);
addSaeReportPriorTherapies(priorTherapy);
}
}
}
/**
* Syncrhonize pre existing conditions.
*/
private void syncrhonizePreExistingConditions() {
if (getSaeReportPreExistingConditions().isEmpty()) {
//copy only once
for (StudyParticipantPreExistingCondition studyParticipantPreExistingCondition : getAssignment().getPreExistingConditions()) {
if(studyParticipantPreExistingCondition.getPreExistingCondition().isRetired()) continue;
SAEReportPreExistingCondition saeReportPreExistingCondition = SAEReportPreExistingCondition.createSAEReportPreExistingCondition(studyParticipantPreExistingCondition);
addSaeReportPreExistingCondition(saeReportPreExistingCondition);
}
}
}
/**
* Syncrhonize concomitant medications.
*/
private void syncrhonizeConcomitantMedications() {
if (getConcomitantMedications().isEmpty()) {
//copy only once
for (StudyParticipantConcomitantMedication studyParticipantConcomitantMedication : getAssignment().getConcomitantMedications()) {
ConcomitantMedication saeReportConcomitantMedication = ConcomitantMedication.createConcomitantMedication(studyParticipantConcomitantMedication);
addConcomitantMedication(saeReportConcomitantMedication);
}
}
}
/**
* Syncrhonize disease histories.
*/
private void syncrhonizeDiseaseHistories() {
if ((getDiseaseHistory() == null) || (getDiseaseHistory() != null && getDiseaseHistory().getId() == null)) {
//copy only once
DiseaseHistory saeReportDiseaseHistory = DiseaseHistory.createDiseaseHistory(getAssignment().getDiseaseHistory());
setDiseaseHistory(saeReportDiseaseHistory);
}
}
/**
* This method returns true if any of the reports associated to this data-collection was submitted
* successfully.
*
* @return the checks for submitted amendable report
*/
@Transient
public Boolean getHasSubmittedAmendableReport(){
for(Report report : reports){
if(report.isSubmitted() && report.isAmendable()) return true;
}
return false;
}
/**
* This method returns true if the data-collection has atleast one amendable report. It returns false otherwise.
*
* @return the checks for amendable report
*/
@Transient
public Boolean getHasAmendableReport(){
Boolean hasAmendableReport = false;
for(Report report: reports){
if(report.getReportDefinition().getAmendable())
hasAmendableReport = true;
}
return hasAmendableReport;
}
/**
* Returns true if all of the active {@link Report} associated to this data collection, says attribution is requried.
*
* @return true, if is attribution required
*/
@Transient
public boolean isAttributionRequired(){
boolean attributionRequired = true;
int activeCount = 0;
for(Report report : getReports()){
if(!report.isActive()) continue;
activeCount++;
attributionRequired &= report.isAttributionRequired();
}
return activeCount > 0 && attributionRequired;
}
/**
* This method will update the signatures in all the adverse events associated to
* this expedited data collection.
*/
public void updateSignatureOfAdverseEvents(){
for(AdverseEvent ae: getAdverseEvents()){
ae.setSignature(ae.getCurrentSignature());
}
}
/**
* This method will return the earliest graded date, of adverse events.
*
* @return the earliest adverse event graded date
*/
@Transient
public Date getEarliestAdverseEventGradedDate(){
Date d = null;
for(AdverseEvent ae : getAdverseEvents()){
if(ae.getGradedDate() == null) continue;
if(d == null){
d = ae.getGradedDate();
}else{
d = (DateUtils.compateDateAndTime(ae.getGradedDate(), d) < 0) ? ae.getGradedDate() : d;
}
}
return d;
}
/**
* This method will set the graded date of adverse events to today.
*/
public void updateAdverseEventGradedDate(){
Date now = new Date();
for(AdverseEvent ae: getAdverseEvents()){
ae.setGradedDate(now);
}
}
/**
* This method will set the reported flag on adverse events.
*/
public void updateReportedFlagOnAdverseEvents(){
for(AdverseEvent ae: getAdverseEvents()){
ae.setReported(true);
}
}
/**
* This method will clear the reportedFlag, set on previously reported adverse events,
* which got modified.
*/
public void clearReportedFlagOnModifiedAdverseEvents(){
List<AdverseEvent> modifiedAdverseEvents = getModifiedAdverseEvents();
for(AdverseEvent modifiedAdverseEvent : modifiedAdverseEvents){
modifiedAdverseEvent.setReported(false);
}
}
/**
* This method will clear the post submission updated date on each of the adverse events.
*/
public void clearPostSubmissionUpdatedDate(){
for(AdverseEvent ae : getAdverseEvents()){
ae.setPostSubmissionUpdatedDate(null);
}
}
/**
* Checks if is physician sign off required.
*
* @return true, if is physician sign off required
*/
@Transient
public boolean isPhysicianSignOffRequired(){
boolean physicianSignOffRequired = false;
for(Report report: getReports()){
if(report.isActive())
physicianSignOffRequired |= report.getReportDefinition().getPhysicianSignOff();
}
return physicianSignOffRequired;
}
/**
* Gets the physician sign off.
*
* @return the physician sign off
*/
@Transient
public Boolean getPhysicianSignOff(){
Boolean physicianSignOff = true;
for(Report report: getReports()){
if(report.getPhysicianSignoff() != null)
physicianSignOff &= report.getPhysicianSignoff();
else
physicianSignOff = false;
}
return physicianSignOff;
}
/**
* Sets the physician sign off.
*
* @param physicianSignOff the new physician sign off
*/
@Transient
public void setPhysicianSignOff(Boolean physicianSignOff){
for(Report report: getReports())
report.setPhysicianSignoff(physicianSignOff);
}
/**
* List all the reports that were created manually.
* @return - all {@link Report}s whose manuallySelected flag is set.
*/
@Transient
public List<Report> getManuallySelectedReports(){
ArrayList<Report> manuallySelectedReports = new ArrayList<Report>();
for(Report report : getActiveReports()){
if(report.isManuallySelected()) manuallySelectedReports.add(report);
}
return manuallySelectedReports;
}
/**
* Lists out the report that completed, belonging to the same group and organization
* of the {@link ReportDefinition} param rd.
*
* @param rd the rd
* @return the list
*/
public List<Report> findReportsToAmmend(ReportDefinition rd){
List<Report> reports = listReportsHavingStatus(ReportStatus.COMPLETED);
List<Report> reportsToAmmend = new ArrayList<Report>();
//check if the reports are amendable and belongs to same organization & group.
for(Report report : reports){
ReportDefinition rdOther = report.getReportDefinition();
if(!rdOther.getAmendable()) continue;
if(!rdOther.getOrganization().getId().equals(rd.getOrganization().getId())) continue;
if(!rdOther.getGroup().getCode().equals(rd.getGroup().getCode())) continue;
reportsToAmmend.add(report);
}
return reportsToAmmend;
}
/**
* Find reports to witdraw.
*
* @param rd the rd
* @return the list
*/
public List<Report> findReportsToWitdraw(ReportDefinition rd){
List<Report> reports = listReportsHavingStatus(ReportStatus.PENDING, ReportStatus.FAILED, ReportStatus.INPROCESS);
List<Report> reportsToWitdraw = new ArrayList<Report>();
//check if they belong to same group/organization and rd is less than rdOther
for(Report report : reports){
ReportDefinition rdOther = report.getReportDefinition();
if(rdOther.getId().equals(rd.getId())) continue;
if(!rdOther.getOrganization().getId().equals(rd.getOrganization().getId())) continue;
if(!rdOther.getGroup().getCode().equals(rd.getGroup().getCode())) continue;
// int delta = rd.compareTo(rdOther);
// if( delta < 0) continue;
reportsToWitdraw.add(report);
}
return reportsToWitdraw;
}
/**
* Find reports to edit.
*
* @param rd the rd
* @return the list
*/
public List<Report> findReportsToEdit(ReportDefinition rd){
List<Report> reports = listReportsHavingStatus(ReportStatus.PENDING, ReportStatus.FAILED, ReportStatus.INPROCESS);
List<Report> reportsToEdit = new ArrayList<Report>();
//check if they belong to the same report definition.
for(Report report :reports){
if(report.getReportDefinition().getId().equals(rd.getId())){
reportsToEdit.add(report);
}
}
return reportsToEdit;
}
/**
* This method will find the recently amended report, that belongs to the same group and organization.
*
* @param rd the rd
* @return the report
*/
public Report findLastAmendedReport(ReportDefinition rd){
List<Report> reports = listReportsHavingStatus(ReportStatus.AMENDED);
Report theReport = null;
for(Report report : reports){
if(report.isOfSameOrganizationAndType(rd)){
if(theReport == null){
theReport = report;
}else{
if(DateUtils.compateDateAndTime(theReport.getAmendedOn(), report.getAmendedOn()) < 0){
theReport = report;
}
}
}
}
return theReport;
}
/**
* The report that is instantiated last, and is belonging to same organization and type.
*
* @param rd the rd
* @return the report
*/
public Report findLastSubmittedReport(ReportDefinition rd){
List<Report> reports = listReportsHavingStatus(ReportStatus.AMENDED, ReportStatus.COMPLETED);
Report theReport = null;
for(Report report : reports){
if(report.isOfSameOrganizationAndType(rd)){
if(theReport == null){
theReport = report;
}else{
if(DateUtils.compateDateAndTime(theReport.getSubmittedOn(), report.getSubmittedOn()) < 0){
theReport = report;
}
}
}
}
return theReport;
}
/**
* List reports having status.
*
* @param statuses the statuses
* @return the list
*/
public List<Report> listReportsHavingStatus(ReportStatus... statuses){
List<Report> reports = new ArrayList<Report>();
for(Report report : getReports()){
if(report.isHavingStatus(statuses)) reports.add(report);
}
return reports;
}
/**
* Will return true, if there is an organization of same group and type is already instantiated
* on this expedited report.
*
* @param rd the rd
* @return true, if successful
*/
public boolean hasExistingReportsOfSameOrganizationAndType(ReportDefinition rd){
for(Report report : getReports()){
if(report.isOfSameOrganizationAndType(rd)) return true;
}
return false;
}
/**
* This method will return the AdverseEvent that is associated with this data collection, identified by ID.
*
* @param id the id
* @return the adverse event
*/
public AdverseEvent findAdverseEventById(Integer id){
for(AdverseEvent ae : getAdverseEvents()){
if(ae.getId().equals(id)) return ae;
}
return null;
}
/**
* This method will return the Report associated to this data collection, identified by ID.
*
* @param id the id
* @return the report
*/
public Report findReportById(Integer id){
for(Report report : getReports()){
if(report.getId().equals(id)) return report;
}
return null;
}
/**
* This method returns is used to determine if there are any active reports which are in a workflow.
*
* @return boolean
*/
public boolean hasWorkflowOnActiveReports(){
boolean hasWorkflowOnActiveReports = false;
for(Report r: getActiveReports())
if(r.getWorkflowId() != null)
hasWorkflowOnActiveReports = true;
return hasWorkflowOnActiveReports;
}
/**
* Will create other cause from PreExistingCondition.
*/
public void autoGenerateOtherCauses(){
for(SAEReportPreExistingCondition saePreCondition : getSaeReportPreExistingConditions()){
if(saePreCondition.getLinkedToOtherCause()) continue; //already linked to a cause.
String preConditionName = saePreCondition.getName();
if(preConditionName == null) continue;
OtherCause otherCause = findOtherCauseByCause(preConditionName);
if(otherCause == null){
addOtherCause(new OtherCause(preConditionName));
saePreCondition.setLinkedToOtherCause(true);
}
}
}
/**
* Will return the OtherCause matching the cause.
* @param cause - The cause to find.
* @return OtherCause if found, otherwise null.
*/
private OtherCause findOtherCauseByCause(String cause){
for(OtherCause otherCause : getOtherCauses()) {
String otherCauseText = otherCause.getText();
if(StringUtils.equals(cause, otherCauseText)) return otherCause;
}
return null;
}
public boolean removeOtherCause(String cause){
OtherCause otherCause = findOtherCauseByCause(cause);
if(otherCause != null) return getOtherCauses().remove(otherCause);
return false;
}
}
|
package gov.nih.nci.cagrid.gts.service.globus.resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.axis.MessageContext;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.mds.servicegroup.client.ServiceGroupRegistrationParameters;
import org.globus.wsrf.Constants;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceContext;
import org.globus.wsrf.ResourceContextException;
import org.globus.wsrf.ResourceProperties;
import org.globus.wsrf.ResourcePropertySet;
import org.globus.wsrf.config.ContainerConfig;
import org.globus.wsrf.container.ServiceHost;
import org.globus.wsrf.impl.SimpleResourcePropertySet;
import org.globus.wsrf.impl.servicegroup.client.ServiceGroupRegistrationClient;
import org.globus.wsrf.utils.AddressingUtils;
import commonj.timers.Timer;
public class BaseResource implements Resource, ResourceProperties {
static final Log logger = LogFactory.getLog(BaseResource.class);
/** Stores the ResourceProperties of this service */
private ResourcePropertySet propSet;
//this can be used to cancel the registration renewal
private Timer registrationTimer;
private MetadataConfiguration configuration;
private URL baseURL;
//Define the metadata resource properties
// initializes the resource
public void initialize() throws Exception {
// create the resource property set
this.propSet = new SimpleResourcePropertySet(ResourceConstants.RESOURCE_PROPERY_SET);
// this loads the metadata from XML files
populateMetadata();
// now add the metadata as resource properties
// register the service to the index sevice
refreshRegistration(true);
}
/**
* This checks the configuration file, and attempts to register to the
* IndexService if shouldPerformRegistration==true. It will first read the
* current container URL, and compare it against the saved value. If the
* value exists, it will only try to reregister if the values are different.
* This exists to handle fixing the registration URL which may be incorrect
* during initialization, then later corrected during invocation. The
* existence of baseURL does not imply successful registration (a non-null
* registrationTimer does). We will only attempt to reregister when the URL
* changes (to prevent attempting registration with each invocation if there
* is a configuration problem).
*/
public void refreshRegistration(boolean forceRefresh) {
if (getConfiguration().shouldPerformRegistration()) {
URL currentContainerURL = null;
try {
currentContainerURL = ServiceHost.getBaseURL();
} catch (IOException e) {
logger.error("Unable to determine container's URL! Skipping registration.");
return;
}
if (this.baseURL != null) {
// we've tried to register before (or we are being forced to
// retry)
// do a string comparison as we don't want to do DNS lookups
// for comparison
if (forceRefresh || !this.baseURL.toExternalForm().equals(currentContainerURL.toExternalForm())) {
// we've tried to register before, and we have a different
// URL now.. so cancel the old registration (if it exists),
// and try to redo it.
if (registrationTimer != null) {
registrationTimer.cancel();
}
// save the new value
this.baseURL = currentContainerURL;
logger.info("Refreshing existing registration [container URL=" + this.baseURL + "].");
} else {
// URLs are the same (and we weren't forced), so don't try
// to reregister
return;
}
} else {
// we've never saved the baseURL (and therefore haven't tried to
// register)
this.baseURL = currentContainerURL;
logger.info("Attempting registration for the first time[container URL=" + this.baseURL + "].");
}
// register with the index service
ResourceContext ctx;
try {
MessageContext msgContext = MessageContext.getCurrentContext();
if (msgContext == null) {
logger.error("Unable to determine message context!");
return;
}
ctx = ResourceContext.getResourceContext(msgContext);
} catch (ResourceContextException e) {
logger.error("Could not get ResourceContext: " + e);
return;
}
EndpointReferenceType epr;
try {
// since this is a singleton, pretty sure we dont't want to
// register the key (allows multiple instances of same service
// on successive restarts)
// epr = AddressingUtils.createEndpointReference(ctx, key);
epr = AddressingUtils.createEndpointReference(ctx, null);
} catch (Exception e) {
logger.error("Could not form EPR: " + e);
return;
}
try {
// This is how registration parameters are set (read from
// template)
File registrationFile = new File(ContainerConfig.getBaseDirectory() + File.separator
+ getConfiguration().getRegistrationTemplateFile());
if (registrationFile.exists() && registrationFile.canRead()) {
logger.debug("Loading registration information from:" + registrationFile);
ServiceGroupRegistrationParameters params = ServiceGroupRegistrationClient
.readParams(registrationFile.getAbsolutePath());
// set our service's EPR as the registrant
params.setRegistrantEPR(epr);
ServiceGroupRegistrationClient client = new ServiceGroupRegistrationClient();
// apply the registration params to the client
registrationTimer = client.register(params);
} else {
logger.error("Unable to read registration file:" + registrationFile);
}
} catch (Exception e) {
logger.error("Exception when trying to register service (" + epr + "): " + e);
}
} else {
logger.info("Skipping registration.");
}
}
private void populateMetadata() {
}
public MetadataConfiguration getConfiguration() {
if (this.configuration != null) {
return this.configuration;
}
MessageContext ctx = MessageContext.getCurrentContext();
String servicePath = ctx.getTargetService();
String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
logger.debug("Will read configuration from jndi name: " + jndiName);
try {
Context initialContext = new InitialContext();
this.configuration = (MetadataConfiguration) initialContext.lookup(jndiName);
} catch (Exception e) {
logger.error("when performing JNDI lookup for " + jndiName + ": " + e);
}
return this.configuration;
}
public ResourcePropertySet getResourcePropertySet() {
return propSet;
}
}
|
package gov.nih.nci.cagrid.portal.search;
import gov.nih.nci.cagrid.portal.dao.PersonDao;
import gov.nih.nci.cagrid.portal.dao.PortalUserDao;
import gov.nih.nci.cagrid.portal.dao.catalog.GridServiceEndPointCatalogEntryDao;
import gov.nih.nci.cagrid.portal.dao.catalog.InstitutionCatalogEntryDao;
import gov.nih.nci.cagrid.portal.dao.catalog.PersonCatalogEntryDao;
import gov.nih.nci.cagrid.portal.domain.GridService;
import gov.nih.nci.cagrid.portal.domain.Participant;
import gov.nih.nci.cagrid.portal.domain.Person;
import gov.nih.nci.cagrid.portal.domain.catalog.PersonCatalogEntry;
/**
* User: kherm
*
* @author kherm manav.kher@semanticbits.com
*/
public class PortalDaoAspectTest extends PortalDaoAspectTestBase {
public void testDelete() {
PersonCatalogEntry pCE = new PersonCatalogEntry();
PersonCatalogEntryDao pCEDao = (PersonCatalogEntryDao) getApplicationContext().getBean("personCatalogEntryDao");
pCEDao.save(pCE);
MockHttpClient.assertJustRan();
pCEDao.delete(pCE);
}
// public void testPersonCEAspect() {
// PersonCatalogEntryDao pCEDao = (PersonCatalogEntryDao) getApplicationContext().getBean("personCatalogEntryDao");
// pCEDao.createCatalogAbout(new PortalUser());
public void testNonCEDao() throws Exception {
Person p = new Person();
PersonDao cEDao = (PersonDao) getApplicationContext().getBean("personDao");
cEDao.save(p);
assertFalse("Solr HTTP interface should not be called for non CatalogEntry DAO", MockHttpClient.assertJustRan());
MockHttpClient httpClient = (MockHttpClient) getApplicationContext().getBean("defaultHttpClient");
httpClient.executeMethod(null);
}
public void testGSCEAspect() {
GridServiceEndPointCatalogEntryDao cEDao = (GridServiceEndPointCatalogEntryDao) getApplicationContext().getBean("gridServiceEndPointCatalogEntryDao");
cEDao.createCatalogAbout(new GridService());
}
public void testInstCEAspect() {
InstitutionCatalogEntryDao cEDao = (InstitutionCatalogEntryDao) getApplicationContext().getBean("institutionCatalogEntryDao");
cEDao.createCatalogAbout(new Participant());
}
@Override
protected void onTearDown() throws Exception {
super.onTearDown(); //To change body of overridden methods use File | Settings | File Templates.
assertTrue("Solr HTTP interface was not called", MockHttpClient.assertJustRan());
}
public PersonCatalogEntryDao getPersonCatalogEntryDao() {
return personCatalogEntryDao;
}
public void setPersonCatalogEntryDao(PersonCatalogEntryDao personCatalogEntryDao) {
this.personCatalogEntryDao = personCatalogEntryDao;
}
public PortalUserDao getPortalUserDao() {
return portalUserDao;
}
public void setPortalUserDao(PortalUserDao portalUserDao) {
this.portalUserDao = portalUserDao;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.